Decompiled source of BepInExPack SlipSkid v6.0.697
BepInExPack\BepInEx\core\0Harmony.dll
Decompiled 2 months ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Security; using System.Security.Cryptography; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using HarmonyLib.Internal.Patching; using HarmonyLib.Internal.RuntimeFixes; using HarmonyLib.Internal.Util; using HarmonyLib.Public.Patching; using HarmonyLib.Tools; using JetBrains.Annotations; using Mono.Cecil; using Mono.Cecil.Cil; using Mono.Collections.Generic; using MonoMod.Cil; using MonoMod.RuntimeDetour; using MonoMod.Utils; using MonoMod.Utils.Cil; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: ComVisible(false)] [assembly: InternalsVisibleTo("HarmonyTests")] [assembly: InternalsVisibleTo("MonoMod.Utils.Cil.ILGeneratorProxy")] [assembly: Guid("69aee16a-b6e7-4642-8081-3928b32455df")] [assembly: AssemblyCompany("BepInEx")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © BepInEx 2022")] [assembly: AssemblyDescription("A library for patching, replacing and decorating .NET and Mono methods during runtime powered by MonoMod.")] [assembly: AssemblyFileVersion("2.10.2.0")] [assembly: AssemblyInformationalVersion("2.10.2")] [assembly: AssemblyProduct("HarmonyX")] [assembly: AssemblyTitle("0Harmony")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("2.10.2.0")] [module: UnverifiableCode] namespace System { internal struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 first, T2 second) { Item1 = first; Item2 = second; } } internal struct ValueTuple<T1, T2, T3> { public T1 Item1; public T2 Item2; public T3 Item3; public ValueTuple(T1 first, T2 second, T3 third) { Item1 = first; Item2 = second; Item3 = third; } } } namespace JetBrains.Annotations { [AttributeUsage(AttributeTargets.All)] internal sealed class UsedImplicitlyAttribute : Attribute { public ImplicitUseKindFlags UseKindFlags { get; } public ImplicitUseTargetFlags TargetFlags { get; } public UsedImplicitlyAttribute() : this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { } public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags) : this(useKindFlags, ImplicitUseTargetFlags.Default) { } public UsedImplicitlyAttribute(ImplicitUseTargetFlags targetFlags) : this(ImplicitUseKindFlags.Default, targetFlags) { } public UsedImplicitlyAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags) { UseKindFlags = useKindFlags; TargetFlags = targetFlags; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Parameter | AttributeTargets.GenericParameter)] internal sealed class MeansImplicitUseAttribute : Attribute { [UsedImplicitly] public ImplicitUseKindFlags UseKindFlags { get; } [UsedImplicitly] public ImplicitUseTargetFlags TargetFlags { get; } public MeansImplicitUseAttribute() : this(ImplicitUseKindFlags.Default, ImplicitUseTargetFlags.Default) { } public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags) : this(useKindFlags, ImplicitUseTargetFlags.Default) { } public MeansImplicitUseAttribute(ImplicitUseTargetFlags targetFlags) : this(ImplicitUseKindFlags.Default, targetFlags) { } public MeansImplicitUseAttribute(ImplicitUseKindFlags useKindFlags, ImplicitUseTargetFlags targetFlags) { UseKindFlags = useKindFlags; TargetFlags = targetFlags; } } [Flags] internal enum ImplicitUseKindFlags { Default = 7, Access = 1, Assign = 2, InstantiatedWithFixedConstructorSignature = 4, InstantiatedNoFixedConstructorSignature = 8 } [Flags] internal enum ImplicitUseTargetFlags { Default = 1, Itself = 1, Members = 2, WithInheritors = 4, WithMembers = 3 } } namespace HarmonyLib { public class DelegateTypeFactory { private class DelegateEntry { public CallingConvention? callingConvention; public Type delegateType; } private static int counter; private static readonly Dictionary<MethodInfo, List<DelegateEntry>> TypeCache = new Dictionary<MethodInfo, List<DelegateEntry>>(); private static readonly MethodBase CallingConvAttr = AccessTools.Constructor(typeof(UnmanagedFunctionPointerAttribute), new Type[1] { typeof(CallingConvention) }); public static readonly DelegateTypeFactory instance = new DelegateTypeFactory(); public Type CreateDelegateType(Type returnType, Type[] argTypes) { return CreateDelegateType(returnType, argTypes, null); } public Type CreateDelegateType(Type returnType, Type[] argTypes, CallingConvention? convention) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Expected O, but got Unknown //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Expected O, but got Unknown //IL_0127: Unknown result type (might be due to invalid IL or missing references) //IL_012c: Unknown result type (might be due to invalid IL or missing references) //IL_0134: Expected O, but got Unknown //IL_0157: Unknown result type (might be due to invalid IL or missing references) //IL_015d: Expected O, but got Unknown //IL_0174: Unknown result type (might be due to invalid IL or missing references) //IL_017a: Expected O, but got Unknown //IL_01a1: Unknown result type (might be due to invalid IL or missing references) //IL_01a6: Unknown result type (might be due to invalid IL or missing references) //IL_01af: 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_00f1: Unknown result type (might be due to invalid IL or missing references) counter++; AssemblyDefinition val = AssemblyDefinition.CreateAssembly(new AssemblyNameDefinition($"HarmonyDTFAssembly{counter}", new Version(1, 0)), $"HarmonyDTFModule{counter}", (ModuleKind)0); ModuleDefinition module = val.MainModule; TypeDefinition val2 = new TypeDefinition("", $"HarmonyDTFType{counter}", (TypeAttributes)257) { BaseType = module.ImportReference(typeof(MulticastDelegate)) }; module.Types.Add(val2); if (convention.HasValue) { CustomAttribute val3 = new CustomAttribute(module.ImportReference(CallingConvAttr)); val3.ConstructorArguments.Add(new CustomAttributeArgument(module.ImportReference(typeof(CallingConvention)), (object)convention.Value)); val2.CustomAttributes.Add(val3); } MethodDefinition val4 = new MethodDefinition(".ctor", (MethodAttributes)4230, module.ImportReference(typeof(void))) { ImplAttributes = (MethodImplAttributes)3 }; Extensions.AddRange<ParameterDefinition>(((MethodReference)val4).Parameters, (IEnumerable<ParameterDefinition>)(object)new ParameterDefinition[2] { new ParameterDefinition(module.ImportReference(typeof(object))), new ParameterDefinition(module.ImportReference(typeof(IntPtr))) }); val2.Methods.Add(val4); MethodDefinition val5 = new MethodDefinition("Invoke", (MethodAttributes)198, module.ImportReference(returnType)) { ImplAttributes = (MethodImplAttributes)3 }; Extensions.AddRange<ParameterDefinition>(((MethodReference)val5).Parameters, ((IEnumerable<Type>)argTypes).Select((Func<Type, ParameterDefinition>)((Type t) => new ParameterDefinition(module.ImportReference(t))))); val2.Methods.Add(val5); return ReflectionHelper.Load(val.MainModule).GetType($"HarmonyDTFType{counter}"); } public Type CreateDelegateType(MethodInfo method) { return CreateDelegateType(method, null); } public Type CreateDelegateType(MethodInfo method, CallingConvention? convention) { DelegateEntry delegateEntry; if (TypeCache.TryGetValue(method, out var value) && (delegateEntry = value.FirstOrDefault((DelegateEntry e) => e.callingConvention == convention)) != null) { return delegateEntry.delegateType; } if (value == null) { value = (TypeCache[method] = new List<DelegateEntry>()); } delegateEntry = new DelegateEntry { delegateType = CreateDelegateType(method.ReturnType, method.GetParameters().Types().ToArray(), convention), callingConvention = convention }; value.Add(delegateEntry); return delegateEntry.delegateType; } } [Obsolete("Use AccessTools.FieldRefAccess<T, S> for fields and AccessTools.MethodDelegate<Func<T, S>> for property getters")] public delegate S GetterHandler<in T, out S>(T source); [Obsolete("Use AccessTools.FieldRefAccess<T, S> for fields and AccessTools.MethodDelegate<Action<T, S>> for property setters")] public delegate void SetterHandler<in T, in S>(T source, S value); public delegate T InstantiationHandler<out T>(); public static class FastAccess { public static InstantiationHandler<T> CreateInstantiationHandler<T>() { //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) ConstructorInfo constructor = typeof(T).GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[0], null); if ((object)constructor == null) { throw new ApplicationException($"The type {typeof(T)} must declare an empty constructor (the constructor may be private, internal, protected, protected internal, or public)."); } DynamicMethodDefinition val = new DynamicMethodDefinition("InstantiateObject_" + typeof(T).Name, typeof(T), (Type[])null); ILGenerator iLGenerator = val.GetILGenerator(); iLGenerator.Emit(OpCodes.Newobj, constructor); iLGenerator.Emit(OpCodes.Ret); return (InstantiationHandler<T>)Extensions.CreateDelegate((MethodBase)val.Generate(), typeof(InstantiationHandler<T>)); } [Obsolete("Use AccessTools.MethodDelegate<Func<T, S>>(PropertyInfo.GetGetMethod(true))")] public static GetterHandler<T, S> CreateGetterHandler<T, S>(PropertyInfo propertyInfo) { MethodInfo getMethod = propertyInfo.GetGetMethod(nonPublic: true); DynamicMethodDefinition obj = CreateGetDynamicMethod<T, S>(propertyInfo.DeclaringType); ILGenerator iLGenerator = obj.GetILGenerator(); iLGenerator.Emit(OpCodes.Ldarg_0); iLGenerator.Emit(OpCodes.Call, getMethod); iLGenerator.Emit(OpCodes.Ret); return (GetterHandler<T, S>)Extensions.CreateDelegate((MethodBase)obj.Generate(), typeof(GetterHandler<T, S>)); } [Obsolete("Use AccessTools.FieldRefAccess<T, S>(fieldInfo)")] public static GetterHandler<T, S> CreateGetterHandler<T, S>(FieldInfo fieldInfo) { DynamicMethodDefinition obj = CreateGetDynamicMethod<T, S>(fieldInfo.DeclaringType); ILGenerator iLGenerator = obj.GetILGenerator(); iLGenerator.Emit(OpCodes.Ldarg_0); iLGenerator.Emit(OpCodes.Ldfld, fieldInfo); iLGenerator.Emit(OpCodes.Ret); return (GetterHandler<T, S>)Extensions.CreateDelegate((MethodBase)obj.Generate(), typeof(GetterHandler<T, S>)); } [Obsolete("Use AccessTools.FieldRefAccess<T, S>(name) for fields and AccessTools.MethodDelegate<Func<T, S>>(AccessTools.PropertyGetter(typeof(T), name)) for properties")] public static GetterHandler<T, S> CreateFieldGetter<T, S>(params string[] names) { foreach (string name in names) { FieldInfo field = typeof(T).GetField(name, AccessTools.all); if ((object)field != null) { return CreateGetterHandler<T, S>(field); } PropertyInfo property = typeof(T).GetProperty(name, AccessTools.all); if ((object)property != null) { return CreateGetterHandler<T, S>(property); } } return null; } [Obsolete("Use AccessTools.MethodDelegate<Action<T, S>>(PropertyInfo.GetSetMethod(true))")] public static SetterHandler<T, S> CreateSetterHandler<T, S>(PropertyInfo propertyInfo) { MethodInfo setMethod = propertyInfo.GetSetMethod(nonPublic: true); DynamicMethodDefinition obj = CreateSetDynamicMethod<T, S>(propertyInfo.DeclaringType); ILGenerator iLGenerator = obj.GetILGenerator(); iLGenerator.Emit(OpCodes.Ldarg_0); iLGenerator.Emit(OpCodes.Ldarg_1); iLGenerator.Emit(OpCodes.Call, setMethod); iLGenerator.Emit(OpCodes.Ret); return (SetterHandler<T, S>)Extensions.CreateDelegate((MethodBase)obj.Generate(), typeof(SetterHandler<T, S>)); } [Obsolete("Use AccessTools.FieldRefAccess<T, S>(fieldInfo)")] public static SetterHandler<T, S> CreateSetterHandler<T, S>(FieldInfo fieldInfo) { DynamicMethodDefinition obj = CreateSetDynamicMethod<T, S>(fieldInfo.DeclaringType); ILGenerator iLGenerator = obj.GetILGenerator(); iLGenerator.Emit(OpCodes.Ldarg_0); iLGenerator.Emit(OpCodes.Ldarg_1); iLGenerator.Emit(OpCodes.Stfld, fieldInfo); iLGenerator.Emit(OpCodes.Ret); return (SetterHandler<T, S>)Extensions.CreateDelegate((MethodBase)obj.Generate(), typeof(SetterHandler<T, S>)); } private static DynamicMethodDefinition CreateGetDynamicMethod<T, S>(Type type) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Expected O, but got Unknown return new DynamicMethodDefinition("DynamicGet_" + type.Name, typeof(S), new Type[1] { typeof(T) }); } private static DynamicMethodDefinition CreateSetDynamicMethod<T, S>(Type type) { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Expected O, but got Unknown return new DynamicMethodDefinition("DynamicSet_" + type.Name, typeof(void), new Type[2] { typeof(T), typeof(S) }); } } public delegate object FastInvokeHandler(object target, params object[] parameters); public static class MethodInvoker { public static FastInvokeHandler GetHandler(MethodInfo methodInfo, bool directBoxValueAccess = false) { //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Expected O, but got Unknown DynamicMethodDefinition val = new DynamicMethodDefinition("FastInvoke_" + methodInfo.Name + "_" + (directBoxValueAccess ? "direct" : "indirect"), typeof(object), new Type[2] { typeof(object), typeof(object[]) }); ILGenerator iLGenerator = val.GetILGenerator(); if (!methodInfo.IsStatic) { Emit(iLGenerator, OpCodes.Ldarg_0); EmitUnboxIfNeeded(iLGenerator, methodInfo.DeclaringType); } bool flag = true; ParameterInfo[] parameters = methodInfo.GetParameters(); for (int i = 0; i < parameters.Length; i++) { Type type = parameters[i].ParameterType; bool isByRef = type.IsByRef; if (isByRef) { type = type.GetElementType(); } bool isValueType = type.IsValueType; if (isByRef && isValueType && !directBoxValueAccess) { Emit(iLGenerator, OpCodes.Ldarg_1); EmitFastInt(iLGenerator, i); } Emit(iLGenerator, OpCodes.Ldarg_1); EmitFastInt(iLGenerator, i); if (isByRef && !isValueType) { Emit(iLGenerator, OpCodes.Ldelema, typeof(object)); continue; } Emit(iLGenerator, OpCodes.Ldelem_Ref); if (!isValueType) { continue; } if (!isByRef || !directBoxValueAccess) { Emit(iLGenerator, OpCodes.Unbox_Any, type); if (isByRef) { Emit(iLGenerator, OpCodes.Box, type); Emit(iLGenerator, OpCodes.Dup); if (flag) { flag = false; iLGenerator.DeclareLocal(typeof(object), pinned: false); } Emit(iLGenerator, OpCodes.Stloc_0); Emit(iLGenerator, OpCodes.Stelem_Ref); Emit(iLGenerator, OpCodes.Ldloc_0); Emit(iLGenerator, OpCodes.Unbox, type); } } else { Emit(iLGenerator, OpCodes.Unbox, type); } } if (methodInfo.IsStatic) { EmitCall(iLGenerator, OpCodes.Call, methodInfo); } else { EmitCall(iLGenerator, OpCodes.Callvirt, methodInfo); } if ((object)methodInfo.ReturnType == typeof(void)) { Emit(iLGenerator, OpCodes.Ldnull); } else { EmitBoxIfNeeded(iLGenerator, methodInfo.ReturnType); } Emit(iLGenerator, OpCodes.Ret); return (FastInvokeHandler)Extensions.CreateDelegate((MethodBase)val.Generate(), typeof(FastInvokeHandler)); } internal static void Emit(ILGenerator il, OpCode opcode) { il.Emit(opcode); } internal static void Emit(ILGenerator il, OpCode opcode, Type type) { il.Emit(opcode, type); } internal static void EmitCall(ILGenerator il, OpCode opcode, MethodInfo methodInfo) { il.EmitCall(opcode, methodInfo, null); } private static void EmitUnboxIfNeeded(ILGenerator il, Type type) { if (type.IsValueType) { Emit(il, OpCodes.Unbox_Any, type); } } private static void EmitBoxIfNeeded(ILGenerator il, Type type) { if (type.IsValueType) { Emit(il, OpCodes.Box, type); } } internal static void EmitFastInt(ILGenerator il, int value) { switch (value) { case -1: il.Emit(OpCodes.Ldc_I4_M1); return; case 0: il.Emit(OpCodes.Ldc_I4_0); return; case 1: il.Emit(OpCodes.Ldc_I4_1); return; case 2: il.Emit(OpCodes.Ldc_I4_2); return; case 3: il.Emit(OpCodes.Ldc_I4_3); return; case 4: il.Emit(OpCodes.Ldc_I4_4); return; case 5: il.Emit(OpCodes.Ldc_I4_5); return; case 6: il.Emit(OpCodes.Ldc_I4_6); return; case 7: il.Emit(OpCodes.Ldc_I4_7); return; case 8: il.Emit(OpCodes.Ldc_I4_8); return; } if (value > -129 && value < 128) { il.Emit(OpCodes.Ldc_I4_S, (sbyte)value); } else { il.Emit(OpCodes.Ldc_I4, value); } } } internal class AccessCache { internal enum MemberType { Any, Static, Instance } private const BindingFlags BasicFlags = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.SetField | BindingFlags.GetProperty | BindingFlags.SetProperty; private static readonly Dictionary<MemberType, BindingFlags> declaredOnlyBindingFlags = new Dictionary<MemberType, BindingFlags> { { MemberType.Any, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.SetField | BindingFlags.GetProperty | BindingFlags.SetProperty }, { MemberType.Instance, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.SetField | BindingFlags.GetProperty | BindingFlags.SetProperty }, { MemberType.Static, BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.SetField | BindingFlags.GetProperty | BindingFlags.SetProperty } }; private readonly Dictionary<Type, Dictionary<string, FieldInfo>> declaredFields = new Dictionary<Type, Dictionary<string, FieldInfo>>(); private readonly Dictionary<Type, Dictionary<string, PropertyInfo>> declaredProperties = new Dictionary<Type, Dictionary<string, PropertyInfo>>(); private readonly Dictionary<Type, Dictionary<string, Dictionary<int, MethodBase>>> declaredMethods = new Dictionary<Type, Dictionary<string, Dictionary<int, MethodBase>>>(); private readonly Dictionary<Type, Dictionary<string, FieldInfo>> inheritedFields = new Dictionary<Type, Dictionary<string, FieldInfo>>(); private readonly Dictionary<Type, Dictionary<string, PropertyInfo>> inheritedProperties = new Dictionary<Type, Dictionary<string, PropertyInfo>>(); private readonly Dictionary<Type, Dictionary<string, Dictionary<int, MethodBase>>> inheritedMethods = new Dictionary<Type, Dictionary<string, Dictionary<int, MethodBase>>>(); private static T Get<T>(Dictionary<Type, Dictionary<string, T>> dict, Type type, string name, Func<T> fetcher) { lock (dict) { if (!dict.TryGetValue(type, out var value)) { value = (dict[type] = new Dictionary<string, T>()); } if (!value.TryGetValue(name, out var value2)) { value2 = (value[name] = fetcher()); } return value2; } } private static T Get<T>(Dictionary<Type, Dictionary<string, Dictionary<int, T>>> dict, Type type, string name, Type[] arguments, Func<T> fetcher) { lock (dict) { if (!dict.TryGetValue(type, out var value)) { value = (dict[type] = new Dictionary<string, Dictionary<int, T>>()); } if (!value.TryGetValue(name, out var value2)) { value2 = (value[name] = new Dictionary<int, T>()); } int key = AccessTools.CombinedHashCode(arguments); if (!value2.TryGetValue(key, out var value3)) { value3 = (value2[key] = fetcher()); } return value3; } } internal FieldInfo GetFieldInfo(Type type, string name, MemberType memberType = MemberType.Any, bool declaredOnly = false) { FieldInfo fieldInfo = Get(declaredFields, type, name, () => type.GetField(name, declaredOnlyBindingFlags[memberType])); if ((object)fieldInfo == null && !declaredOnly) { fieldInfo = Get(inheritedFields, type, name, () => AccessTools.FindIncludingBaseTypes(type, (Type t) => t.GetField(name, AccessTools.all))); } return fieldInfo; } internal PropertyInfo GetPropertyInfo(Type type, string name, MemberType memberType = MemberType.Any, bool declaredOnly = false) { PropertyInfo propertyInfo = Get(declaredProperties, type, name, () => type.GetProperty(name, declaredOnlyBindingFlags[memberType])); if ((object)propertyInfo == null && !declaredOnly) { propertyInfo = Get(inheritedProperties, type, name, () => AccessTools.FindIncludingBaseTypes(type, (Type t) => t.GetProperty(name, AccessTools.all))); } return propertyInfo; } internal MethodBase GetMethodInfo(Type type, string name, Type[] arguments, MemberType memberType = MemberType.Any, bool declaredOnly = false) { MethodBase methodBase = Get(declaredMethods, type, name, arguments, () => type.GetMethod(name, declaredOnlyBindingFlags[memberType], null, arguments, null)); if ((object)methodBase == null && !declaredOnly) { methodBase = Get(inheritedMethods, type, name, arguments, () => AccessTools.Method(type, name, arguments)); } return methodBase; } } internal static class PatchArgumentExtensions { private static HarmonyArgument[] AllHarmonyArguments(object[] attributes) { return (from attr in attributes select (attr.GetType().Name != "HarmonyArgument") ? null : AccessTools.MakeDeepCopy<HarmonyArgument>(attr) into harg where harg != null select harg).ToArray(); } private static HarmonyArgument GetArgumentAttribute(this ParameterInfo parameter) { return AllHarmonyArguments(parameter.GetCustomAttributes(inherit: false)).FirstOrDefault(); } private static HarmonyArgument[] GetArgumentAttributes(this MethodInfo method) { if ((object)method == null || method is DynamicMethod) { return null; } return AllHarmonyArguments(method.GetCustomAttributes(inherit: false)); } private static HarmonyArgument[] GetArgumentAttributes(this Type type) { return AllHarmonyArguments(type.GetCustomAttributes(inherit: false)); } private static string GetOriginalArgumentName(this ParameterInfo parameter, string[] originalParameterNames) { HarmonyArgument argumentAttribute = parameter.GetArgumentAttribute(); if (argumentAttribute == null) { return null; } if (!string.IsNullOrEmpty(argumentAttribute.OriginalName)) { return argumentAttribute.OriginalName; } if (argumentAttribute.Index >= 0 && argumentAttribute.Index < originalParameterNames.Length) { return originalParameterNames[argumentAttribute.Index]; } return null; } private static string GetOriginalArgumentName(HarmonyArgument[] attributes, string name, string[] originalParameterNames) { if (((attributes != null && attributes.Length != 0) ? 1 : 0) <= (false ? 1 : 0)) { return null; } HarmonyArgument harmonyArgument = attributes.SingleOrDefault((HarmonyArgument p) => p.NewName == name); if (harmonyArgument == null) { return null; } if (!string.IsNullOrEmpty(harmonyArgument.OriginalName)) { return harmonyArgument.OriginalName; } if (originalParameterNames != null && harmonyArgument.Index >= 0 && harmonyArgument.Index < originalParameterNames.Length) { return originalParameterNames[harmonyArgument.Index]; } return null; } private static string GetOriginalArgumentName(this MethodInfo method, string[] originalParameterNames, string name) { string originalArgumentName = GetOriginalArgumentName(((object)method != null) ? method.GetArgumentAttributes() : null, name, originalParameterNames); if (originalArgumentName != null) { return originalArgumentName; } object attributes; if ((object)method == null) { attributes = null; } else { Type? declaringType = method.DeclaringType; attributes = (((object)declaringType != null) ? declaringType.GetArgumentAttributes() : null); } originalArgumentName = GetOriginalArgumentName((HarmonyArgument[])attributes, name, originalParameterNames); if (originalArgumentName != null) { return originalArgumentName; } return name; } internal static int GetArgumentIndex(this MethodInfo patch, string[] originalParameterNames, ParameterInfo patchParam) { if (patch is DynamicMethod) { return Array.IndexOf<string>(originalParameterNames, patchParam.Name); } string originalArgumentName = patchParam.GetOriginalArgumentName(originalParameterNames); if (originalArgumentName != null) { return Array.IndexOf(originalParameterNames, originalArgumentName); } originalArgumentName = patch.GetOriginalArgumentName(originalParameterNames, patchParam.Name); if (originalArgumentName != null) { return Array.IndexOf(originalParameterNames, originalArgumentName); } return -1; } } internal static class PatchFunctions { internal static List<MethodInfo> GetSortedPatchMethods(MethodBase original, Patch[] patches, bool debug) { return new PatchSorter(patches, debug).Sort(original); } internal static Patch[] GetSortedPatchMethodsAsPatches(MethodBase original, Patch[] patches, bool debug) { return new PatchSorter(patches, debug).SortAsPatches(original); } internal static MethodInfo UpdateWrapper(MethodBase original, PatchInfo patchInfo) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Expected O, but got Unknown MethodPatcher methodPatcher = original.GetMethodPatcher(); DynamicMethodDefinition val = methodPatcher.PrepareOriginal(); if (val != null) { ILContext ctx = new ILContext(val.Definition); HarmonyManipulator.Manipulate(original, patchInfo, ctx); } try { return methodPatcher.DetourTo((val != null) ? val.Generate() : null) as MethodInfo; } catch (Exception ex) { object body; if (val == null) { body = null; } else { MethodDefinition definition = val.Definition; body = ((definition != null) ? definition.Body : null); } throw HarmonyException.Create(ex, (MethodBody)body); } } internal static MethodInfo ReversePatch(HarmonyMethod standin, MethodBase original, MethodInfo postTranspiler, MethodInfo postManipulator) { //IL_0162: Unknown result type (might be due to invalid IL or missing references) //IL_0169: 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_017e: Expected O, but got Unknown //IL_0179: Unknown result type (might be due to invalid IL or missing references) //IL_017f: Expected O, but got Unknown if (standin == null) { throw new ArgumentNullException("standin"); } if ((object)standin.method == null) { throw new ArgumentNullException("standin", "standin.method is NULL"); } if (!standin.method.IsStatic) { throw new ArgumentException("standin", "standin.method is not static"); } bool debug = standin.debug.GetValueOrDefault(); List<MethodInfo> transpilers = new List<MethodInfo>(); List<MethodInfo> ilmanipulators = new List<MethodInfo>(); if (standin.reversePatchType == HarmonyReversePatchType.Snapshot) { Patches patchInfo = Harmony.GetPatchInfo(original); transpilers.AddRange(GetSortedPatchMethods(original, patchInfo.Transpilers.ToArray(), debug)); ilmanipulators.AddRange(GetSortedPatchMethods(original, patchInfo.ILManipulators.ToArray(), debug)); } if ((object)postTranspiler != null) { transpilers.Add(postTranspiler); } if ((object)postManipulator != null) { ilmanipulators.Add(postManipulator); } Logger.Log(Logger.LogChannel.Info, delegate { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("Reverse patching " + standin.method.FullDescription() + " with " + original.FullDescription()); PrintInfo(stringBuilder, transpilers, "Transpiler"); PrintInfo(stringBuilder, ilmanipulators, "Manipulators"); return stringBuilder.ToString(); }, debug); MethodBody patchBody = null; ILHook val = new ILHook((MethodBase)standin.method, (Manipulator)delegate(ILContext ctx) { //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_00f1: Unknown result type (might be due to invalid IL or missing references) //IL_00fb: Expected O, but got Unknown //IL_01e1: Unknown result type (might be due to invalid IL or missing references) //IL_01d4: Unknown result type (might be due to invalid IL or missing references) if (original is MethodInfo methodInfo2) { patchBody = ctx.Body; MethodPatcher methodPatcher = methodInfo2.GetMethodPatcher(); DynamicMethodDefinition val2 = methodPatcher.CopyOriginal(); if (val2 == null) { throw new NullReferenceException("Cannot reverse patch " + methodInfo2.FullDescription() + ": method patcher (" + methodPatcher.GetType().FullDescription() + ") can't copy original method body"); } ILManipulator iLManipulator = new ILManipulator(val2.Definition.Body, debug); ctx.Body.Variables.Clear(); Enumerator<VariableDefinition> enumerator2 = iLManipulator.Body.Variables.GetEnumerator(); try { while (enumerator2.MoveNext()) { VariableDefinition current2 = enumerator2.Current; ctx.Body.Variables.Add(new VariableDefinition(ctx.Module.ImportReference(((VariableReference)current2).VariableType))); } } finally { ((IDisposable)enumerator2).Dispose(); } foreach (MethodInfo item in transpilers) { iLManipulator.AddTranspiler(item); } iLManipulator.WriteTo(ctx.Body, standin.method); HarmonyManipulator.ApplyManipulators(ctx, original, ilmanipulators, null); Instruction val3 = null; foreach (Instruction item2 in ((IEnumerable<Instruction>)ctx.Instrs).Where((Instruction i) => i.OpCode == OpCodes.Ret)) { if (val3 == null) { val3 = ctx.IL.Create(OpCodes.Ret); } item2.OpCode = OpCodes.Br; item2.Operand = val3; } if (val3 != null) { ctx.IL.Append(val3); } Logger.Log(Logger.LogChannel.IL, () => "Generated reverse patcher (" + ((MemberReference)ctx.Method).FullName + "):\n" + ctx.Body.ToILDasmString(), debug); } }, new ILHookConfig { ManualApply = true }); try { val.Apply(); } catch (Exception ex) { throw HarmonyException.Create(ex, patchBody); } MethodInfo methodInfo = val.GetCurrentTarget() as MethodInfo; PatchTools.RememberObject(standin.method, methodInfo); return methodInfo; static void PrintInfo(StringBuilder sb, ICollection<MethodInfo> methods, string name) { if (methods.Count <= 0) { return; } sb.AppendLine(name + ":"); foreach (MethodInfo method in methods) { sb.AppendLine(" * " + method.FullDescription()); } } } internal static IEnumerable<CodeInstruction> ApplyTranspilers(MethodBase methodBase, ILGenerator generator, int maxTranspilers = 0) { MethodPatcher methodPatcher = methodBase.GetMethodPatcher(); DynamicMethodDefinition val = methodPatcher.CopyOriginal(); if (val == null) { throw new NullReferenceException("Cannot reverse patch " + methodBase.FullDescription() + ": method patcher (" + methodPatcher.GetType().FullDescription() + ") can't copy original method body"); } ILManipulator iLManipulator = new ILManipulator(val.Definition.Body, debug: false); PatchInfo patchInfo = methodBase.GetPatchInfo(); if (patchInfo != null) { List<MethodInfo> sortedPatchMethods = GetSortedPatchMethods(methodBase, patchInfo.transpilers, debug: false); for (int i = 0; i < maxTranspilers && i < sortedPatchMethods.Count; i++) { iLManipulator.AddTranspiler(sortedPatchMethods[i]); } } return iLManipulator.GetInstructions(generator, methodBase); } internal static void UnpatchConditional(Func<Patch, bool> executionCondition) { foreach (MethodBase item in PatchProcessor.GetAllPatchedMethods().ToList()) { bool num = item.HasMethodBody(); Patches patchInfo2 = PatchProcessor.GetPatchInfo(item); PatchProcessor patchProcessor = new PatchProcessor(null, item); if (num) { patchInfo2.Postfixes.DoIf(executionCondition, delegate(Patch patchInfo) { patchProcessor.Unpatch(patchInfo.PatchMethod); }); patchInfo2.Prefixes.DoIf(executionCondition, delegate(Patch patchInfo) { patchProcessor.Unpatch(patchInfo.PatchMethod); }); } patchInfo2.ILManipulators.DoIf(executionCondition, delegate(Patch patchInfo) { patchProcessor.Unpatch(patchInfo.PatchMethod); }); patchInfo2.Transpilers.DoIf(executionCondition, delegate(Patch patchInfo) { patchProcessor.Unpatch(patchInfo.PatchMethod); }); if (num) { patchInfo2.Finalizers.DoIf(executionCondition, delegate(Patch patchInfo) { patchProcessor.Unpatch(patchInfo.PatchMethod); }); } } } } internal class PatchJobs<T> { internal class Job { internal MethodBase original; internal T replacement; internal List<HarmonyMethod> prefixes = new List<HarmonyMethod>(); internal List<HarmonyMethod> postfixes = new List<HarmonyMethod>(); internal List<HarmonyMethod> transpilers = new List<HarmonyMethod>(); internal List<HarmonyMethod> finalizers = new List<HarmonyMethod>(); internal List<HarmonyMethod> ilmanipulators = new List<HarmonyMethod>(); internal void AddPatch(AttributePatch patch) { HarmonyPatchType? type = patch.type; if (type.HasValue) { switch (type.GetValueOrDefault()) { case HarmonyPatchType.Prefix: prefixes.Add(patch.info); break; case HarmonyPatchType.Postfix: postfixes.Add(patch.info); break; case HarmonyPatchType.Transpiler: transpilers.Add(patch.info); break; case HarmonyPatchType.Finalizer: finalizers.Add(patch.info); break; case HarmonyPatchType.ILManipulator: ilmanipulators.Add(patch.info); break; case HarmonyPatchType.ReversePatch: break; } } } } internal Dictionary<MethodBase, Job> state = new Dictionary<MethodBase, Job>(); internal Job GetJob(MethodBase method) { if ((object)method == null) { return null; } if (!state.TryGetValue(method, out var value)) { value = new Job { original = method }; state[method] = value; } return value; } internal List<Job> GetJobs() { return state.Values.Where((Job job) => job.prefixes.Count + job.postfixes.Count + job.transpilers.Count + job.finalizers.Count + job.ilmanipulators.Count > 0).ToList(); } internal List<T> GetReplacements() { return state.Values.Select((Job job) => job.replacement).ToList(); } } internal class AttributePatch { private static readonly HarmonyPatchType[] allPatchTypes = new HarmonyPatchType[6] { HarmonyPatchType.Prefix, HarmonyPatchType.Postfix, HarmonyPatchType.Transpiler, HarmonyPatchType.Finalizer, HarmonyPatchType.ReversePatch, HarmonyPatchType.ILManipulator }; internal HarmonyMethod info; internal HarmonyPatchType? type; private static readonly string harmonyAttributeName = typeof(HarmonyAttribute).FullName; internal static IEnumerable<AttributePatch> Create(MethodInfo patch, bool collectIncomplete = false) { if ((object)patch == null) { throw new NullReferenceException("Patch method cannot be null"); } object[] customAttributes = patch.GetCustomAttributes(inherit: true); string name = patch.Name; HarmonyPatchType? type = GetPatchType(name, customAttributes); if (!type.HasValue) { return Enumerable.Empty<AttributePatch>(); } if (type != HarmonyPatchType.ReversePatch && !patch.IsStatic) { throw new ArgumentException("Patch method " + patch.FullDescription() + " must be static"); } List<HarmonyMethod> list = (from attr in customAttributes where attr.GetType().BaseType.FullName == harmonyAttributeName select AccessTools.Field(attr.GetType(), "info").GetValue(attr) into harmonyInfo select AccessTools.MakeDeepCopy<HarmonyMethod>(harmonyInfo)).ToList(); List<HarmonyMethod> list2 = new List<HarmonyMethod>(); ILookup<bool, HarmonyMethod> lookup = list.ToLookup((HarmonyMethod m) => IsComplete(m, collectIncomplete)); List<HarmonyMethod> incomplete = lookup[false].ToList(); HarmonyMethod info = HarmonyMethod.Merge(incomplete); List<HarmonyMethod> list3 = lookup[true].Where((HarmonyMethod m) => !Same(m, info)).ToList(); if (list3.Count > 1) { list2.AddRange(list3.Select((HarmonyMethod m) => HarmonyMethod.Merge(incomplete.AddItem(m)))); } else { list2.Add(HarmonyMethod.Merge(list)); } foreach (HarmonyMethod item in list2) { item.method = patch; } return list2.Select((HarmonyMethod i) => new AttributePatch { info = i, type = type }).ToList(); static bool IsComplete(HarmonyMethod m, bool collectIncomplete) { if (collectIncomplete || (object)m.GetDeclaringType() != null) { return m.methodName != null; } return false; } static bool Same(HarmonyMethod m1, HarmonyMethod m2) { if ((object)m1.GetDeclaringType() == m2.GetDeclaringType() && m1.methodName == m2.methodName) { return m1.GetArgumentList().SequenceEqual(m2.GetArgumentList()); } return false; } } private static HarmonyPatchType? GetPatchType(string methodName, object[] allAttributes) { HashSet<string> hashSet = new HashSet<string>(from attr in allAttributes select attr.GetType().FullName into name where name.StartsWith("Harmony") select name); HarmonyPatchType? result = null; HarmonyPatchType[] array = allPatchTypes; for (int i = 0; i < array.Length; i++) { HarmonyPatchType value = array[i]; string text = value.ToString(); if (text == methodName || hashSet.Contains("HarmonyLib.Harmony" + text)) { result = value; break; } } return result; } } internal class PatchSorter { private class PatchSortingWrapper : IComparable { internal readonly HashSet<PatchSortingWrapper> after; internal readonly HashSet<PatchSortingWrapper> before; internal readonly Patch innerPatch; internal PatchSortingWrapper(Patch patch) { innerPatch = patch; before = new HashSet<PatchSortingWrapper>(); after = new HashSet<PatchSortingWrapper>(); } public int CompareTo(object obj) { return PatchInfoSerialization.PriorityComparer((obj as PatchSortingWrapper)?.innerPatch, innerPatch.index, innerPatch.priority); } public override bool Equals(object obj) { if (obj is PatchSortingWrapper patchSortingWrapper) { return (object)innerPatch.PatchMethod == patchSortingWrapper.innerPatch.PatchMethod; } return false; } public override int GetHashCode() { return innerPatch.PatchMethod.GetHashCode(); } internal void AddBeforeDependency(IEnumerable<PatchSortingWrapper> dependencies) { foreach (PatchSortingWrapper dependency in dependencies) { before.Add(dependency); dependency.after.Add(this); } } internal void AddAfterDependency(IEnumerable<PatchSortingWrapper> dependencies) { foreach (PatchSortingWrapper dependency in dependencies) { after.Add(dependency); dependency.before.Add(this); } } internal void RemoveAfterDependency(PatchSortingWrapper afterNode) { after.Remove(afterNode); afterNode.before.Remove(this); } internal void RemoveBeforeDependency(PatchSortingWrapper beforeNode) { before.Remove(beforeNode); beforeNode.after.Remove(this); } } internal class PatchDetailedComparer : IEqualityComparer<Patch> { public bool Equals(Patch x, Patch y) { if (y != null && x != null && x.owner == y.owner && (object)x.PatchMethod == y.PatchMethod && x.index == y.index && x.priority == y.priority && x.before.Length == y.before.Length && x.after.Length == y.after.Length && x.before.All(((IEnumerable<string>)y.before).Contains<string>)) { return x.after.All(((IEnumerable<string>)y.after).Contains<string>); } return false; } public int GetHashCode(Patch obj) { return obj.GetHashCode(); } } private List<PatchSortingWrapper> patches; private HashSet<PatchSortingWrapper> handledPatches; private List<PatchSortingWrapper> result; private List<PatchSortingWrapper> waitingList; internal Patch[] sortedPatchArray; private readonly bool debug; internal PatchSorter(Patch[] patches, bool debug = false) { this.patches = patches.Select((Patch x) => new PatchSortingWrapper(x)).ToList(); this.debug = debug; foreach (PatchSortingWrapper node in this.patches) { node.AddBeforeDependency(this.patches.Where((PatchSortingWrapper x) => node.innerPatch.before.Contains(x.innerPatch.owner))); node.AddAfterDependency(this.patches.Where((PatchSortingWrapper x) => node.innerPatch.after.Contains(x.innerPatch.owner))); } this.patches.Sort(); } internal List<MethodInfo> Sort(MethodBase original) { return (from x in SortAsPatches(original) select x.GetMethod(original)).ToList(); } internal Patch[] SortAsPatches(MethodBase original) { if (sortedPatchArray != null) { return sortedPatchArray; } handledPatches = new HashSet<PatchSortingWrapper>(); waitingList = new List<PatchSortingWrapper>(); result = new List<PatchSortingWrapper>(patches.Count); Queue<PatchSortingWrapper> queue = new Queue<PatchSortingWrapper>(patches); while (queue.Count != 0) { foreach (PatchSortingWrapper item in queue) { if (item.after.All((PatchSortingWrapper x) => handledPatches.Contains(x))) { AddNodeToResult(item); if (item.before.Count != 0) { ProcessWaitingList(); } } else { waitingList.Add(item); } } CullDependency(); queue = new Queue<PatchSortingWrapper>(waitingList); waitingList.Clear(); } sortedPatchArray = result.Select((PatchSortingWrapper x) => x.innerPatch).ToArray(); handledPatches = null; waitingList = null; patches = null; return sortedPatchArray; } internal bool ComparePatchLists(Patch[] patches) { if (sortedPatchArray == null) { Sort(null); } if (patches != null && sortedPatchArray.Length == patches.Length) { return sortedPatchArray.All((Patch x) => patches.Contains(x, new PatchDetailedComparer())); } return false; } private void CullDependency() { for (int i = waitingList.Count - 1; i >= 0; i--) { foreach (PatchSortingWrapper afterNode in waitingList[i].after) { if (!handledPatches.Contains(afterNode)) { waitingList[i].RemoveAfterDependency(afterNode); Logger.Log(Logger.LogChannel.Debug, delegate { string text = afterNode.innerPatch.PatchMethod.FullDescription(); string text2 = waitingList[i].innerPatch.PatchMethod.FullDescription(); return "Breaking dependence between " + text + " and " + text2; }, debug); return; } } } } private void ProcessWaitingList() { int num = waitingList.Count; int num2 = 0; while (num2 < num) { PatchSortingWrapper patchSortingWrapper = waitingList[num2]; if (patchSortingWrapper.after.All(handledPatches.Contains)) { waitingList.Remove(patchSortingWrapper); AddNodeToResult(patchSortingWrapper); num--; num2 = 0; } else { num2++; } } } private void AddNodeToResult(PatchSortingWrapper node) { result.Add(node); handledPatches.Add(node); } } internal static class PatchTools { [ThreadStatic] private static Dictionary<object, object> objectReferences; internal static void RememberObject(object key, object value) { if (objectReferences == null) { objectReferences = new Dictionary<object, object>(); } objectReferences[key] = value; } internal static MethodInfo GetPatchMethod(Type patchType, string attributeName) { MethodInfo methodInfo = patchType.GetMethods(AccessTools.all).FirstOrDefault((MethodInfo m) => m.GetCustomAttributes(inherit: true).Any((object a) => a.GetType().FullName == attributeName)); if ((object)methodInfo == null) { string name = attributeName.Replace("HarmonyLib.Harmony", ""); methodInfo = patchType.GetMethod(name, AccessTools.all); } return methodInfo; } internal static AssemblyBuilder DefineDynamicAssembly(string name) { AssemblyName assemblyName = new AssemblyName(name); return AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); } internal static List<AttributePatch> GetPatchMethods(Type type, bool collectIncomplete = false) { return (from attributePatch in AccessTools.GetDeclaredMethods(type).SelectMany((MethodInfo m) => AttributePatch.Create(m, collectIncomplete)) where attributePatch != null select attributePatch).ToList(); } internal static MethodBase GetOriginalMethod(this HarmonyMethod attr) { try { MethodType? methodType = attr.methodType; if (methodType.HasValue) { switch (methodType.GetValueOrDefault()) { case MethodType.Normal: if (attr.methodName == null) { return null; } return AccessTools.DeclaredMethod(attr.GetDeclaringType(), attr.methodName, attr.argumentTypes); case MethodType.Getter: if (attr.methodName == null) { return null; } return AccessTools.DeclaredProperty(attr.GetDeclaringType(), attr.methodName).GetGetMethod(nonPublic: true); case MethodType.Setter: if (attr.methodName == null) { return null; } return AccessTools.DeclaredProperty(attr.GetDeclaringType(), attr.methodName).GetSetMethod(nonPublic: true); case MethodType.Constructor: return AccessTools.DeclaredConstructor(attr.GetDeclaringType(), attr.argumentTypes); case MethodType.StaticConstructor: return AccessTools.GetDeclaredConstructors(attr.GetDeclaringType()).FirstOrDefault((ConstructorInfo c) => c.IsStatic); case MethodType.Enumerator: if (attr.methodName == null) { return null; } return AccessTools.EnumeratorMoveNext(AccessTools.DeclaredMethod(attr.GetDeclaringType(), attr.methodName, attr.argumentTypes)); } } } catch (AmbiguousMatchException ex) { throw new HarmonyException("Ambiguous match for HarmonyMethod[" + attr.Description() + "]", ex.InnerException ?? ex); } return null; } } public enum MethodType { Normal, Getter, Setter, Constructor, StaticConstructor, Enumerator } public enum ArgumentType { Normal, Ref, Out, Pointer } public enum HarmonyPatchType { All, Prefix, Postfix, Transpiler, Finalizer, ReversePatch, ILManipulator } public enum HarmonyReversePatchType { Original, Snapshot } public enum MethodDispatchType { VirtualCall, Call } [MeansImplicitUse] public class HarmonyAttribute : Attribute { public HarmonyMethod info = new HarmonyMethod(); } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Delegate, AllowMultiple = true)] public class HarmonyPatch : HarmonyAttribute { public HarmonyPatch() { } public HarmonyPatch(Type declaringType) { info.declaringType = declaringType; } public HarmonyPatch(Type declaringType, Type[] argumentTypes) { info.declaringType = declaringType; info.argumentTypes = argumentTypes; } public HarmonyPatch(Type declaringType, string methodName) { info.declaringType = declaringType; info.methodName = methodName; } public HarmonyPatch(Type declaringType, string methodName, params Type[] argumentTypes) { info.declaringType = declaringType; info.methodName = methodName; info.argumentTypes = argumentTypes; } public HarmonyPatch(Type declaringType, string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations) { info.declaringType = declaringType; info.methodName = methodName; ParseSpecialArguments(argumentTypes, argumentVariations); } public HarmonyPatch(string typeName, string methodName) { info.declaringType = AccessTools.TypeByName(typeName); info.methodName = methodName; } public HarmonyPatch(string typeName, string methodName, MethodType methodType, Type[] argumentTypes = null, ArgumentType[] argumentVariations = null) { info.declaringType = AccessTools.TypeByName(typeName); info.methodName = methodName; info.methodType = methodType; if (argumentTypes != null) { ParseSpecialArguments(argumentTypes, argumentVariations); } } public HarmonyPatch(Type declaringType, MethodType methodType) { info.declaringType = declaringType; info.methodType = methodType; } public HarmonyPatch(Type declaringType, MethodType methodType, params Type[] argumentTypes) { info.declaringType = declaringType; info.methodType = methodType; info.argumentTypes = argumentTypes; } public HarmonyPatch(Type declaringType, MethodType methodType, Type[] argumentTypes, ArgumentType[] argumentVariations) { info.declaringType = declaringType; info.methodType = methodType; ParseSpecialArguments(argumentTypes, argumentVariations); } public HarmonyPatch(Type declaringType, string methodName, MethodType methodType) { info.declaringType = declaringType; info.methodName = methodName; info.methodType = methodType; } public HarmonyPatch(string methodName) { info.methodName = methodName; } public HarmonyPatch(string methodName, params Type[] argumentTypes) { info.methodName = methodName; info.argumentTypes = argumentTypes; } public HarmonyPatch(string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations) { info.methodName = methodName; ParseSpecialArguments(argumentTypes, argumentVariations); } public HarmonyPatch(string methodName, MethodType methodType) { info.methodName = methodName; info.methodType = methodType; } public HarmonyPatch(MethodType methodType) { info.methodType = methodType; } public HarmonyPatch(MethodType methodType, params Type[] argumentTypes) { info.methodType = methodType; info.argumentTypes = argumentTypes; } public HarmonyPatch(MethodType methodType, Type[] argumentTypes, ArgumentType[] argumentVariations) { info.methodType = methodType; ParseSpecialArguments(argumentTypes, argumentVariations); } public HarmonyPatch(Type[] argumentTypes) { info.argumentTypes = argumentTypes; } public HarmonyPatch(Type[] argumentTypes, ArgumentType[] argumentVariations) { ParseSpecialArguments(argumentTypes, argumentVariations); } public HarmonyPatch(string typeName, string methodName, MethodType methodType = MethodType.Normal) { info.declaringType = AccessTools.TypeByName(typeName); info.methodName = methodName; info.methodType = methodType; } private void ParseSpecialArguments(Type[] argumentTypes, ArgumentType[] argumentVariations) { if (argumentVariations == null || argumentVariations.Length == 0) { info.argumentTypes = argumentTypes; return; } if (argumentTypes.Length < argumentVariations.Length) { throw new ArgumentException("argumentVariations contains more elements than argumentTypes", "argumentVariations"); } List<Type> list = new List<Type>(); for (int i = 0; i < argumentTypes.Length; i++) { Type type = argumentTypes[i]; switch (argumentVariations[i]) { case ArgumentType.Ref: case ArgumentType.Out: type = type.MakeByRefType(); break; case ArgumentType.Pointer: type = type.MakePointerType(); break; } list.Add(type); } info.argumentTypes = list.ToArray(); } } [AttributeUsage(AttributeTargets.Delegate, AllowMultiple = true)] public class HarmonyDelegate : HarmonyPatch { public HarmonyDelegate(Type declaringType) : base(declaringType) { } public HarmonyDelegate(Type declaringType, Type[] argumentTypes) : base(declaringType, argumentTypes) { } public HarmonyDelegate(Type declaringType, string methodName) : base(declaringType, methodName) { } public HarmonyDelegate(Type declaringType, string methodName, params Type[] argumentTypes) : base(declaringType, methodName, argumentTypes) { } public HarmonyDelegate(Type declaringType, string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations) : base(declaringType, methodName, argumentTypes, argumentVariations) { } public HarmonyDelegate(Type declaringType, MethodDispatchType methodDispatchType) : base(declaringType, MethodType.Normal) { info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call; } public HarmonyDelegate(Type declaringType, MethodDispatchType methodDispatchType, params Type[] argumentTypes) : base(declaringType, MethodType.Normal, argumentTypes) { info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call; } public HarmonyDelegate(Type declaringType, MethodDispatchType methodDispatchType, Type[] argumentTypes, ArgumentType[] argumentVariations) : base(declaringType, MethodType.Normal, argumentTypes, argumentVariations) { info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call; } public HarmonyDelegate(Type declaringType, string methodName, MethodDispatchType methodDispatchType) : base(declaringType, methodName, MethodType.Normal) { info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call; } public HarmonyDelegate(string methodName) : base(methodName) { } public HarmonyDelegate(string methodName, params Type[] argumentTypes) : base(methodName, argumentTypes) { } public HarmonyDelegate(string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations) : base(methodName, argumentTypes, argumentVariations) { } public HarmonyDelegate(string methodName, MethodDispatchType methodDispatchType) : base(methodName, MethodType.Normal) { info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call; } public HarmonyDelegate(MethodDispatchType methodDispatchType) { info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call; } public HarmonyDelegate(MethodDispatchType methodDispatchType, params Type[] argumentTypes) : base(MethodType.Normal, argumentTypes) { info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call; } public HarmonyDelegate(MethodDispatchType methodDispatchType, Type[] argumentTypes, ArgumentType[] argumentVariations) : base(MethodType.Normal, argumentTypes, argumentVariations) { info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call; } public HarmonyDelegate(Type[] argumentTypes) : base(argumentTypes) { } public HarmonyDelegate(Type[] argumentTypes, ArgumentType[] argumentVariations) : base(argumentTypes, argumentVariations) { } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)] public class HarmonyReversePatch : HarmonyAttribute { public HarmonyReversePatch(HarmonyReversePatchType type = HarmonyReversePatchType.Original) { info.reversePatchType = type; } } [AttributeUsage(AttributeTargets.Class)] public class HarmonyPatchAll : HarmonyAttribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class HarmonyPriority : HarmonyAttribute { public HarmonyPriority(int priority) { info.priority = priority; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class HarmonyBefore : HarmonyAttribute { public HarmonyBefore(params string[] before) { info.before = before; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class HarmonyAfter : HarmonyAttribute { public HarmonyAfter(params string[] after) { info.after = after; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class HarmonyDebug : HarmonyAttribute { public HarmonyDebug() { info.debug = true; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class HarmonyEmitIL : HarmonyAttribute { public HarmonyEmitIL() { info.debugEmitPath = "./"; } public HarmonyEmitIL(string dir) { info.debugEmitPath = dir; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)] public class HarmonyWrapSafe : HarmonyAttribute { public HarmonyWrapSafe() { info.wrapTryCatch = true; } } [AttributeUsage(AttributeTargets.Method)] public class HarmonyPrepare : Attribute { } [AttributeUsage(AttributeTargets.Method)] public class HarmonyCleanup : Attribute { } [AttributeUsage(AttributeTargets.Method)] public class HarmonyTargetMethod : Attribute { } [AttributeUsage(AttributeTargets.Method)] public class HarmonyTargetMethods : Attribute { } [AttributeUsage(AttributeTargets.Method)] public class HarmonyPrefix : Attribute { } [AttributeUsage(AttributeTargets.Method)] public class HarmonyPostfix : Attribute { } [AttributeUsage(AttributeTargets.Method)] public class HarmonyTranspiler : Attribute { } [AttributeUsage(AttributeTargets.Method)] public class HarmonyILManipulator : Attribute { } [AttributeUsage(AttributeTargets.Method)] public class HarmonyFinalizer : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Parameter, AllowMultiple = true)] public class HarmonyArgument : Attribute { public string OriginalName { get; private set; } public int Index { get; private set; } public string NewName { get; private set; } public HarmonyArgument(string originalName) : this(originalName, null) { } public HarmonyArgument(int index) : this(index, null) { } public HarmonyArgument(string originalName, string newName) { OriginalName = originalName; Index = -1; NewName = newName; } public HarmonyArgument(int index, string name) { OriginalName = null; Index = index; NewName = name; } } public class CodeInstruction { public OpCode opcode; public object operand; public List<Label> labels = new List<Label>(); public List<ExceptionBlock> blocks = new List<ExceptionBlock>(); internal CodeInstruction() { } public CodeInstruction(OpCode opcode, object operand = null) { this.opcode = opcode; this.operand = operand; } public CodeInstruction(CodeInstruction instruction) { opcode = instruction.opcode; operand = instruction.operand; labels = instruction.labels.ToList(); blocks = instruction.blocks.ToList(); } public CodeInstruction Clone() { return new CodeInstruction(this) { labels = new List<Label>(), blocks = new List<ExceptionBlock>() }; } public CodeInstruction Clone(OpCode opcode) { CodeInstruction codeInstruction = Clone(); codeInstruction.opcode = opcode; return codeInstruction; } public CodeInstruction Clone(object operand) { CodeInstruction codeInstruction = Clone(); codeInstruction.operand = operand; return codeInstruction; } public static CodeInstruction Call(Type type, string name, Type[] parameters = null, Type[] generics = null) { MethodInfo methodInfo = AccessTools.Method(type, name, parameters, generics); if ((object)methodInfo == null) { throw new ArgumentException($"No method found for type={type}, name={name}, parameters={parameters.Description()}, generics={generics.Description()}"); } return new CodeInstruction(OpCodes.Call, methodInfo); } public static CodeInstruction Call(string typeColonMethodname, Type[] parameters = null, Type[] generics = null) { MethodInfo methodInfo = AccessTools.Method(typeColonMethodname, parameters, generics); if ((object)methodInfo == null) { throw new ArgumentException("No method found for " + typeColonMethodname + ", parameters=" + parameters.Description() + ", generics=" + generics.Description()); } return new CodeInstruction(OpCodes.Call, methodInfo); } public static CodeInstruction Call(Expression<Action> expression) { return new CodeInstruction(OpCodes.Call, SymbolExtensions.GetMethodInfo(expression)); } public static CodeInstruction Call<T>(Expression<Action<T>> expression) { return new CodeInstruction(OpCodes.Call, SymbolExtensions.GetMethodInfo(expression)); } public static CodeInstruction Call<T, TResult>(Expression<Func<T, TResult>> expression) { return new CodeInstruction(OpCodes.Call, SymbolExtensions.GetMethodInfo(expression)); } public static CodeInstruction Call(LambdaExpression expression) { return new CodeInstruction(OpCodes.Call, SymbolExtensions.GetMethodInfo(expression)); } public static CodeInstruction CallClosure<T>(T closure) where T : Delegate { return Transpilers.EmitDelegate(closure); } public static CodeInstruction LoadField(Type type, string name, bool useAddress = false) { FieldInfo fieldInfo = AccessTools.Field(type, name); if ((object)fieldInfo == null) { throw new ArgumentException($"No field found for {type} and {name}"); } return new CodeInstruction((!useAddress) ? (fieldInfo.IsStatic ? OpCodes.Ldsfld : OpCodes.Ldfld) : (fieldInfo.IsStatic ? OpCodes.Ldsflda : OpCodes.Ldflda), fieldInfo); } public static CodeInstruction StoreField(Type type, string name) { FieldInfo fieldInfo = AccessTools.Field(type, name); if ((object)fieldInfo == null) { throw new ArgumentException($"No field found for {type} and {name}"); } return new CodeInstruction(fieldInfo.IsStatic ? OpCodes.Stsfld : OpCodes.Stfld, fieldInfo); } public override string ToString() { List<string> list = new List<string>(); foreach (Label label in labels) { list.Add($"Label{label.GetHashCode()}"); } foreach (ExceptionBlock block in blocks) { list.Add("EX_" + block.blockType.ToString().Replace("Block", "")); } string text = ((list.Count > 0) ? (" [" + string.Join(", ", list.ToArray()) + "]") : ""); string text2 = FormatArgument(operand); if (text2.Length > 0) { text2 = " " + text2; } OpCode opCode = opcode; return opCode.ToString() + text2 + text; } internal static string FormatArgument(object argument, string extra = null) { if (argument == null) { return "NULL"; } Type type = argument.GetType(); if (argument is MethodBase member) { return member.FullDescription() + ((extra != null) ? (" " + extra) : ""); } if (argument is FieldInfo fieldInfo) { return fieldInfo.FieldType.FullDescription() + " " + fieldInfo.DeclaringType.FullDescription() + "::" + fieldInfo.Name; } if ((object)type == typeof(Label)) { return $"Label{((Label)argument).GetHashCode()}"; } if ((object)type == typeof(Label[])) { return "Labels" + string.Join(",", ((Label[])argument).Select((Label l) => l.GetHashCode().ToString()).ToArray()); } if ((object)type == typeof(LocalBuilder)) { return $"{((LocalBuilder)argument).LocalIndex} ({((LocalBuilder)argument).LocalType})"; } if ((object)type == typeof(string)) { return argument.ToString().ToLiteral(); } return argument.ToString().Trim(); } } public enum ExceptionBlockType { BeginExceptionBlock, BeginCatchBlock, BeginExceptFilterBlock, BeginFaultBlock, BeginFinallyBlock, EndExceptionBlock } public class ExceptionBlock { public ExceptionBlockType blockType; public Type catchType; public ExceptionBlock(ExceptionBlockType blockType, Type catchType = null) { this.blockType = blockType; this.catchType = catchType ?? typeof(object); } } public class InvalidHarmonyPatchArgumentException : Exception { public MethodBase Original { get; } public MethodInfo Patch { get; } public override string Message => "(" + Patch.FullDescription() + "): " + base.Message; public InvalidHarmonyPatchArgumentException(string message, MethodBase original, MethodInfo patch) : base(message) { Original = original; Patch = patch; } } public class MemberNotFoundException : Exception { public MemberNotFoundException(string message) : base(message) { } } public class Harmony : IDisposable { [Obsolete("Use HarmonyFileLog.Enabled instead")] public static bool DEBUG; public string Id { get; } static Harmony() { StackTraceFixes.Install(); } public Harmony(string id) { if (string.IsNullOrEmpty(id)) { throw new ArgumentException("id cannot be null or empty"); } try { string environmentVariable = Environment.GetEnvironmentVariable("HARMONY_DEBUG"); if (environmentVariable != null && environmentVariable.Length > 0) { environmentVariable = environmentVariable.Trim(); DEBUG = environmentVariable == "1" || bool.Parse(environmentVariable); } } catch { } if (DEBUG) { HarmonyFileLog.Enabled = true; } MethodBase callingMethod = (Logger.IsEnabledFor(Logger.LogChannel.Info) ? AccessTools.GetOutsideCaller() : null); Logger.Log(Logger.LogChannel.Info, delegate { //IL_0070: 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_00aa: Unknown result type (might be due to invalid IL or missing references) StringBuilder stringBuilder = new StringBuilder(); Assembly assembly = typeof(Harmony).Assembly; Version version = assembly.GetName().Version; string text = assembly.Location; string text2 = Environment.Version.ToString(); string text3 = Environment.OSVersion.Platform.ToString(); if (string.IsNullOrEmpty(text)) { text = new Uri(assembly.CodeBase).LocalPath; } int size = IntPtr.Size; Platform current = PlatformHelper.Current; stringBuilder.AppendLine($"### Harmony id={id}, version={version}, location={text}, env/clr={text2}, platform={text3}, ptrsize:runtime/env={size}/{current}"); if ((object)callingMethod?.DeclaringType != null) { Assembly assembly2 = callingMethod.DeclaringType.Assembly; text = assembly2.Location; if (string.IsNullOrEmpty(text)) { text = new Uri(assembly2.CodeBase).LocalPath; } stringBuilder.AppendLine("### Started from " + callingMethod.FullDescription() + ", location " + text); stringBuilder.Append($"### At {DateTime.Now:yyyy-MM-dd hh.mm.ss}"); } return stringBuilder.ToString(); }); Id = id; } public void PatchAll() { Assembly assembly = new StackTrace().GetFrame(1).GetMethod().ReflectedType.Assembly; PatchAll(assembly); } public PatchProcessor CreateProcessor(MethodBase original) { return new PatchProcessor(this, original); } public PatchClassProcessor CreateClassProcessor(Type type) { return new PatchClassProcessor(this, type); } public PatchClassProcessor CreateClassProcessor(Type type, bool allowUnannotatedType) { return new PatchClassProcessor(this, type, allowUnannotatedType); } public ReversePatcher CreateReversePatcher(MethodBase original, HarmonyMethod standin) { return new ReversePatcher(this, original, standin); } public void PatchAll(Assembly assembly) { AccessTools.GetTypesFromAssembly(assembly).Do(delegate(Type type) { CreateClassProcessor(type).Patch(); }); } public void PatchAll(Type type) { CreateClassProcessor(type, allowUnannotatedType: true).Patch(); } public MethodInfo Patch(MethodBase original, HarmonyMethod prefix = null, HarmonyMethod postfix = null, HarmonyMethod transpiler = null, HarmonyMethod finalizer = null, HarmonyMethod ilmanipulator = null) { PatchProcessor patchProcessor = CreateProcessor(original); patchProcessor.AddPrefix(prefix); patchProcessor.AddPostfix(postfix); patchProcessor.AddTranspiler(transpiler); patchProcessor.AddFinalizer(finalizer); patchProcessor.AddILManipulator(ilmanipulator); return patchProcessor.Patch(); } [Obsolete("Use newer Patch() instead", true)] public MethodInfo Patch(MethodBase original, HarmonyMethod prefix, HarmonyMethod postfix, HarmonyMethod transpiler, HarmonyMethod finalizer) { return Patch(original, prefix, postfix, transpiler, finalizer, null); } public static MethodInfo ReversePatch(MethodBase original, HarmonyMethod standin, MethodInfo transpiler = null, MethodInfo ilmanipulator = null) { return PatchFunctions.ReversePatch(standin, original, transpiler, ilmanipulator); } [Obsolete("Use newer ReversePatch() instead", true)] public static MethodInfo ReversePatch(MethodBase original, HarmonyMethod standin, MethodInfo transpiler) { return PatchFunctions.ReversePatch(standin, original, transpiler, null); } public static void UnpatchID(string harmonyID) { if (string.IsNullOrEmpty(harmonyID)) { throw new ArgumentNullException("harmonyID", "UnpatchID was called with a null or empty harmonyID."); } PatchFunctions.UnpatchConditional((Patch patchInfo) => patchInfo.owner == harmonyID); } void IDisposable.Dispose() { UnpatchSelf(); } public void UnpatchSelf() { UnpatchID(Id); } public static void UnpatchAll() { Logger.Log(Logger.LogChannel.Warn, () => "UnpatchAll has been called - This will remove ALL HARMONY PATCHES."); PatchFunctions.UnpatchConditional((Patch _) => true); } [Obsolete("Use UnpatchSelf() to unpatch the current instance. The functionality to unpatch either other ids or EVERYTHING has been moved the static methods UnpatchID() and UnpatchAll() respectively", true)] public void UnpatchAll(string harmonyID = null) { if (harmonyID == null) { if (HarmonyGlobalSettings.DisallowLegacyGlobalUnpatchAll) { Logger.Log(Logger.LogChannel.Warn, () => "Legacy UnpatchAll has been called AND DisallowLegacyGlobalUnpatchAll=true. Skipping execution of UnpatchAll"); } else { UnpatchAll(); } } else if (harmonyID.Length == 0) { Logger.Log(Logger.LogChannel.Warn, () => "Legacy UnpatchAll was called with harmonyID=\"\" which is an invalid id. Skipping execution of UnpatchAll"); } else { UnpatchID(harmonyID); } } public void Unpatch(MethodBase original, HarmonyPatchType type, string harmonyID = "*") { CreateProcessor(original).Unpatch(type, harmonyID); } public void Unpatch(MethodBase original, MethodInfo patch) { CreateProcessor(original).Unpatch(patch); } public static bool HasAnyPatches(string harmonyID) { return (from original in GetAllPatchedMethods() select GetPatchInfo(original)).Any((Patches info) => info.Owners.Contains(harmonyID)); } public static Patches GetPatchInfo(MethodBase method) { return PatchProcessor.GetPatchInfo(method); } public IEnumerable<MethodBase> GetPatchedMethods() { return from original in GetAllPatchedMethods() where GetPatchInfo(original).Owners.Contains(Id) select original; } public static IEnumerable<MethodBase> GetAllPatchedMethods() { return PatchProcessor.GetAllPatchedMethods(); } public static MethodBase GetOriginalMethod(MethodInfo replacement) { if ((object)replacement == null) { throw new ArgumentNullException("replacement"); } return PatchManager.GetOriginal(replacement); } public static MethodBase GetMethodFromStackframe(StackFrame frame) { if (frame == null) { throw new ArgumentNullException("frame"); } return PatchManager.FindReplacement(frame) ?? frame.GetMethod(); } public static MethodBase GetOriginalMethodFromStackframe(StackFrame frame) { MethodBase methodBase = GetMethodFromStackframe(frame); if (methodBase is MethodInfo replacement) { methodBase = GetOriginalMethod(replacement) ?? methodBase; } return methodBase; } public static Dictionary<string, Version> VersionInfo(out Version currentVersion) { return PatchProcessor.VersionInfo(out currentVersion); } public static Harmony CreateAndPatchAll(Type type, string harmonyInstanceId = null) { Harmony harmony = new Harmony(harmonyInstanceId ?? $"harmony-auto-{Guid.NewGuid()}"); harmony.PatchAll(type); return harmony; } public static Harmony CreateAndPatchAll(Assembly assembly, string harmonyInstanceId = null) { Harmony harmony = new Harmony(harmonyInstanceId ?? $"harmony-auto-{Guid.NewGuid()}"); harmony.PatchAll(assembly); return harmony; } } [Serializable] public class HarmonyException : Exception { private Dictionary<int, CodeInstruction> instructions = new Dictionary<int, CodeInstruction>(); private int errorOffset = -1; internal HarmonyException() { } internal HarmonyException(string message) : base(message) { } internal HarmonyException(string message, Exception innerException) : base(message, innerException) { } protected HarmonyException(SerializationInfo serializationInfo, StreamingContext streamingContext) { throw new NotImplementedException(); } internal HarmonyException(Exception innerException, Dictionary<int, CodeInstruction> instructions, int errorOffset) : base("IL Compile Error", innerException) { this.instructions = instructions; this.errorOffset = errorOffset; } internal static Exception Create(Exception ex, MethodBody body) { if (ex is HarmonyException ex2) { Dictionary<int, CodeInstruction> dictionary = ex2.instructions; if (dictionary != null && dictionary.Count > 0 && ex2.errorOffset >= 0) { return ex; } } Match match = Regex.Match(ex.Message.TrimEnd(new char[0]), "(?:Reason: )?Invalid IL code in.+: IL_(\\d{4}): (.+)$"); if (!match.Success) { return new HarmonyException("IL Compile Error (unknown location)", ex); } Dictionary<int, CodeInstruction> dictionary2 = ILManipulator.GetInstructions(body) ?? new Dictionary<int, CodeInstruction>(); int num = int.Parse(match.Groups[1].Value, NumberStyles.HexNumber); Regex.Replace(match.Groups[2].Value, " {2,}", " "); if (ex is HarmonyException ex3) { if (dictionary2.Count != 0) { ex3.instructions = dictionary2; ex3.errorOffset = num; } return ex3; } return new HarmonyException(ex, dictionary2, num); } public List<KeyValuePair<int, CodeInstruction>> GetInstructionsWithOffsets() { return instructions.OrderBy((KeyValuePair<int, CodeInstruction> ins) => ins.Key).ToList(); } public List<CodeInstruction> GetInstructions() { return (from ins in instructions orderby ins.Key select ins.Value).ToList(); } public int GetErrorOffset() { return errorOffset; } public int GetErrorIndex() { if (instructions.TryGetValue(errorOffset, out var value)) { return GetInstructions().IndexOf(value); } return -1; } } public static class HarmonyGlobalSettings { public static bool DisallowLegacyGlobalUnpatchAll { get; set; } } public class HarmonyMethod { public MethodInfo method; public Type declaringType; public string methodName; public MethodType? methodType; public Type[] argumentTypes; public int priority = -1; public string[] before; public string[] after; public HarmonyReversePatchType? reversePatchType; public bool? debug; public string debugEmitPath; public bool nonVirtualDelegate; public bool? wrapTryCatch; public HarmonyMethod() { } private void ImportMethod(MethodInfo theMethod) { if ((object)theMethod == null) { throw new ArgumentNullException("theMethod", "Harmony method is null (did you target a wrong or missing method?)"); } if (!theMethod.IsStatic) { throw new ArgumentException("Harmony method must be static", "theMethod"); } method = theMethod; List<HarmonyMethod> fromMethod = HarmonyMethodExtensions.GetFromMethod(method); if (fromMethod != null) { Merge(fromMethod).CopyTo(this); } } public HarmonyMethod(MethodInfo method) { if ((object)method == null) { throw new ArgumentNullException("method"); } ImportMethod(method); } public HarmonyMethod(MethodInfo method, int priority = -1, string[] before = null, string[] after = null, bool? debug = null) { if ((object)method == null) { throw new ArgumentNullException("method"); } ImportMethod(method); this.priority = priority; this.before = before; this.after = after; this.debug = debug; } public HarmonyMethod(Type methodType, string methodName, Type[] argumentTypes = null) { MethodInfo methodInfo = AccessTools.Method(methodType, methodName, argumentTypes); if ((object)methodInfo == null) { throw new ArgumentException($"Cannot not find method for type {methodType} and name {methodName} and parameters {argumentTypes?.Description()}"); } ImportMethod(methodInfo); } public static List<string> HarmonyFields() { return (from s in AccessTools.GetFieldNames(typeof(HarmonyMethod)) where s != "method" select s).ToList(); } public static HarmonyMethod Merge(List<HarmonyMethod> attributes) { return Merge((IEnumerable<HarmonyMethod>)attributes); } internal static HarmonyMethod Merge(IEnumerable<HarmonyMethod> attributes) { HarmonyMethod harmonyMethod = new HarmonyMethod(); if (attributes == null) { return harmonyMethod; } Traverse resultTrv = Traverse.Create(harmonyMethod); attributes.Do(delegate(HarmonyMethod attribute) { Traverse trv = Traverse.Create(attribute); HarmonyFields().ForEach(delegate(string f) { object value = trv.Field(f).GetValue(); if (value != null && (f != "priority" || (int)value != -1)) { HarmonyMethodExtensions.SetValue(resultTrv, f, value); } }); }); return harmonyMethod; } public override string ToString() { string result = ""; Traverse trv = Traverse.Create(this); HarmonyFields().ForEach(delegate(string f) { if (result.Length > 0) { result += ", "; } result += $"{f}={trv.Field(f).GetValue()}"; }); return "HarmonyMethod[" + result + "]"; } internal string Description() { string text = (((object)declaringType != null) ? declaringType.FullDescription() : "undefined"); string text2 = methodName ?? "undefined"; string text3 = (methodType.HasValue ? methodType.Value.ToString() : "undefined"); string text4 = ((argumentTypes != null) ? argumentTypes.Description() : "undefined"); return "(class=" + text + ", methodname=" + text2 + ", type=" + text3 + ", args=" + text4 + ")"; } internal Type GetDeclaringType() { return declaringType; } internal Type[] GetArgumentList() { return argumentTypes ?? EmptyType.NoArgs; } } internal static class EmptyType { internal static readonly Type[] NoArgs = new Type[0]; } public static class HarmonyMethodExtensions { internal static void SetValue(Traverse trv, string name, object val) { if (val != null) { Traverse traverse = trv.Field(name); if (name == "methodType" || name == "reversePatchType") { val = Enum.ToObject(Nullable.GetUnderlyingType(traverse.GetValueType()), (int)val); } traverse.SetValue(val); } } public static void CopyTo(this HarmonyMethod from, HarmonyMethod to) { if (to == null) { return; } Traverse fromTrv = Traverse.Create(from); Traverse toTrv = Traverse.Create(to); HarmonyMethod.HarmonyFields().ForEach(delegate(string f) { object value = fromTrv.Field(f).GetValue(); if (value != null) { SetValue(toTrv, f, value); } }); } public static HarmonyMethod Clone(this HarmonyMethod original) { HarmonyMethod harmonyMethod = new HarmonyMethod(); original.CopyTo(harmonyMethod); return harmonyMethod; } public static HarmonyMethod Merge(this HarmonyMethod master, HarmonyMethod detail) { if (detail == null) { return master; } HarmonyMethod harmonyMethod = new HarmonyMethod(); Traverse resultTrv = Traverse.Create(harmonyMethod); Traverse masterTrv = Traverse.Create(master); Traverse detailTrv = Traverse.Create(detail); HarmonyMethod.HarmonyFields().ForEach(delegate(string f) { object value = masterTrv.Field(f).GetValue(); object value2 = detailTrv.Field(f).GetValue(); if (f != "priority" || (int)value2 != -1) { SetValue(resultTrv, f, value2 ?? value); } }); return harmonyMethod; } private static HarmonyMethod GetHarmonyMethodInfo(object attribute) { FieldInfo field = attribute.GetType().GetField("info", AccessTools.all); if ((object)field == null) { return null; } if (field.FieldType.FullName != typeof(HarmonyMethod).FullName) { return null; } return AccessTools.MakeDeepCopy<HarmonyMethod>(field.GetValue(attribute)); } public static List<HarmonyMethod> GetFromType(Type type) { return (from attr in type.GetCustomAttributes(inherit: true) select GetHarmonyMethodInfo(attr) into info where info != null select info).ToList(); } public static HarmonyMethod GetMergedFromType(Type type) { return HarmonyMethod.Merge(GetFromType(type)); } public static List<HarmonyMethod> GetFromMethod(MethodBase method) { return (from attr in method.GetCustomAttributes(inherit: true) select GetHarmonyMethodInfo(attr) into info where info != null select info).ToList(); } public static HarmonyMethod GetMergedFromMethod(MethodBase method) { return HarmonyMethod.Merge(GetFromMethod(method)); } } public class InlineSignature : ICallSiteGenerator { public class ModifierType { public bool IsOptional; public Type Modifier; public object Type; public override string ToString() { return ((Type is Type type) ? type.FullDescription() : Type?.ToString()) + " mod" + (IsOptional ? "opt" : "req") + "(" + Modifier?.FullDescription() + ")"; } internal TypeReference ToTypeReference(ModuleDefinition module) { //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Expected O, but got Unknown //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Expected O, but got Unknown if (!IsOptional) { return (TypeReference)new RequiredModifierType(module.ImportReference(Modifier), GetTypeReference(module, Type)); } return (TypeReference)new OptionalModifierType(module.ImportReference(Modifier), GetTypeReference(module, Type)); } } public bool HasThis { get; set; } public bool ExplicitThis { get; set; } public CallingConvention CallingConvention { get; set; } = CallingConvention.Winapi; public List<object> Parameters { get; set; } = new List<object>(); public object ReturnType { get; set; } = typeof(void); public override string ToString() { return ((ReturnType is Type type) ? type.FullDescription() : ReturnType?.ToString()) + " (" + Parameters.Join((object p) => (!(p is Type type2)) ? p?.ToString() : type2.FullDescription()) + ")"; } internal static TypeReference GetTypeReference(ModuleDefinition module, object param) { if (!(param is Type type)) { if (!(param is InlineSignature inlineSignature)) { if (param is ModifierType modifierType) { return modifierType.ToTypeReference(module); } throw new NotSupportedException($"Unsupported inline signature parameter type: {param} ({param?.GetType().FullDescription()})"); } return (TypeReference)(object)inlineSignature.ToFunctionPointer(module); } return module.ImportReference(type); } CallSite ICallSiteGenerator.ToCallSite(ModuleDefinition module) { //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_001d: 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: Expected O, but got Unknown //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Expected O, but got Unknown CallSite val = new CallSite(GetTypeReference(module, ReturnType)) { HasThis = HasThis, ExplicitThis = ExplicitThis, CallingConvention = (MethodCallingConvention)(byte)((byte)CallingConvention - 1) }; foreach (object parameter in Parameters) { val.Parameters.Add(new ParameterDefinition(GetTypeReference(module, parameter))); } return val; } private FunctionPointerType ToFunctionPointer(ModuleDefinition module) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0017: 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_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Expected O, but got Unknown //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Expected O, but got Unknown FunctionPointerType val = new FunctionPointerType { ReturnType = GetTypeReference(module, ReturnType), HasThis = HasThis, ExplicitThis = ExplicitThis, CallingConvention = (MethodCallingConvention)(byte)((byte)CallingConvention - 1) }; foreach (object parameter in Parameters) { val.Parameters.Add(new ParameterDefinition(GetTypeReference(module, parameter))); } return val; } } internal static class PatchInfoSerialization { private class Binder : SerializationBinder { public override Type BindToType(string assemblyName, string typeName) { Type[] array = new Type[3] { typeof(PatchInfo), typeof(Patch[]), typeof(Patch) }; foreach (Type type in array) { if (typeName == type.FullName) { return type; } } return Type.GetType($"{typeName}, {assemblyName}"); } } internal static byte[] Serialize(this PatchInfo patchInfo) { using MemoryStream memoryStream = new MemoryStream(); new BinaryFormatter().Serialize(memoryStream, patchInfo); return memoryStream.GetBuffer(); } internal static PatchInfo Deserialize(byte[] bytes) { BinaryFormatter obj = new BinaryFormatter { Binder = new Binder() }; MemoryStream serializationStream = new MemoryStream(bytes); return (PatchInfo)obj.Deserialize(serializationStream); } internal static int PriorityComparer(object obj, int index, int priority) { Traverse traverse = Traverse.Create(obj); int value = traverse.Field("priority").GetValue<int>(); int value2 = traverse.Field("index").GetValue<int>(); if (priority != value) { return -priority.CompareTo(value); } return index.CompareTo(value2); } } [Serializable] public class PatchInfo { public Patch[] prefixes = new Patch[0]; public Patch[] postfixes = new Patch[0]; public Patch[] transpilers = new Patch[0]; public Patch[] finalizers = new Patch[0]; public Patch[] ilmanipulators = new Patch[0]; public bool Debugging { get { if (!prefixes.Any((Patch p) => p.debug) && !postfixes.Any((Patch p) => p.debug) && !transpilers.Any((Patch p) => p.debug) && !finalizers.Any((Patch p) => p.debug)) { return ilmanipulators.Any((Patch p) => p.debug); } return true; } } public string[] DebugEmitPaths => (from p in prefixes.Concat(postfixes).Concat(transpilers).Concat(finalizers) .Concat(ilmanipulators) select p.debugEmitPath into p where p != null select p).ToArray(); internal void AddPrefixes(string owner, params HarmonyMethod[] methods) { prefixes = Add(owner, methods, prefixes); } [Obsolete("This method only exists for backwards compatibility since the class is public.")] public void AddPrefix(MethodInfo patch, string owner, int priority, string[] before, string[] after, bool debug) { AddPrefixes(owner, new HarmonyMethod(patch, priority, before, after, debug)); } public void RemovePrefix(string owner) { prefixes = Remove(owner, prefixes); } internal void AddPostfixes(string owner, params HarmonyMethod[] methods) { postfixes = Add(owner, methods, postfixes); } [Obsolete("This method only exists for backwards compatibility since the class is public.")] public void AddPostfix(MethodInfo patch, string owner, int priority, string[] before, string[] after, bool debug) { AddPostfixes(owner, new HarmonyMethod(patch, priority, before, after, debug)); } public void RemovePostfix(string owner) { postfixes = Remove(owner, postfixes); } internal void AddTranspilers(string owner, params HarmonyMethod[] methods) { transpilers = Add(owner, methods, transpilers); } [Obsolete("This method only exists for backwards compatibility since the class is public.")] public void AddTranspiler(MethodInfo patch, string owner, int priority, string[] before, string[] after, bool debug) { AddTranspilers(owner, new HarmonyMethod(patch, priority, before, after, debug)); } public void RemoveTranspiler(string owner) { transpilers = Remove(owner, transpilers); } internal void AddFinalizers(string owner, params HarmonyMethod[] methods) { finalizers = Add(owner, methods, finalizers); } [Obsolete("This method only exists for backwards compatibility since the class is public.")] public void AddFinalizer(MethodInfo patch, string owner, int priority, string[] before, string[] after, bool debug) { AddFinalizers(owner, new HarmonyMethod(patch, priority, before, after, debug)); } public void RemoveFinalizer(string owner) { finalizers = Remove(owner, finalizers); } internal void AddILManipulators(string owner, params HarmonyMethod[] methods) { ilmanipulators = Add(owner, methods, ilmanipulators); } public void RemoveILManipulator(string owner) { ilmanipulators = Remove(owner, ilmanipulators); } public void RemovePatch(MethodInfo patch) { prefixes = prefixes.Where((Patch p) => (object)p.PatchMethod != patch).ToArray(); postfixes = postfixes.Where((Patch p) => (object)p.PatchMethod != patch).ToArray(); transpilers = transpilers.Where((Patch p) => (object)p.PatchMethod != patch).ToArray(); finalizers = finalizers.Where((Patch p) => (object)p.PatchMethod != patch).ToArray(); ilmanipulators = ilmanipulators.Where((Patch p) => (object)p.PatchMethod != patch).ToArray(); } private static Patch[] Add(string owner, HarmonyMethod[] add, Patch[] current) { if (add.Length == 0) { return current; } int initialIndex = current.Length; return current.Concat(add.Where((HarmonyMethod method) => method != null).Select((HarmonyMethod method, int i) => new Patch(method, i + initialIndex, owner))).ToArray(); } private static Patch[] Remove(string owner, Patch[] current) { if (!(owner == "*")) { return current.Where((Patch patch) => patch.owner != owner).ToArray(); } return new Patch[0]; } } [Serializable] public class Patch : IComparable { public readonly int index; public readonly string owner; public readonly int priority; public readonly string[] before; public readonly string[] after; public readonly bool debug; public readonly string debugEmitPath; public readonly bool wrapTryCatch; [NonSerialized] private MethodInfo patchMethod; private int methodToken; private string moduleGUID; public MethodInfo PatchMethod { get { if ((object)patchMethod == null) { Module module = (from a in AppDomain.CurrentDomain.GetAssemblies() where !a.FullName.StartsWith("Microsoft.VisualStudio") select a).SelectMany((Assembly a) => a.GetLoadedModules()).First((Module m) => m.ModuleVersionId.ToString() == moduleGUID); patchMethod = (MethodInfo)module.ResolveMethod(methodToken); } return patchMethod; } set { patchMethod = value; methodToken = patchMethod.MetadataToken; moduleGUID = patchMethod.Module.ModuleVersionId.ToString(); } } public Patch(MethodInfo patch, int index, string owner, int priority, string[] before, string[] after, bool debug) { if (patch is DynamicMethod) { throw new Exception("Cannot directly reference dynamic method \"" + patch.FullDescription() + "\" in Harmony. Use a factory method instead that will return the dynamic method."); } this.index = index; this.owner = owner; this.priority = ((priority == -1) ? 400 : priority); this.before = before ?? new string[0]; this.after = after ?? new string[0]; this.debug = debug; PatchMethod = patch; } public Patch(MethodInfo patch, int index, string owner, int priority, string[] before, string[] after, bool debug, bool wrapTryCatch) { if (patch is DynamicMethod) { throw new Exception("Cannot directly reference dynamic method \"" + patch.FullDescription() + "\" in Harmony. Use a factory method instead that will return the dynamic method."); } this.index = index; this.owner = owner; this.priority = ((priority == -1) ? 400 : priority); this.before = before ?? new string[0]; this.after = after ?? new string[0]; this.debug = debug; this.wrapTryCatch = wrapTryCatch; PatchMethod = patch; } public Patch(MethodInfo patch, int index, string owner, int priority, string[] before, string[] after, bool debug, bool wrapTryCatch, string debugEmitPath) { if (patch is DynamicMethod) { throw new Exception("Cannot directly reference dynamic method \"" + patch.FullDescription() + "\" in Harmony. Use a factory method instead that will return the dynamic method."); } this.index = index; this.owner = owner; this.priority = ((priority == -1) ? 400 : priority); this.before = before ?? new string[0]; this.after = after ?? new string[0]; this.debug = debug; this.debugEmitPath = debugEmitPath; this.wrapTryCatch = wrapTryCatch; PatchMethod = patch; } public Patch(HarmonyMethod method, int index, string owner) : this(method.method, index, owner, method.priority, method.before, method.after, method.debug.GetValueOrDefault(), method.wrapTryCatch.GetValueOrDefault(), method.debugEmitPath) { } public MethodInfo GetMethod(MethodBase original) { MethodInfo methodInfo = PatchMethod; if ((object)methodInfo.ReturnType != typeof(DynamicMethod) && (object)methodInfo.ReturnType != typeof(MethodInfo)) { return methodInfo; } if (!methodInfo.IsStatic) { return methodInfo; } ParameterInfo[] parameters = methodInfo.GetParameters(); if (parameters.Length != 1) { return methodInfo; } if ((object)parameters[0].ParameterType != typeof(MethodBase)) { return methodInfo; } return methodInfo.Invoke(null, new object[1] { original }) as MethodInfo; } public override bool Equals(object obj) { if (obj != null && obj is Patch) { return (object)PatchMethod == ((Patch)obj).PatchMethod; } return false; } public int CompareTo(object obj) { return PatchInfoSerialization.PriorityComparer(obj, index, priority); } public override int GetHashCode() { return PatchMethod.GetHashCode(); } } public class PatchClassProcessor { private readonly Harmony instance; private readonly Type containerType; private readonly HarmonyMethod containerAttributes; private readonly Dictionary<Type, MethodInfo> auxilaryMethods; private readonly List<AttributePatch> patchMethods; private static readonly List<Type> auxilaryTypes = new List<Type> { typeof(HarmonyPrepare), typeof(HarmonyCleanup), typeof(HarmonyTargetMethod), typeof(HarmonyTargetMethods) }; public PatchClassProcessor(Harmony instance, Type type) : this(instance, type, allowUnannotatedType: false) { } public PatchClassProcessor(Harmony instance, Type type, bool allowUnannotatedType) { if (instance == null) { throw new ArgumentNullException("instance"); } if ((object)type == null) { throw new ArgumentNullException("type"); } this.instance = instance; containerType = type; List<HarmonyMethod> fromType = HarmonyMethodExtensions.GetFromType(type); if (!allowUnannotatedType && (fromType == null || fromType.Count == 0)) { return; } containerAttributes = HarmonyMethod.Merge(fromType); MethodType? methodType = containerAttributes.methodType; if (!methodType.HasValue) { containerAttributes.methodType = MethodType.Normal; } auxilaryMethods = new Dictionary<Type, MethodInfo>(); foreach (Type auxilaryType in auxilaryTypes) { MethodInfo patchMethod = PatchTools.GetPatchMethod(containerType, auxilaryType.FullName); if ((object)patchMethod != null) { auxilaryMethods[auxilaryType] = patchMethod; } } patchMethods = PatchTools.GetPatchMethods(containerType, (object)containerAttributes.GetDeclaringType() != null); foreach (AttributePatch patchMethod2 in patchMethods) { MethodInfo method = patchMethod2.info.method; patchMethod2.info = containerAttributes.Merge(patchMethod2.info); patchMethod2.info.method = method; } } public List<MethodInfo> Patch() { if (containerAttributes == null) { return null; } Exception exception = null; if (!RunMethod<HarmonyPrepare, bool>(defaultIfNotExisting: true, defaultIfFailing: false, null, new object[0])) { RunMethod<HarmonyCleanup>(ref exception, new object[0]); ReportException(exception, null); return new List<MethodInfo>(); } List<MethodInfo> result = new List<MethodInfo>(); MethodBase lastOriginal = null; try { List<MethodBase> bulkMethods = GetBulkMethods(); if (bulkMethods.Count == 1) { lastOriginal = bulkMethods[0]; } ReversePatch(ref lastOriginal); result = ((bulkMethods.Count > 0) ? BulkPatch(bulkMethods, ref lastOriginal) : PatchWithAttributes(ref lastOriginal)); } catch (Exception ex) { exception = ex; } RunMethod<HarmonyCleanup>(ref exception, new object[1] { exception }); ReportException(exception, lastOriginal); return result; } private void ReversePatch(ref MethodBase lastOriginal) { for (int i = 0; i < patchMethods.Count; i++) { AttributePatch attributePatch = patchMethods[i]; if (attributePatch.type == HarmonyPatchType.ReversePatch) { MethodBase originalMethod = attributePatch.info.GetOriginalMethod(); if ((object)originalMethod != null) { lastOriginal = originalMethod; } ReversePatcher reversePatcher = instance.CreateReversePatcher(lastOriginal, attributePatch.info); lock (PatchProcessor.locker) { reversePatcher.Patch(); } } } } private List<MethodInfo> BulkPatch(List<MethodBase> originals, ref MethodBase lastOriginal) { PatchJobs<MethodInfo> patchJobs = new PatchJobs<MethodInfo>(); for (int i = 0; i < originals.Count; i++) { lastOriginal = originals[i]; PatchJobs<MethodInfo>.Job job = patchJobs.GetJob(lastOriginal); foreach (AttributePatch patchMethod in patchMethods) { string text = "You cannot combine TargetMethod, TargetMethods or [HarmonyPatchAll] with individual annotations"; HarmonyMethod info = patchMethod.info; if (info.methodName != null) { throw new ArgumentException(text + " [" + info.methodName + "]"); } if (info.methodType.HasValue && info.methodType.Value != 0) { throw new ArgumentException($"{text} [{info.methodType}]"); } if (info.argumentTypes != null) { throw new ArgumentException(text + " [" + info.argumentTypes.Description() + "]");
BepInExPack\BepInEx\core\AssetRipper.Primitives.dll
Decompiled 2 months agousing System; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using AssetRipper.Primitives.Extensions; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("VersionUtilities.Tests")] [assembly: AssemblyCompany("AssetRipper")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright (c) 2022-2024 ds5678")] [assembly: AssemblyDescription("Managed library for primitive types used in AssetRipper.")] [assembly: AssemblyFileVersion("3.1.3")] [assembly: AssemblyInformationalVersion("3.1.3+9c4a7d8127cc9af1e5f61edee8eeb90bd90676aa")] [assembly: AssemblyProduct("AssetRipper.Primitives")] [assembly: AssemblyTitle("AssetRipper.Primitives")] [assembly: AssemblyVersion("3.1.3.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace System { internal readonly struct Index : IEquatable<Index> { private static class ThrowHelper { [DoesNotReturn] public static void ThrowValueArgumentOutOfRange_NeedNonNegNumException() { throw new ArgumentOutOfRangeException("value", "Non-negative number required."); } } private readonly int _value; public static Index Start => new Index(0); public static Index End => new Index(-1); public int Value { get { if (_value < 0) { return ~_value; } return _value; } } public bool IsFromEnd => _value < 0; public Index(int value, bool fromEnd = false) { if (value < 0) { ThrowHelper.ThrowValueArgumentOutOfRange_NeedNonNegNumException(); } if (fromEnd) { _value = ~value; } else { _value = value; } } private Index(int value) { _value = value; } public static Index FromStart(int value) { if (value < 0) { ThrowHelper.ThrowValueArgumentOutOfRange_NeedNonNegNumException(); } return new Index(value); } public static Index FromEnd(int value) { if (value < 0) { ThrowHelper.ThrowValueArgumentOutOfRange_NeedNonNegNumException(); } return new Index(~value); } public int GetOffset(int length) { int num = _value; if (IsFromEnd) { num += length + 1; } return num; } public override bool Equals([NotNullWhen(true)] object? value) { if (value is Index) { return _value == ((Index)value)._value; } return false; } public bool Equals(Index other) { return _value == other._value; } public override int GetHashCode() { return _value; } public static implicit operator Index(int value) { return FromStart(value); } public override string ToString() { if (IsFromEnd) { return ToStringFromEnd(); } return ((uint)Value).ToString(); } private string ToStringFromEnd() { return "^" + Value; } } } namespace System.Runtime.Versioning { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)] internal sealed class RequiresPreviewFeaturesAttribute : Attribute { public string? Message { get; } public string? Url { get; set; } public RequiresPreviewFeaturesAttribute() { } public RequiresPreviewFeaturesAttribute(string? message) { Message = message; } } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false, AllowMultiple = false)] internal sealed class AsyncMethodBuilderAttribute : Attribute { public Type BuilderType { get; } public AsyncMethodBuilderAttribute(Type builderType) { BuilderType = builderType; } } [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] internal sealed class CallerArgumentExpressionAttribute : Attribute { public string ParameterName { get; } public CallerArgumentExpressionAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, Inherited = false)] internal sealed class CollectionBuilderAttribute : Attribute { public Type BuilderType { get; } public string MethodName { get; } public CollectionBuilderAttribute(Type builderType, string methodName) { BuilderType = builderType; MethodName = methodName; } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)] internal sealed class CompilerFeatureRequiredAttribute : Attribute { public const string RefStructs = "RefStructs"; public const string RequiredMembers = "RequiredMembers"; public string FeatureName { get; } public bool IsOptional { get; set; } public CompilerFeatureRequiredAttribute(string featureName) { FeatureName = featureName; } } [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] internal sealed class InterpolatedStringHandlerArgumentAttribute : Attribute { public string[] Arguments { get; } public InterpolatedStringHandlerArgumentAttribute(string argument) { Arguments = new string[1] { argument }; } public InterpolatedStringHandlerArgumentAttribute(params string[] arguments) { Arguments = arguments; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)] internal sealed class InterpolatedStringHandlerAttribute : Attribute { } [EditorBrowsable(EditorBrowsableState.Never)] internal static class IsExternalInit { } [AttributeUsage(AttributeTargets.Method, Inherited = false)] internal sealed class ModuleInitializerAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = false)] internal sealed class RequiredMemberAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] [EditorBrowsable(EditorBrowsableState.Never)] internal sealed class RequiresLocationAttribute : Attribute { } [AttributeUsage(AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event | AttributeTargets.Interface, Inherited = false)] internal sealed class SkipLocalsInitAttribute : Attribute { } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class DisallowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method, Inherited = false)] internal sealed class DoesNotReturnAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)] internal sealed class ExperimentalAttribute : Attribute { public string DiagnosticId { get; } public string? UrlFormat { get; set; } public ExperimentalAttribute(string diagnosticId) { DiagnosticId = diagnosticId; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullAttribute : Attribute { public string[] Members { get; } public MemberNotNullAttribute(string member) { Members = new string[1] { member }; } public MemberNotNullAttribute(params string[] members) { Members = members; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] internal sealed class MemberNotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public string[] Members { get; } public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; Members = new string[1] { member }; } public MemberNotNullWhenAttribute(bool returnValue, params string[] members) { ReturnValue = returnValue; Members = members; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] internal sealed class NotNullIfNotNullAttribute : Attribute { public string ParameterName { get; } public NotNullIfNotNullAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false, Inherited = false)] internal sealed class SetsRequiredMembersAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] internal sealed class StringSyntaxAttribute : Attribute { public const string CompositeFormat = "CompositeFormat"; public const string DateOnlyFormat = "DateOnlyFormat"; public const string DateTimeFormat = "DateTimeFormat"; public const string EnumFormat = "EnumFormat"; public const string GuidFormat = "GuidFormat"; public const string Json = "Json"; public const string NumericFormat = "NumericFormat"; public const string Regex = "Regex"; public const string TimeOnlyFormat = "TimeOnlyFormat"; public const string TimeSpanFormat = "TimeSpanFormat"; public const string Uri = "Uri"; public const string Xml = "Xml"; public string Syntax { get; } public object?[] Arguments { get; } public StringSyntaxAttribute(string syntax) { Syntax = syntax; Arguments = new object[0]; } public StringSyntaxAttribute(string syntax, params object?[] arguments) { Syntax = syntax; Arguments = arguments; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] internal sealed class UnscopedRefAttribute : Attribute { } } namespace AssetRipper.Primitives { public readonly struct UnityVersion : IEquatable<UnityVersion>, IComparable, IComparable<UnityVersion> { private const ulong subMajorMask = 281474976710655uL; private const ulong subMinorMask = 4294967295uL; private const ulong subBuildMask = 65535uL; private const ulong subTypeMask = 255uL; private const int majorOffset = 48; private const int minorOffset = 32; private const int buildOffset = 16; private const int typeOffset = 8; private const ulong byteMask = 255uL; private const ulong ushortMask = 65535uL; private readonly ulong m_data; public ushort Major => (ushort)((m_data >> 48) & 0xFFFF); public ushort Minor => (ushort)((m_data >> 32) & 0xFFFF); public ushort Build => (ushort)((m_data >> 16) & 0xFFFF); public UnityVersionType Type => (UnityVersionType)((m_data >> 8) & 0xFF); public byte TypeNumber => (byte)(m_data & 0xFF); public static UnityVersion MinVersion { get; } = new UnityVersion(0uL); public static UnityVersion MaxVersion { get; } = new UnityVersion(ulong.MaxValue); public bool Equals(ushort major) { return this == From(major); } public bool Equals(ushort major, ushort minor) { return this == From(major, minor); } public bool Equals(ushort major, ushort minor, ushort build) { return this == From(major, minor, build); } public bool Equals(ushort major, ushort minor, ushort build, UnityVersionType type) { return this == From(major, minor, build, type); } public bool Equals(ushort major, ushort minor, ushort build, UnityVersionType type, byte typeNumber) { return this == new UnityVersion(major, minor, build, type, typeNumber); } public bool Equals(string version) { return this == Parse(version); } public bool LessThan(ushort major) { return this < From(major); } public bool LessThan(ushort major, ushort minor) { return this < From(major, minor); } public bool LessThan(ushort major, ushort minor, ushort build) { return this < From(major, minor, build); } public bool LessThan(ushort major, ushort minor, ushort build, UnityVersionType type) { return this < From(major, minor, build, type); } public bool LessThan(ushort major, ushort minor, ushort build, UnityVersionType type, byte typeNumber) { return this < new UnityVersion(major, minor, build, type, typeNumber); } public bool LessThan(string version) { return this < Parse(version); } public bool LessThanOrEquals(ushort major) { return this <= From(major); } public bool LessThanOrEquals(ushort major, ushort minor) { return this <= From(major, minor); } public bool LessThanOrEquals(ushort major, ushort minor, ushort build) { return this <= From(major, minor, build); } public bool LessThanOrEquals(ushort major, ushort minor, ushort build, UnityVersionType type) { return this <= From(major, minor, build, type); } public bool LessThanOrEquals(ushort major, ushort minor, ushort build, UnityVersionType type, byte typeNumber) { return this <= new UnityVersion(major, minor, build, type, typeNumber); } public bool LessThanOrEquals(string version) { return this <= Parse(version); } public bool GreaterThan(ushort major) { return this > From(major); } public bool GreaterThan(ushort major, ushort minor) { return this > From(major, minor); } public bool GreaterThan(ushort major, ushort minor, ushort build) { return this > From(major, minor, build); } public bool GreaterThan(ushort major, ushort minor, ushort build, UnityVersionType type) { return this > From(major, minor, build, type); } public bool GreaterThan(ushort major, ushort minor, ushort build, UnityVersionType type, byte typeNumber) { return this > new UnityVersion(major, minor, build, type, typeNumber); } public bool GreaterThan(string version) { return this > Parse(version); } public bool GreaterThanOrEquals(ushort major) { return this >= From(major); } public bool GreaterThanOrEquals(ushort major, ushort minor) { return this >= From(major, minor); } public bool GreaterThanOrEquals(ushort major, ushort minor, ushort build) { return this >= From(major, minor, build); } public bool GreaterThanOrEquals(ushort major, ushort minor, ushort build, UnityVersionType type) { return this >= From(major, minor, build, type); } public bool GreaterThanOrEquals(ushort major, ushort minor, ushort build, UnityVersionType type, byte typeNumber) { return this >= new UnityVersion(major, minor, build, type, typeNumber); } public bool GreaterThanOrEquals(string version) { return this >= Parse(version); } private UnityVersion From(ushort major) { return new UnityVersion(((ulong)major << 48) | (0xFFFFFFFFFFFFuL & m_data)); } private UnityVersion From(ushort major, ushort minor) { return new UnityVersion(((ulong)major << 48) | ((ulong)minor << 32) | (0xFFFFFFFFu & m_data)); } private UnityVersion From(ushort major, ushort minor, ushort build) { return new UnityVersion(((ulong)major << 48) | ((ulong)minor << 32) | ((ulong)build << 16) | (0xFFFF & m_data)); } private UnityVersion From(ushort major, ushort minor, ushort build, UnityVersionType type) { return new UnityVersion(((ulong)major << 48) | ((ulong)minor << 32) | ((ulong)build << 16) | ((ulong)type << 8) | (0xFF & m_data)); } public UnityVersion(ushort major) { m_data = (ulong)major << 48; } public UnityVersion(ushort major, ushort minor) { m_data = ((ulong)major << 48) | ((ulong)minor << 32); } public UnityVersion(ushort major, ushort minor, ushort build) { m_data = ((ulong)major << 48) | ((ulong)minor << 32) | ((ulong)build << 16); } public UnityVersion(ushort major, ushort minor, ushort build, UnityVersionType type) { m_data = ((ulong)major << 48) | ((ulong)minor << 32) | ((ulong)build << 16) | ((ulong)type << 8); } public UnityVersion(ushort major, ushort minor, ushort build, UnityVersionType type, byte typeNumber) { m_data = ((ulong)major << 48) | ((ulong)minor << 32) | ((ulong)build << 16) | ((ulong)type << 8) | typeNumber; } private UnityVersion(ulong data) { m_data = data; } public ulong GetBits() { return m_data; } public static UnityVersion FromBits(ulong bits) { return new UnityVersion(bits); } public int CompareTo(object? obj) { if (!(obj is UnityVersion other)) { return 1; } return CompareTo(other); } public int CompareTo(UnityVersion other) { ulong data = m_data; return data.CompareTo(other.m_data); } public override bool Equals(object? obj) { if (obj is UnityVersion unityVersion) { return this == unityVersion; } return false; } public bool Equals(UnityVersion other) { return this == other; } public override int GetHashCode() { ulong data = m_data; return data.GetHashCode(); } public static UnityVersion Max(UnityVersion left, UnityVersion right) { if (!(left > right)) { return right; } return left; } public static UnityVersion Min(UnityVersion left, UnityVersion right) { if (!(left < right)) { return right; } return left; } public static ulong Distance(UnityVersion left, UnityVersion right) { if (left.m_data >= right.m_data) { return left.m_data - right.m_data; } return right.m_data - left.m_data; } public UnityVersion GetClosestVersion(UnityVersion[] versions) { if (versions == null) { throw new ArgumentNullException("versions"); } if (versions.Length == 0) { throw new ArgumentException("Length cannot be zero", "versions"); } UnityVersion unityVersion = versions[0]; ulong num = Distance(this, unityVersion); for (int i = 1; i < versions.Length; i++) { ulong num2 = Distance(this, versions[i]); if (num2 < num) { num = num2; unityVersion = versions[i]; } } return unityVersion; } public UnityVersion ChangeMajor(ushort value) { return new UnityVersion(value, Minor, Build, Type, TypeNumber); } public UnityVersion ChangeMinor(ushort value) { return new UnityVersion(Major, value, Build, Type, TypeNumber); } public UnityVersion ChangeBuild(ushort value) { return new UnityVersion(Major, Minor, value, Type, TypeNumber); } public UnityVersion ChangeType(UnityVersionType value) { return new UnityVersion(Major, Minor, Build, value, TypeNumber); } public UnityVersion ChangeTypeNumber(byte value) { return new UnityVersion(Major, Minor, Build, Type, value); } public static bool operator ==(UnityVersion left, UnityVersion right) { return left.m_data == right.m_data; } public static bool operator !=(UnityVersion left, UnityVersion right) { return left.m_data != right.m_data; } public static bool operator >(UnityVersion left, UnityVersion right) { return left.m_data > right.m_data; } public static bool operator >=(UnityVersion left, UnityVersion right) { return left.m_data >= right.m_data; } public static bool operator <(UnityVersion left, UnityVersion right) { return left.m_data < right.m_data; } public static bool operator <=(UnityVersion left, UnityVersion right) { return left.m_data <= right.m_data; } public override string ToString() { return ToString(UnityVersionFormatFlags.Default); } public string ToString(UnityVersionFormatFlags flags) { if ((flags & UnityVersionFormatFlags.ExcludeType) == 0) { if (Type == UnityVersionType.China && (flags & UnityVersionFormatFlags.UseShortChineseFormat) == 0) { return $"{Major}.{Minor}.{Build}f1c{TypeNumber}"; } return $"{Major}.{Minor}.{Build}{Type.ToCharacter()}{TypeNumber}"; } return ToStringWithoutType(); } public string ToString(UnityVersionFormatFlags flags, string customEngineString = "") { if (customEngineString.Length != 0) { if ((flags & UnityVersionFormatFlags.ExcludeType) == 0) { if (Type == UnityVersionType.China && (flags & UnityVersionFormatFlags.UseShortChineseFormat) == 0) { return $"{Major}.{Minor}.{Build}f1c{TypeNumber}{customEngineString}"; } return $"{Major}.{Minor}.{Build}{Type.ToCharacter()}{TypeNumber}{customEngineString}"; } return ToStringWithoutType(); } return ToString(flags); } public string ToStringWithoutType() { return $"{Major}.{Minor}.{Build}"; } public static UnityVersion Parse(string s) { string customEngine; return Parse(s, out customEngine); } public static UnityVersion Parse(string s, out string? customEngine) { if (!TryParse(s, out var version, out customEngine)) { throw new ArgumentException("Invalid version format: " + s, "s"); } return version; } public static bool TryParse(string s, out UnityVersion version, out string? customEngine) { if (string.IsNullOrEmpty(s)) { customEngine = null; version = default(UnityVersion); return false; } if (UnityVersionRegexes.GetChinaRegex().TryMatch(s, out Match match)) { int num = int.Parse(match.Groups[1].Value); int num2 = int.Parse(match.Groups[2].Value); int num3 = int.Parse(match.Groups[3].Value); int num4 = int.Parse(match.Groups[4].Value); customEngine = GetNullableString(match.Groups[5]); version = new UnityVersion((ushort)num, (ushort)num2, (ushort)num3, UnityVersionType.China, (byte)num4); return true; } if (UnityVersionRegexes.GetNormalRegex().TryMatch(s, out match)) { int num5 = int.Parse(match.Groups[1].Value); int num6 = int.Parse(match.Groups[2].Value); int num7 = int.Parse(match.Groups[3].Value); char c = match.Groups[4].Value[0]; int num8 = int.Parse(match.Groups[5].Value); customEngine = GetNullableString(match.Groups[6]); version = new UnityVersion((ushort)num5, (ushort)num6, (ushort)num7, c.ToUnityVersionType(), (byte)num8); return true; } if (UnityVersionRegexes.GetMajorMinorBuildRegex().TryMatch(s, out match)) { int num9 = int.Parse(match.Groups[1].Value); int num10 = int.Parse(match.Groups[2].Value); int num11 = int.Parse(match.Groups[3].Value); customEngine = null; version = ((num9 != 0 || num10 != 0 || num11 != 0) ? new UnityVersion((ushort)num9, (ushort)num10, (ushort)num11, UnityVersionType.Final, 1) : default(UnityVersion)); return true; } if (UnityVersionRegexes.GetMajorMinorRegex().TryMatch(s, out match)) { int num12 = int.Parse(match.Groups[1].Value); int num13 = int.Parse(match.Groups[2].Value); customEngine = null; version = ((num12 != 0 || num13 != 0) ? new UnityVersion((ushort)num12, (ushort)num13, 0, UnityVersionType.Final, 1) : default(UnityVersion)); return true; } if (UnityVersionRegexes.GetMajorRegex().TryMatch(s, out match)) { int num14 = int.Parse(match.Groups[1].Value); customEngine = null; version = ((num14 != 0) ? new UnityVersion((ushort)num14, 0, 0, UnityVersionType.Final, 1) : default(UnityVersion)); return true; } customEngine = null; version = default(UnityVersion); return false; static string? GetNullableString(Capture capture) { if (capture.Length != 0) { return capture.Value; } return null; } } } [Flags] public enum UnityVersionFormatFlags { Default = 0, ExcludeType = 1, UseShortChineseFormat = 2 } internal static class UnityVersionRegexes { private const RegexOptions Options = RegexOptions.None; [StringSyntax("regex")] private const string Major = "([0-9]+)"; [StringSyntax("regex")] private const string MajorMinor = "([0-9]+)\\.([0-9]+)"; [StringSyntax("regex")] private const string MajorMinorBuild = "([0-9]+)\\.([0-9]+)\\.([0-9]+)"; [StringSyntax("regex")] private const string Normal = "([0-9]+)\\.([0-9]+)\\.([0-9]+)\\.?([abcfpx])([0-9]+)((?:.|[\\r\\n])+)?"; [StringSyntax("regex")] private const string China = "([0-9]+)\\.([0-9]+)\\.([0-9]+)\\.?f1c([0-9]+)((?:.|[\\r\\n])+)?"; private static readonly Regex majorRegex = new Regex("([0-9]+)", RegexOptions.None); private static readonly Regex majorMinorRegex = new Regex("([0-9]+)\\.([0-9]+)", RegexOptions.None); private static readonly Regex majorMinorBuildRegex = new Regex("([0-9]+)\\.([0-9]+)\\.([0-9]+)", RegexOptions.None); private static readonly Regex normalRegex = new Regex("([0-9]+)\\.([0-9]+)\\.([0-9]+)\\.?([abcfpx])([0-9]+)((?:.|[\\r\\n])+)?", RegexOptions.None); private static readonly Regex chinaRegex = new Regex("([0-9]+)\\.([0-9]+)\\.([0-9]+)\\.?f1c([0-9]+)((?:.|[\\r\\n])+)?", RegexOptions.None); public static Regex GetMajorRegex() { return majorRegex; } public static Regex GetMajorMinorRegex() { return majorMinorRegex; } public static Regex GetMajorMinorBuildRegex() { return majorMinorBuildRegex; } public static Regex GetNormalRegex() { return normalRegex; } public static Regex GetChinaRegex() { return chinaRegex; } } public enum UnityVersionType : byte { Alpha = 0, Beta = 1, China = 2, Final = 3, Patch = 4, Experimental = 5, MinValue = 0, MaxValue = 5 } public static class UnityVersionTypeExtentions { public static char ToCharacter(this UnityVersionType type) { return type switch { UnityVersionType.Alpha => 'a', UnityVersionType.Beta => 'b', UnityVersionType.China => 'c', UnityVersionType.Final => 'f', UnityVersionType.Patch => 'p', UnityVersionType.Experimental => 'x', _ => 'u', }; } } } namespace AssetRipper.Primitives.Extensions { public static class CharacterExtensions { public static UnityVersionType ToUnityVersionType(this char c) { return c switch { 'a' => UnityVersionType.Alpha, 'b' => UnityVersionType.Beta, 'c' => UnityVersionType.China, 'f' => UnityVersionType.Final, 'p' => UnityVersionType.Patch, 'x' => UnityVersionType.Experimental, _ => throw new ArgumentException($"There is no version type {c}", "c"), }; } } internal static class RegexExtensions { public static bool TryMatch(this Regex regex, string input, [NotNullWhen(true)] out Match? match) { match = regex.Match(input); if (match.Success) { return true; } match = null; return false; } } }
BepInExPack\BepInEx\core\BepInEx.Core.dll
Decompiled 2 months ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Security.Cryptography; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.ConsoleUtil; using BepInEx.Core.Logging.Interpolation; using BepInEx.Logging; using BepInEx.Unix; using HarmonyLib; using HarmonyLib.Tools; using Microsoft.Win32.SafeHandles; using Mono.Cecil; using Mono.Collections.Generic; using MonoMod.Utils; using SemanticVersioning; using UnityInjector.ConsoleUtil; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("BepInEx.Preloader.Core")] [assembly: InternalsVisibleTo("BepInEx.Unity.Mono")] [assembly: InternalsVisibleTo("BepInEx.NET.Framework.Launcher")] [assembly: InternalsVisibleTo("BepInEx.NET.CoreCLR")] [assembly: InternalsVisibleTo("BepInEx.Unity.IL2CPP")] [assembly: InternalsVisibleTo("BepInExTests")] [assembly: AssemblyCompany("BepInEx")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © 2022 BepInEx Team")] [assembly: AssemblyDescription("BepInEx Core library")] [assembly: AssemblyFileVersion("6.0.0.0")] [assembly: AssemblyInformationalVersion("6.0.0-be.697+53625800b86f6c68751445248260edf0b27a71c2")] [assembly: AssemblyProduct("BepInEx.Core")] [assembly: AssemblyTitle("BepInEx.Core")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("6.0.0.0")] [module: UnverifiableCode] namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false)] internal sealed class InterpolatedStringHandlerAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter)] internal sealed class InterpolatedStringHandlerArgumentAttribute : Attribute { public string[] Arguments { get; } public InterpolatedStringHandlerArgumentAttribute(string argument) { Arguments = new string[1] { argument }; } public InterpolatedStringHandlerArgumentAttribute(params string[] arguments) { Arguments = arguments; } } } namespace UnityInjector.ConsoleUtil { internal static class SafeConsole { private delegate ConsoleColor GetColorDelegate(); private delegate void SetColorDelegate(ConsoleColor value); private delegate string GetStringDelegate(); private delegate void SetStringDelegate(string value); private static GetColorDelegate _getBackgroundColor; private static SetColorDelegate _setBackgroundColor; private static GetColorDelegate _getForegroundColor; private static SetColorDelegate _setForegroundColor; private static GetStringDelegate _getTitle; private static SetStringDelegate _setTitle; public static bool BackgroundColorExists { get; private set; } public static ConsoleColor BackgroundColor { get { return _getBackgroundColor(); } set { _setBackgroundColor(value); } } public static bool ForegroundColorExists { get; private set; } public static ConsoleColor ForegroundColor { get { return _getForegroundColor(); } set { _setForegroundColor(value); } } public static bool TitleExists { get; private set; } public static string Title { get { return _getTitle(); } set { _setTitle(value); } } static SafeConsole() { InitColors(typeof(Console)); } private static void InitColors(Type tConsole) { MethodInfo method = tConsole.GetMethod("get_ForegroundColor", BindingFlags.Static | BindingFlags.Public); MethodInfo method2 = tConsole.GetMethod("set_ForegroundColor", BindingFlags.Static | BindingFlags.Public); MethodInfo method3 = tConsole.GetMethod("get_BackgroundColor", BindingFlags.Static | BindingFlags.Public); MethodInfo method4 = tConsole.GetMethod("set_BackgroundColor", BindingFlags.Static | BindingFlags.Public); MethodInfo method5 = tConsole.GetMethod("get_Title", BindingFlags.Static | BindingFlags.Public); MethodInfo method6 = tConsole.GetMethod("set_Title", BindingFlags.Static | BindingFlags.Public); _setForegroundColor = (((object)method2 != null) ? ((SetColorDelegate)Delegate.CreateDelegate(typeof(SetColorDelegate), method2)) : ((SetColorDelegate)delegate { })); _setBackgroundColor = (((object)method4 != null) ? ((SetColorDelegate)Delegate.CreateDelegate(typeof(SetColorDelegate), method4)) : ((SetColorDelegate)delegate { })); _getForegroundColor = (((object)method != null) ? ((GetColorDelegate)Delegate.CreateDelegate(typeof(GetColorDelegate), method)) : ((GetColorDelegate)(() => ConsoleColor.Gray))); _getBackgroundColor = (((object)method3 != null) ? ((GetColorDelegate)Delegate.CreateDelegate(typeof(GetColorDelegate), method3)) : ((GetColorDelegate)(() => ConsoleColor.Black))); _getTitle = (((object)method5 != null) ? ((GetStringDelegate)Delegate.CreateDelegate(typeof(GetStringDelegate), method5)) : ((GetStringDelegate)(() => string.Empty))); _setTitle = (((object)method6 != null) ? ((SetStringDelegate)Delegate.CreateDelegate(typeof(SetStringDelegate), method6)) : ((SetStringDelegate)delegate { })); BackgroundColorExists = _setBackgroundColor != null && _getBackgroundColor != null; ForegroundColorExists = _setForegroundColor != null && _getForegroundColor != null; TitleExists = _setTitle != null && _getTitle != null; } } internal class ConsoleEncoding : Encoding { private readonly byte[] _zeroByte = new byte[0]; private readonly char[] _zeroChar = new char[0]; private byte[] _byteBuffer = new byte[256]; private char[] _charBuffer = new char[256]; private readonly uint _codePage; public override int CodePage => (int)_codePage; public static Encoding OutputEncoding => new ConsoleEncoding(ConsoleCodePage); public static uint ConsoleCodePage { get { return GetConsoleOutputCP(); } set { SetConsoleOutputCP(value); } } private void ExpandByteBuffer(int count) { if (_byteBuffer.Length < count) { _byteBuffer = new byte[count]; } } private void ExpandCharBuffer(int count) { if (_charBuffer.Length < count) { _charBuffer = new char[count]; } } private void ReadByteBuffer(byte[] bytes, int index, int count) { for (int i = 0; i < count; i++) { bytes[index + i] = _byteBuffer[i]; } } private void ReadCharBuffer(char[] chars, int index, int count) { for (int i = 0; i < count; i++) { chars[index + i] = _charBuffer[i]; } } private void WriteByteBuffer(byte[] bytes, int index, int count) { ExpandByteBuffer(count); for (int i = 0; i < count; i++) { _byteBuffer[i] = bytes[index + i]; } } private void WriteCharBuffer(char[] chars, int index, int count) { ExpandCharBuffer(count); for (int i = 0; i < count; i++) { _charBuffer[i] = chars[index + i]; } } private ConsoleEncoding(uint codePage) { _codePage = codePage; } public static uint GetActiveCodePage() { return GetACP(); } public static ConsoleEncoding GetEncoding(uint codePage) { return new ConsoleEncoding(codePage); } public override int GetByteCount(char[] chars, int index, int count) { WriteCharBuffer(chars, index, count); return WideCharToMultiByte(_codePage, 0u, chars, count, _zeroByte, 0, IntPtr.Zero, IntPtr.Zero); } public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { int byteCount = GetByteCount(chars, charIndex, charCount); WriteCharBuffer(chars, charIndex, charCount); ExpandByteBuffer(byteCount); WideCharToMultiByte(_codePage, 0u, chars, charCount, _byteBuffer, byteCount, IntPtr.Zero, IntPtr.Zero); int num = Math.Min(bytes.Length, byteCount); ReadByteBuffer(bytes, byteIndex, num); return num; } public override int GetCharCount(byte[] bytes, int index, int count) { WriteByteBuffer(bytes, index, count); return MultiByteToWideChar(_codePage, 0u, bytes, count, _zeroChar, 0); } public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { int charCount = GetCharCount(bytes, byteIndex, byteCount); WriteByteBuffer(bytes, byteIndex, byteCount); ExpandCharBuffer(charCount); MultiByteToWideChar(_codePage, 0u, bytes, byteCount, _charBuffer, charCount); int num = Math.Min(chars.Length, charCount); ReadCharBuffer(chars, charIndex, num); return num; } public override int GetMaxByteCount(int charCount) { return charCount * 4; } public override int GetMaxCharCount(int byteCount) { return byteCount; } [DllImport("kernel32.dll")] private static extern uint GetConsoleOutputCP(); [DllImport("kernel32.dll")] private static extern uint GetACP(); [DllImport("kernel32.dll", SetLastError = true)] private static extern int MultiByteToWideChar(uint codePage, uint dwFlags, [In][MarshalAs(UnmanagedType.LPArray)] byte[] lpMultiByteStr, int cbMultiByte, [Out][MarshalAs(UnmanagedType.LPWStr)] char[] lpWideCharStr, int cchWideChar); [DllImport("kernel32.dll")] private static extern IntPtr SetConsoleOutputCP(uint codepage); [DllImport("kernel32.dll", SetLastError = true)] private static extern int WideCharToMultiByte(uint codePage, uint dwFlags, [In][MarshalAs(UnmanagedType.LPWStr)] char[] lpWideCharStr, int cchWideChar, [Out][MarshalAs(UnmanagedType.LPArray)] byte[] lpMultiByteStr, int cbMultiByte, IntPtr lpDefaultChar, IntPtr lpUsedDefaultChar); } internal class ConsoleWindow { [UnmanagedFunctionPointer(CallingConvention.Winapi)] [return: MarshalAs(UnmanagedType.Bool)] private delegate bool SetForegroundWindowDelegate(IntPtr hWnd); [UnmanagedFunctionPointer(CallingConvention.Winapi)] private delegate IntPtr GetForegroundWindowDelegate(); [UnmanagedFunctionPointer(CallingConvention.Winapi)] private delegate IntPtr GetSystemMenuDelegate(IntPtr hwnd, bool bRevert); [UnmanagedFunctionPointer(CallingConvention.Winapi)] private delegate bool DeleteMenuDelegate(IntPtr hMenu, uint uPosition, uint uFlags); private const int STD_OUTPUT_HANDLE = -11; private const uint SC_CLOSE = 61536u; private const uint MF_BYCOMMAND = 0u; private const uint LOAD_LIBRARY_SEARCH_SYSTEM32 = 2048u; public static IntPtr ConsoleOutHandle; public static IntPtr OriginalStdoutHandle; private static bool methodsInited; private static SetForegroundWindowDelegate setForeground; private static GetForegroundWindowDelegate getForeground; private static GetSystemMenuDelegate getSystemMenu; private static DeleteMenuDelegate deleteMenu; public static bool IsAttached { get; private set; } public static string Title { set { if (IsAttached) { if (value == null) { throw new ArgumentNullException("value"); } if (value.Length > 24500) { throw new InvalidOperationException("Console title too long"); } if (!SetConsoleTitle(value)) { throw new InvalidOperationException("Console title invalid"); } } } } public static void Attach() { if (IsAttached) { return; } Initialize(); if (OriginalStdoutHandle == IntPtr.Zero) { OriginalStdoutHandle = GetStdHandle(-11); } if (GetConsoleWindow() == IntPtr.Zero) { IntPtr hWnd = getForeground(); if (!AllocConsole() && Marshal.GetLastWin32Error() != 5) { throw new Win32Exception("AllocConsole() failed"); } setForeground(hWnd); } ConsoleOutHandle = CreateFile("CONOUT$", 3221225472u, 2, IntPtr.Zero, 3, 0, IntPtr.Zero); Kon.conOut = ConsoleOutHandle; if (!SetStdHandle(-11, ConsoleOutHandle)) { throw new Win32Exception("SetStdHandle() failed"); } if (OriginalStdoutHandle != IntPtr.Zero && ConsoleManager.ConfigConsoleOutRedirectType.Value == ConsoleManager.ConsoleOutRedirectType.ConsoleOut) { CloseHandle(OriginalStdoutHandle); } IsAttached = true; } public static void PreventClose() { if (IsAttached) { Initialize(); IntPtr consoleWindow = GetConsoleWindow(); IntPtr intPtr = getSystemMenu(consoleWindow, bRevert: false); if (intPtr != IntPtr.Zero) { deleteMenu(intPtr, 61536u, 0u); } } } public static void Detach() { if (IsAttached) { if (!CloseHandle(ConsoleOutHandle)) { throw new Win32Exception("CloseHandle() failed"); } ConsoleOutHandle = IntPtr.Zero; if (!FreeConsole()) { throw new Win32Exception("FreeConsole() failed"); } if (!SetStdHandle(-11, OriginalStdoutHandle)) { throw new Win32Exception("SetStdHandle() failed"); } IsAttached = false; } } private static void Initialize() { if (!methodsInited) { methodsInited = true; IntPtr hModule = LoadLibraryEx("user32.dll", IntPtr.Zero, 2048u); setForeground = DynDll.AsDelegate<SetForegroundWindowDelegate>(GetProcAddress(hModule, "SetForegroundWindow")); getForeground = DynDll.AsDelegate<GetForegroundWindowDelegate>(GetProcAddress(hModule, "GetForegroundWindow")); getSystemMenu = DynDll.AsDelegate<GetSystemMenuDelegate>(GetProcAddress(hModule, "GetSystemMenu")); deleteMenu = DynDll.AsDelegate<DeleteMenuDelegate>(GetProcAddress(hModule, "DeleteMenu")); } } [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr GetProcAddress(IntPtr hModule, string procName); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool AllocConsole(); [DllImport("kernel32.dll")] private static extern IntPtr GetConsoleWindow(); [DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)] private static extern bool CloseHandle(IntPtr handle); [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern IntPtr CreateFile(string fileName, uint desiredAccess, int shareMode, IntPtr securityAttributes, int creationDisposition, int flagsAndAttributes, IntPtr templateFile); [DllImport("kernel32.dll")] private static extern bool FreeConsole(); [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr GetStdHandle(int nStdHandle); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool SetStdHandle(int nStdHandle, IntPtr hConsoleOutput); [DllImport("kernel32.dll", BestFitMapping = true, CharSet = CharSet.Auto, SetLastError = true)] private static extern bool SetConsoleTitle(string title); [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr LoadLibraryEx(string lpLibFileName, IntPtr hFile, uint dwFlags); } } namespace BepInEx { public static class ConsoleManager { public enum ConsoleOutRedirectType { [Description("Auto")] Auto, [Description("Console Out")] ConsoleOut, [Description("Standard Out")] StandardOut } private const uint SHIFT_JIS_CP = 932u; private const string ENABLE_CONSOLE_ARG = "--enable-console"; public static readonly ConfigEntry<bool> ConfigConsoleEnabled; public static readonly ConfigEntry<bool> ConfigPreventClose; public static readonly ConfigEntry<bool> ConfigConsoleShiftJis; public static readonly ConfigEntry<ConsoleOutRedirectType> ConfigConsoleOutRedirectType; private static readonly bool? EnableConsoleArgOverride; public static bool ConsoleEnabled => EnableConsoleArgOverride ?? ConfigConsoleEnabled.Value; internal static IConsoleDriver Driver { get; set; } public static bool ConsoleActive => Driver?.ConsoleActive ?? false; public static TextWriter StandardOutStream => Driver?.StandardOut; public static TextWriter ConsoleStream => Driver?.ConsoleOut; static ConsoleManager() { ConfigConsoleEnabled = ConfigFile.CoreConfig.Bind("Logging.Console", "Enabled", defaultValue: true, "Enables showing a console for log output."); ConfigPreventClose = ConfigFile.CoreConfig.Bind("Logging.Console", "PreventClose", defaultValue: false, "If enabled, will prevent closing the console (either by deleting the close button or in other platform-specific way)."); ConfigConsoleShiftJis = ConfigFile.CoreConfig.Bind("Logging.Console", "ShiftJisEncoding", defaultValue: false, "If true, console is set to the Shift-JIS encoding, otherwise UTF-8 encoding."); ConfigConsoleOutRedirectType = ConfigFile.CoreConfig.Bind("Logging.Console", "StandardOutType", ConsoleOutRedirectType.Auto, new StringBuilder().AppendLine("Hints console manager on what handle to assign as StandardOut. Possible values:").AppendLine("Auto - lets BepInEx decide how to redirect console output").AppendLine("ConsoleOut - prefer redirecting to console output; if possible, closes original standard output") .AppendLine("StandardOut - prefer redirecting to standard output; if possible, closes console out") .ToString()); try { string[] commandLineArgs = Environment.GetCommandLineArgs(); for (int i = 0; i < commandLineArgs.Length; i++) { if (commandLineArgs[i] == "--enable-console" && i + 1 < commandLineArgs.Length && bool.TryParse(commandLineArgs[i + 1], out var result)) { EnableConsoleArgOverride = result; } } } catch (Exception) { } } public static void Initialize(bool alreadyActive, bool useManagedEncoder) { //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) if (PlatformHelper.Is((Platform)8)) { Driver = new LinuxConsoleDriver(); } else { if (!PlatformHelper.Is((Platform)37)) { throw new PlatformNotSupportedException("Was unable to determine console driver for platform " + ((object)PlatformHelper.Current/*cast due to .constrained prefix*/).ToString()); } Driver = new WindowsConsoleDriver(); } Driver.Initialize(alreadyActive, useManagedEncoder); } private static void DriverCheck() { if (Driver == null) { throw new InvalidOperationException("Driver has not been initialized"); } } public static void CreateConsole() { if (!ConsoleActive) { DriverCheck(); uint codepage = (ConfigConsoleShiftJis.Value ? 932u : ((uint)Encoding.UTF8.CodePage)); Driver.CreateConsole(codepage); if (ConfigPreventClose.Value) { Driver.PreventClose(); } } } public static void DetachConsole() { if (ConsoleActive) { DriverCheck(); Driver.DetachConsole(); } } public static void SetConsoleTitle(string title) { DriverCheck(); Driver.SetConsoleTitle(title); } public static void SetConsoleColor(ConsoleColor color) { DriverCheck(); Driver.SetConsoleColor(color); } } internal interface IConsoleDriver { TextWriter StandardOut { get; } TextWriter ConsoleOut { get; } bool ConsoleActive { get; } bool ConsoleIsExternal { get; } void PreventClose(); void Initialize(bool alreadyActive, bool useManagedEncoder); void CreateConsole(uint codepage); void DetachConsole(); void SetConsoleColor(ConsoleColor color); void SetConsoleTitle(string title); } internal class WindowsConsoleDriver : IConsoleDriver { private static readonly ConstructorInfo FileStreamCtor = new ConstructorInfo[2] { AccessTools.Constructor(typeof(FileStream), new Type[2] { typeof(SafeFileHandle), typeof(FileAccess) }, false), AccessTools.Constructor(typeof(FileStream), new Type[2] { typeof(IntPtr), typeof(FileAccess) }, false) }.FirstOrDefault((ConstructorInfo m) => (object)m != null); private readonly Func<int> getWindowHeight; private readonly Func<int> getWindowWidth; private bool useManagedEncoder; private int ConsoleWidth { get { try { return getWindowWidth?.Invoke() ?? 0; } catch (IOException) { return 0; } } } private int ConsoleHeight { get { try { return getWindowHeight?.Invoke() ?? 0; } catch (IOException) { return 0; } } } public TextWriter StandardOut { get; private set; } public TextWriter ConsoleOut { get; private set; } public bool ConsoleActive { get; private set; } public bool ConsoleIsExternal => true; public void Initialize(bool alreadyActive, bool useManagedEncoder) { ConsoleActive = alreadyActive; this.useManagedEncoder = useManagedEncoder; if (ConsoleActive) { ConsoleOut = Console.Out; StandardOut = new StreamWriter(Console.OpenStandardOutput()); } else { StandardOut = Console.Out; } } public void CreateConsole(uint codepage) { ConsoleWindow.Attach(); if (!useManagedEncoder) { ConsoleEncoding.ConsoleCodePage = codepage; } IntPtr outHandle = GetOutHandle(); if (outHandle == IntPtr.Zero) { StandardOut = TextWriter.Null; ConsoleOut = TextWriter.Null; return; } Stream stream = OpenFileStream(outHandle); StandardOut = new StreamWriter(stream, Utility.UTF8NoBom) { AutoFlush = true }; Stream stream2 = OpenFileStream(ConsoleWindow.ConsoleOutHandle); ConsoleOut = new StreamWriter(stream2, useManagedEncoder ? Utility.UTF8NoBom : ConsoleEncoding.OutputEncoding) { AutoFlush = true }; ConsoleActive = true; } public void PreventClose() { ConsoleWindow.PreventClose(); } public void DetachConsole() { ConsoleWindow.Detach(); ConsoleOut.Close(); ConsoleOut = null; ConsoleActive = false; } public void SetConsoleColor(ConsoleColor color) { SafeConsole.ForegroundColor = color; Kon.ForegroundColor = color; } public void SetConsoleTitle(string title) { ConsoleWindow.Title = title; } private static Stream OpenFileStream(IntPtr handle) { if (ReflectionHelper.IsCore) { return (Stream)AccessTools.Constructor(Type.GetType("System.ConsolePal+WindowsConsoleStream, System.Console", throwOnError: true), new Type[3] { typeof(IntPtr), typeof(FileAccess), typeof(bool) }, false).Invoke(new object[3] { handle, FileAccess.Write, true }); } SafeFileHandle safeFileHandle = new SafeFileHandle(handle, ownsHandle: false); object[] args = AccessTools.ActualParameters((MethodBase)FileStreamCtor, new object[3] { safeFileHandle, safeFileHandle.DangerousGetHandle(), FileAccess.Write }); return (FileStream)Activator.CreateInstance(typeof(FileStream), args); } private IntPtr GetOutHandle() { switch (ConsoleManager.ConfigConsoleOutRedirectType.Value) { case ConsoleManager.ConsoleOutRedirectType.ConsoleOut: return ConsoleWindow.ConsoleOutHandle; case ConsoleManager.ConsoleOutRedirectType.StandardOut: return ConsoleWindow.OriginalStdoutHandle; default: if (!(ConsoleWindow.OriginalStdoutHandle != IntPtr.Zero)) { return ConsoleWindow.ConsoleOutHandle; } return ConsoleWindow.OriginalStdoutHandle; } } public WindowsConsoleDriver() { MethodInfo methodInfo = AccessTools.PropertyGetter(typeof(Console), "WindowHeight"); getWindowHeight = (((object)methodInfo != null) ? Extensions.CreateDelegate<Func<int>>((MethodBase)methodInfo) : null); MethodInfo methodInfo2 = AccessTools.PropertyGetter(typeof(Console), "WindowWidth"); getWindowWidth = (((object)methodInfo2 != null) ? Extensions.CreateDelegate<Func<int>>((MethodBase)methodInfo2) : null); base..ctor(); } } [AttributeUsage(AttributeTargets.Class)] public class BepInPlugin : Attribute { public string GUID { get; protected set; } public string Name { get; protected set; } public Version Version { get; protected set; } public BepInPlugin(string GUID, string Name, string Version) { this.GUID = GUID; this.Name = Name; this.Version = TryParseLongVersion(Version); } private static Version TryParseLongVersion(string version) { //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Expected O, but got Unknown Version result = default(Version); if (Version.TryParse(version, ref result)) { return result; } try { Version version2 = new Version(version); return new Version(version2.Major, version2.Minor, (version2.Build != -1) ? version2.Build : 0, (string)null, (string)null); } catch { } return null; } internal static BepInPlugin FromCecilType(TypeDefinition td) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0032: 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_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) CustomAttribute val = MetadataHelper.GetCustomAttributes<BepInPlugin>(td, inherit: false).FirstOrDefault(); if (val == null) { return null; } CustomAttributeArgument val2 = val.ConstructorArguments[0]; string gUID = (string)((CustomAttributeArgument)(ref val2)).Value; val2 = val.ConstructorArguments[1]; string name = (string)((CustomAttributeArgument)(ref val2)).Value; val2 = val.ConstructorArguments[2]; return new BepInPlugin(gUID, name, (string)((CustomAttributeArgument)(ref val2)).Value); } } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class BepInDependency : Attribute, ICacheable { [Flags] public enum DependencyFlags { HardDependency = 1, SoftDependency = 2 } public string DependencyGUID { get; protected set; } public DependencyFlags Flags { get; protected set; } public Range VersionRange { get; protected set; } public BepInDependency(string DependencyGUID, DependencyFlags Flags = DependencyFlags.HardDependency) { this.DependencyGUID = DependencyGUID; this.Flags = Flags; VersionRange = null; } public BepInDependency(string guid, string version) : this(guid) { VersionRange = Range.Parse(version, false); } void ICacheable.Save(BinaryWriter bw) { bw.Write(DependencyGUID); bw.Write((int)Flags); bw.Write(((object)VersionRange)?.ToString() ?? string.Empty); } void ICacheable.Load(BinaryReader br) { DependencyGUID = br.ReadString(); Flags = (DependencyFlags)br.ReadInt32(); string text = br.ReadString(); VersionRange = ((text == string.Empty) ? null : Range.Parse(text, false)); } internal static IEnumerable<BepInDependency> FromCecilType(TypeDefinition td) { return MetadataHelper.GetCustomAttributes<BepInDependency>(td, inherit: true).Select(delegate(CustomAttribute customAttribute) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //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) CustomAttributeArgument val = customAttribute.ConstructorArguments[0]; string text = (string)((CustomAttributeArgument)(ref val)).Value; val = customAttribute.ConstructorArguments[1]; object value = ((CustomAttributeArgument)(ref val)).Value; return (value is string version) ? new BepInDependency(text, version) : new BepInDependency(text, (DependencyFlags)value); }).ToList(); } } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class BepInIncompatibility : Attribute, ICacheable { public string IncompatibilityGUID { get; protected set; } public BepInIncompatibility(string IncompatibilityGUID) { this.IncompatibilityGUID = IncompatibilityGUID; } void ICacheable.Save(BinaryWriter bw) { bw.Write(IncompatibilityGUID); } void ICacheable.Load(BinaryReader br) { IncompatibilityGUID = br.ReadString(); } internal static IEnumerable<BepInIncompatibility> FromCecilType(TypeDefinition td) { return MetadataHelper.GetCustomAttributes<BepInIncompatibility>(td, inherit: true).Select(delegate(CustomAttribute customAttribute) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) CustomAttributeArgument val = customAttribute.ConstructorArguments[0]; return new BepInIncompatibility((string)((CustomAttributeArgument)(ref val)).Value); }).ToList(); } } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class BepInProcess : Attribute { public string ProcessName { get; protected set; } public BepInProcess(string ProcessName) { this.ProcessName = ProcessName; } internal static List<BepInProcess> FromCecilType(TypeDefinition td) { return MetadataHelper.GetCustomAttributes<BepInProcess>(td, inherit: true).Select(delegate(CustomAttribute customAttribute) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) CustomAttributeArgument val = customAttribute.ConstructorArguments[0]; return new BepInProcess((string)((CustomAttributeArgument)(ref val)).Value); }).ToList(); } } public static class MetadataHelper { internal static IEnumerable<CustomAttribute> GetCustomAttributes<T>(TypeDefinition td, bool inherit) where T : Attribute { List<CustomAttribute> list = new List<CustomAttribute>(); Type type = typeof(T); TypeDefinition val = td; do { list.AddRange(((IEnumerable<CustomAttribute>)val.CustomAttributes).Where((CustomAttribute ca) => ((MemberReference)ca.AttributeType).FullName == type.FullName)); TypeReference baseType = val.BaseType; val = ((baseType != null) ? baseType.Resolve() : null); } while (inherit && ((val != null) ? ((MemberReference)val).FullName : null) != "System.Object"); return list; } public static BepInPlugin GetMetadata(Type pluginType) { object[] customAttributes = pluginType.GetCustomAttributes(typeof(BepInPlugin), inherit: false); if (customAttributes.Length == 0) { return null; } return (BepInPlugin)customAttributes[0]; } public static BepInPlugin GetMetadata(object plugin) { return GetMetadata(plugin.GetType()); } public static T[] GetAttributes<T>(Type pluginType) where T : Attribute { return (T[])pluginType.GetCustomAttributes(typeof(T), inherit: true); } public static T[] GetAttributes<T>(Assembly assembly) where T : Attribute { return (T[])assembly.GetCustomAttributes(typeof(T), inherit: true); } public static IEnumerable<T> GetAttributes<T>(object plugin) where T : Attribute { return GetAttributes<T>(plugin.GetType()); } public static T[] GetAttributes<T>(MemberInfo member) where T : Attribute { return (T[])member.GetCustomAttributes(typeof(T), inherit: true); } public static IEnumerable<BepInDependency> GetDependencies(Type plugin) { return plugin.GetCustomAttributes(typeof(BepInDependency), inherit: true).Cast<BepInDependency>(); } } public class PluginInfo : ICacheable { public BepInPlugin Metadata { get; internal set; } public IEnumerable<BepInProcess> Processes { get; internal set; } public IEnumerable<BepInDependency> Dependencies { get; internal set; } public IEnumerable<BepInIncompatibility> Incompatibilities { get; internal set; } public string Location { get; internal set; } public object Instance { get; internal set; } public string TypeName { get; internal set; } internal Version TargettedBepInExVersion { get; set; } void ICacheable.Save(BinaryWriter bw) { bw.Write(TypeName); bw.Write(Location); bw.Write(Metadata.GUID); bw.Write(Metadata.Name); bw.Write(((object)Metadata.Version).ToString()); List<BepInProcess> list = Processes.ToList(); bw.Write(list.Count); foreach (BepInProcess item in list) { bw.Write(item.ProcessName); } List<BepInDependency> list2 = Dependencies.ToList(); bw.Write(list2.Count); foreach (BepInDependency item2 in list2) { ((ICacheable)item2).Save(bw); } List<BepInIncompatibility> list3 = Incompatibilities.ToList(); bw.Write(list3.Count); foreach (BepInIncompatibility item3 in list3) { ((ICacheable)item3).Save(bw); } bw.Write(TargettedBepInExVersion.ToString(4)); } void ICacheable.Load(BinaryReader br) { TypeName = br.ReadString(); Location = br.ReadString(); Metadata = new BepInPlugin(br.ReadString(), br.ReadString(), br.ReadString()); int num = br.ReadInt32(); List<BepInProcess> list = new List<BepInProcess>(num); for (int i = 0; i < num; i++) { list.Add(new BepInProcess(br.ReadString())); } Processes = list; int num2 = br.ReadInt32(); List<BepInDependency> list2 = new List<BepInDependency>(num2); for (int j = 0; j < num2; j++) { BepInDependency bepInDependency = new BepInDependency(""); ((ICacheable)bepInDependency).Load(br); list2.Add(bepInDependency); } Dependencies = list2; int num3 = br.ReadInt32(); List<BepInIncompatibility> list3 = new List<BepInIncompatibility>(num3); for (int k = 0; k < num3; k++) { BepInIncompatibility bepInIncompatibility = new BepInIncompatibility(""); ((ICacheable)bepInIncompatibility).Load(br); list3.Add(bepInIncompatibility); } Incompatibilities = list3; TargettedBepInExVersion = new Version(br.ReadString()); } public override string ToString() { return $"{Metadata?.Name} {Metadata?.Version}"; } } public static class Paths { public static Version BepInExVersion { get; } = Version.Parse(MetadataHelper.GetAttributes<AssemblyInformationalVersionAttribute>(typeof(Paths).Assembly)[0].InformationalVersion, false); public static string ManagedPath { get; private set; } public static string GameDataPath { get; private set; } public static string BepInExAssemblyDirectory { get; private set; } public static string BepInExAssemblyPath { get; private set; } public static string BepInExRootPath { get; private set; } public static string ExecutablePath { get; private set; } public static string GameRootPath { get; private set; } public static string ConfigPath { get; private set; } public static string BepInExConfigPath { get; private set; } public static string CachePath { get; private set; } public static string PatcherPluginPath { get; private set; } public static string PluginPath { get; private set; } public static string ProcessName { get; private set; } public static string[] DllSearchPaths { get; private set; } public static void SetExecutablePath(string executablePath, string bepinRootPath = null, string managedPath = null, bool gameDataRelativeToManaged = false, string[] dllSearchPath = null) { ExecutablePath = executablePath; ProcessName = Path.GetFileNameWithoutExtension(executablePath); GameRootPath = (PlatformHelper.Is((Platform)73) ? Utility.ParentDirectory(executablePath, 4) : Path.GetDirectoryName(executablePath)); GameDataPath = ((managedPath != null && gameDataRelativeToManaged) ? Path.GetDirectoryName(managedPath) : Path.Combine(GameRootPath, ProcessName + "_Data")); ManagedPath = managedPath ?? Path.Combine(GameDataPath, "Managed"); BepInExRootPath = bepinRootPath ?? Path.Combine(GameRootPath, "BepInEx"); ConfigPath = Path.Combine(BepInExRootPath, "config"); BepInExConfigPath = Path.Combine(ConfigPath, "BepInEx.cfg"); PluginPath = Path.Combine(BepInExRootPath, "plugins"); PatcherPluginPath = Path.Combine(BepInExRootPath, "patchers"); BepInExAssemblyDirectory = Path.Combine(BepInExRootPath, "core"); BepInExAssemblyPath = Path.Combine(BepInExAssemblyDirectory, Assembly.GetExecutingAssembly().GetName().Name + ".dll"); CachePath = Path.Combine(BepInExRootPath, "cache"); DllSearchPaths = (dllSearchPath ?? new string[0]).Concat(new string[1] { ManagedPath }).Distinct().ToArray(); } internal static void SetPluginPath(string pluginPath) { PluginPath = Utility.CombinePaths(BepInExRootPath, pluginPath); } } public static class Utility { private const string TRUSTED_PLATFORM_ASSEMBLIES = "TRUSTED_PLATFORM_ASSEMBLIES"; private static bool? sreEnabled; public static bool CLRSupportsDynamicAssemblies => CheckSRE(); public static Encoding UTF8NoBom { get; } = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); private static bool CheckSRE() { try { if (sreEnabled.HasValue) { return sreEnabled.Value; } new CustomAttributeBuilder(null, new object[0]); } catch (PlatformNotSupportedException) { sreEnabled = false; return sreEnabled.Value; } catch (ArgumentNullException) { } sreEnabled = true; return sreEnabled.Value; } public static bool TryDo(Action action, out Exception exception) { exception = null; try { action(); return true; } catch (Exception ex) { exception = ex; return false; } } public static string CombinePaths(params string[] parts) { return parts.Aggregate(Path.Combine); } public static string ParentDirectory(string path, int levels = 1) { for (int i = 0; i < levels; i++) { path = Path.GetDirectoryName(path); } return path; } public static bool SafeParseBool(string input, bool defaultValue = false) { if (!bool.TryParse(input, out var result)) { return defaultValue; } return result; } public static string ConvertToWWWFormat(string path) { return "file://" + path.Replace('\\', '/'); } public static bool IsNullOrWhiteSpace(this string self) { return self?.All(char.IsWhiteSpace) ?? true; } public static IEnumerable<TNode> TopologicalSort<TNode>(IEnumerable<TNode> nodes, Func<TNode, IEnumerable<TNode>> dependencySelector) { List<TNode> sorted_list = new List<TNode>(); HashSet<TNode> visited = new HashSet<TNode>(); HashSet<TNode> sorted = new HashSet<TNode>(); foreach (TNode node in nodes) { Stack<TNode> stack = new Stack<TNode>(); if (!Visit(node, stack)) { throw new Exception("Cyclic Dependency:\r\n" + stack.Select((TNode x) => $" - {x}").Aggregate((string a, string b) => a + "\r\n" + b)); } } return sorted_list; bool Visit(TNode node, Stack<TNode> stack2) { if (visited.Contains(node)) { if (!sorted.Contains(node)) { return false; } } else { visited.Add(node); stack2.Push(node); if (dependencySelector(node).Any((TNode dep) => !Visit(dep, stack2))) { return false; } sorted.Add(node); sorted_list.Add(node); stack2.Pop(); } return true; } } public static bool TryResolveDllAssembly<T>(AssemblyName assemblyName, string directory, Func<string, T> loader, out T assembly) where T : class { assembly = null; List<string> list = new List<string> { directory }; if (!Directory.Exists(directory)) { return false; } list.AddRange(Directory.GetDirectories(directory, "*", SearchOption.AllDirectories)); foreach (string item in list) { string[] array = new string[2] { assemblyName.Name + ".dll", assemblyName.Name + ".exe" }; foreach (string path in array) { string text = Path.Combine(item, path); if (File.Exists(text)) { try { assembly = loader(text); } catch (Exception) { continue; } return true; } } } return false; } public static bool IsSubtypeOf(this TypeDefinition self, Type td) { if (((MemberReference)self).FullName == td.FullName) { return true; } if (((MemberReference)self).FullName != "System.Object") { TypeReference baseType = self.BaseType; return ((baseType == null) ? ((bool?)null) : baseType.Resolve()?.IsSubtypeOf(td)) == true; } return false; } public static bool TryResolveDllAssembly(AssemblyName assemblyName, string directory, out Assembly assembly) { return TryResolveDllAssembly(assemblyName, directory, (Func<string, Assembly>)Assembly.LoadFrom, out assembly); } public static bool TryResolveDllAssembly(AssemblyName assemblyName, string directory, ReaderParameters readerParameters, out AssemblyDefinition assembly) { return TryResolveDllAssembly(assemblyName, directory, (Func<string, AssemblyDefinition>)((string s) => AssemblyDefinition.ReadAssembly(s, readerParameters)), out assembly); } public static bool TryOpenFileStream(string path, FileMode mode, out FileStream fileStream, FileAccess access = FileAccess.ReadWrite, FileShare share = FileShare.Read) { try { fileStream = new FileStream(path, mode, access, share); return true; } catch (IOException) { fileStream = null; return false; } } public static IEnumerable<MethodDefinition> EnumerateAllMethods(this TypeDefinition type) { TypeDefinition currentType = type; while (currentType != null) { Enumerator<MethodDefinition> enumerator = currentType.Methods.GetEnumerator(); try { while (enumerator.MoveNext()) { yield return enumerator.Current; } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } TypeReference baseType = currentType.BaseType; currentType = ((baseType != null) ? baseType.Resolve() : null); } } public static string HashStream(Stream stream) { using MD5 mD = MD5.Create(); byte[] array = new byte[4096]; int inputCount; while ((inputCount = stream.Read(array, 0, array.Length)) > 0) { mD.TransformBlock(array, 0, inputCount, array, 0); } mD.TransformFinalBlock(new byte[0], 0, 0); return ByteArrayToString(mD.Hash); } public static string HashStrings(params string[] strings) { using MD5 mD = MD5.Create(); foreach (string text in strings) { mD.TransformBlock(Encoding.UTF8.GetBytes(text), 0, text.Length, null, 0); } mD.TransformFinalBlock(new byte[0], 0, 0); return ByteArrayToString(mD.Hash); } public static string ByteArrayToString(byte[] data) { StringBuilder stringBuilder = new StringBuilder(data.Length * 2); foreach (byte b in data) { stringBuilder.AppendFormat("{0:x2}", b); } return stringBuilder.ToString(); } public static string GetCommandLineArgValue(string arg) { string[] commandLineArgs = Environment.GetCommandLineArgs(); for (int i = 1; i < commandLineArgs.Length; i++) { if (commandLineArgs[i] == arg && i + 1 < commandLineArgs.Length) { return commandLineArgs[i + 1]; } } return null; } public static bool TryParseAssemblyName(string fullName, out AssemblyName assemblyName) { try { assemblyName = new AssemblyName(fullName); return true; } catch (Exception) { assemblyName = null; return false; } } internal static void AddCecilPlatformAssemblies(this AppDomain appDomain, string assemblyDir) { if (Directory.Exists(assemblyDir)) { string text = appDomain.GetData("TRUSTED_PLATFORM_ASSEMBLIES") as string; char pathSeparator = Path.PathSeparator; string text2 = string.Join(pathSeparator.ToString(), Directory.GetFiles(assemblyDir, "*.dll", SearchOption.TopDirectoryOnly)); string data = ((text == null) ? text2 : $"{text}{Path.PathSeparator}{text2}"); appDomain.SetData("TRUSTED_PLATFORM_ASSEMBLIES", data); } } public static IEnumerable<string> GetUniqueFilesInDirectories(IEnumerable<string> directories, string pattern = "*") { Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase); foreach (string directory in directories) { string[] files = Directory.GetFiles(directory, pattern); foreach (string text in files) { string fileName = Path.GetFileName(text); if (!dictionary.ContainsKey(fileName)) { dictionary[fileName] = text; } } } return dictionary.Values; } } } namespace BepInEx.Logging { public class ConsoleLogListener : ILogListener, IDisposable { protected static readonly ConfigEntry<LogLevel> ConfigConsoleDisplayedLevel = ConfigFile.CoreConfig.Bind("Logging.Console", "LogLevels", LogLevel.Fatal | LogLevel.Error | LogLevel.Warning | LogLevel.Message | LogLevel.Info, "Only displays the specified log levels in the console output."); public LogLevel LogLevelFilter => ConfigConsoleDisplayedLevel.Value; public void LogEvent(object sender, LogEventArgs eventArgs) { ConsoleManager.SetConsoleColor(eventArgs.Level.GetConsoleColor()); ConsoleManager.ConsoleStream?.Write(eventArgs.ToStringLine()); ConsoleManager.SetConsoleColor(ConsoleColor.Gray); } public void Dispose() { } } public class DiskLogListener : ILogListener, IDisposable { public static HashSet<string> BlacklistedSources = new HashSet<string>(); public LogLevel DisplayedLogLevel { get; } public TextWriter LogWriter { get; protected set; } private Timer FlushTimer { get; } private bool InstantFlushing { get; } public LogLevel LogLevelFilter => DisplayedLogLevel; public DiskLogListener(string localPath, LogLevel displayedLogLevel = LogLevel.Info, bool appendLog = false, bool delayedFlushing = true, int fileLimit = 5) { DisplayedLogLevel = displayedLogLevel; int num = 1; FileStream fileStream; while (!Utility.TryOpenFileStream(Path.Combine(Paths.BepInExRootPath, localPath), appendLog ? FileMode.Append : FileMode.Create, out fileStream, FileAccess.Write)) { if (num == fileLimit) { Logger.Log(LogLevel.Error, "Couldn't open a log file for writing. Skipping log file creation"); return; } LogLevel logLevel = LogLevel.Warning; bool isEnabled; BepInExLogInterpolatedStringHandler bepInExLogInterpolatedStringHandler = new BepInExLogInterpolatedStringHandler(56, 1, logLevel, out isEnabled); if (isEnabled) { bepInExLogInterpolatedStringHandler.AppendLiteral("Couldn't open log file '"); bepInExLogInterpolatedStringHandler.AppendFormatted(localPath); bepInExLogInterpolatedStringHandler.AppendLiteral("' for writing, trying another..."); } Logger.Log(logLevel, bepInExLogInterpolatedStringHandler); localPath = $"LogOutput.{num++}.log"; } LogWriter = TextWriter.Synchronized(new StreamWriter(fileStream, Utility.UTF8NoBom)); if (delayedFlushing) { FlushTimer = new Timer(delegate { LogWriter?.Flush(); }, null, 2000, 2000); } InstantFlushing = !delayedFlushing; } public void LogEvent(object sender, LogEventArgs eventArgs) { if (LogWriter != null && !BlacklistedSources.Contains(eventArgs.Source.SourceName)) { LogWriter.WriteLine(eventArgs.ToString()); if (InstantFlushing) { LogWriter.Flush(); } } } public void Dispose() { FlushTimer?.Dispose(); try { LogWriter?.Flush(); LogWriter?.Dispose(); } catch (ObjectDisposedException) { } } ~DiskLogListener() { Dispose(); } } public class HarmonyLogSource : ILogSource, IDisposable { private static readonly ConfigEntry<LogChannel> LogChannels = ConfigFile.CoreConfig.Bind<LogChannel>("Harmony.Logger", "LogChannels", (LogChannel)24, "Specifies which Harmony log channels to listen to.\nNOTE: IL channel dumps the whole patch methods, use only when needed!"); private static readonly Dictionary<LogChannel, LogLevel> LevelMap = new Dictionary<LogChannel, LogLevel> { [(LogChannel)2] = LogLevel.Info, [(LogChannel)8] = LogLevel.Warning, [(LogChannel)16] = LogLevel.Error, [(LogChannel)4] = LogLevel.Debug }; public string SourceName { get; } = "HarmonyX"; public event EventHandler<LogEventArgs> LogEvent; public HarmonyLogSource() { //IL_0016: Unknown result type (might be due to invalid IL or missing references) Logger.ChannelFilter = LogChannels.Value; Logger.MessageReceived += HandleHarmonyMessage; } public void Dispose() { Logger.MessageReceived -= HandleHarmonyMessage; } private void HandleHarmonyMessage(object sender, LogEventArgs e) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) if (LevelMap.TryGetValue(e.LogChannel, out var value)) { this.LogEvent?.Invoke(this, new LogEventArgs(e.Message, value, this)); } } } public interface ILogListener : IDisposable { LogLevel LogLevelFilter { get; } void LogEvent(object sender, LogEventArgs eventArgs); } public interface ILogSource : IDisposable { string SourceName { get; } event EventHandler<LogEventArgs> LogEvent; } public class LogEventArgs : EventArgs { public object Data { get; } public LogLevel Level { get; } public ILogSource Source { get; } public LogEventArgs(object data, LogLevel level, ILogSource source) { Data = data; Level = level; Source = source; } public override string ToString() { return $"[{Level,-7}:{Source.SourceName,10}] {Data}"; } public string ToStringLine() { return $"[{Level,-7}:{Source.SourceName,10}] {Data}{Environment.NewLine}"; } } public static class Logger { private class LogListenerCollection : List<ILogListener>, ICollection<ILogListener>, IEnumerable<ILogListener>, IEnumerable { public LogLevel activeLogLevels; void ICollection<ILogListener>.Add(ILogListener item) { if (item == null) { throw new ArgumentNullException("item"); } activeLogLevels |= item.LogLevelFilter; Add(item); } void ICollection<ILogListener>.Clear() { activeLogLevels = LogLevel.None; Clear(); } bool ICollection<ILogListener>.Remove(ILogListener item) { if (item == null || !Remove(item)) { return false; } activeLogLevels = LogLevel.None; using (Enumerator enumerator = GetEnumerator()) { while (enumerator.MoveNext()) { ILogListener current = enumerator.Current; activeLogLevels |= current.LogLevelFilter; } } return true; } } private class LogSourceCollection : List<ILogSource>, ICollection<ILogSource>, IEnumerable<ILogSource>, IEnumerable { void ICollection<ILogSource>.Add(ILogSource item) { if (item == null) { throw new ArgumentNullException("item", "Log sources cannot be null when added to the source list."); } item.LogEvent += InternalLogEvent; Add(item); } void ICollection<ILogSource>.Clear() { using (Enumerator enumerator = GetEnumerator()) { while (enumerator.MoveNext()) { enumerator.Current.LogEvent -= InternalLogEvent; } } Clear(); } bool ICollection<ILogSource>.Remove(ILogSource item) { if (item == null || !Remove(item)) { return false; } item.LogEvent -= InternalLogEvent; return true; } } private static readonly ManualLogSource InternalLogSource; private static readonly LogListenerCollection listeners; public static LogLevel ListenedLogLevels => listeners.activeLogLevels; public static ICollection<ILogListener> Listeners => listeners; public static ICollection<ILogSource> Sources { get; } static Logger() { Sources = new LogSourceCollection(); listeners = new LogListenerCollection(); InternalLogSource = CreateLogSource("BepInEx"); } internal static void InternalLogEvent(object sender, LogEventArgs eventArgs) { foreach (ILogListener listener in listeners) { if ((eventArgs.Level & listener.LogLevelFilter) != LogLevel.None) { listener?.LogEvent(sender, eventArgs); } } } internal static void Log(LogLevel level, object data) { InternalLogSource.Log(level, data); } internal static void Log(LogLevel level, [InterpolatedStringHandlerArgument("level")] BepInExLogInterpolatedStringHandler logHandler) { InternalLogSource.Log(level, logHandler); } public static ManualLogSource CreateLogSource(string sourceName) { ManualLogSource manualLogSource = new ManualLogSource(sourceName); Sources.Add(manualLogSource); return manualLogSource; } } [Flags] public enum LogLevel { None = 0, Fatal = 1, Error = 2, Warning = 4, Message = 8, Info = 0x10, Debug = 0x20, All = 0x3F } public static class LogLevelExtensions { public static LogLevel GetHighestLevel(this LogLevel levels) { Array values = Enum.GetValues(typeof(LogLevel)); Array.Sort(values); foreach (LogLevel item in values) { if ((levels & item) != LogLevel.None) { return item; } } return LogLevel.None; } public static ConsoleColor GetConsoleColor(this LogLevel level) { level = level.GetHighestLevel(); return level switch { LogLevel.Fatal => ConsoleColor.Red, LogLevel.Error => ConsoleColor.DarkRed, LogLevel.Warning => ConsoleColor.Yellow, LogLevel.Message => ConsoleColor.White, LogLevel.Info => ConsoleColor.DarkGray, LogLevel.Debug => ConsoleColor.DarkGray, _ => ConsoleColor.Gray, }; } } public class ManualLogSource : ILogSource, IDisposable { public string SourceName { get; } public event EventHandler<LogEventArgs> LogEvent; public ManualLogSource(string sourceName) { SourceName = sourceName; } public void Dispose() { } public void Log(LogLevel level, object data) { this.LogEvent?.Invoke(this, new LogEventArgs(data, level, this)); } public void Log(LogLevel level, [InterpolatedStringHandlerArgument("level")] BepInExLogInterpolatedStringHandler logHandler) { if (logHandler.Enabled) { this.LogEvent?.Invoke(this, new LogEventArgs(logHandler.ToString(), level, this)); } } public void LogFatal(object data) { Log(LogLevel.Fatal, data); } public void LogFatal(BepInExFatalLogInterpolatedStringHandler logHandler) { Log(LogLevel.Fatal, logHandler); } public void LogError(object data) { Log(LogLevel.Error, data); } public void LogError(BepInExErrorLogInterpolatedStringHandler logHandler) { Log(LogLevel.Error, logHandler); } public void LogWarning(object data) { Log(LogLevel.Warning, data); } public void LogWarning(BepInExWarningLogInterpolatedStringHandler logHandler) { Log(LogLevel.Warning, logHandler); } public void LogMessage(object data) { Log(LogLevel.Message, data); } public void LogMessage(BepInExMessageLogInterpolatedStringHandler logHandler) { Log(LogLevel.Message, logHandler); } public void LogInfo(object data) { Log(LogLevel.Info, data); } public void LogInfo(BepInExInfoLogInterpolatedStringHandler logHandler) { Log(LogLevel.Info, logHandler); } public void LogDebug(object data) { Log(LogLevel.Debug, data); } public void LogDebug(BepInExDebugLogInterpolatedStringHandler logHandler) { Log(LogLevel.Debug, logHandler); } } public class TraceLogSource : TraceListener { private static TraceLogSource traceListener; public static bool IsListening { get; private set; } protected ManualLogSource LogSource { get; } protected TraceLogSource() { LogSource = new ManualLogSource("Trace"); } public static ILogSource CreateSource() { if (traceListener == null) { traceListener = new TraceLogSource(); Trace.Listeners.Add(traceListener); IsListening = true; } return traceListener.LogSource; } public override void Write(string message) { LogSource.Log(LogLevel.Info, message); } public override void WriteLine(string message) { LogSource.Log(LogLevel.Info, message); } public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args) { TraceEvent(eventCache, source, eventType, id, string.Format(format, args)); } public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message) { LogSource.Log(eventType switch { TraceEventType.Critical => LogLevel.Fatal, TraceEventType.Error => LogLevel.Error, TraceEventType.Warning => LogLevel.Warning, TraceEventType.Information => LogLevel.Info, _ => LogLevel.Debug, }, (message ?? "").Trim()); } } } namespace BepInEx.Core.Logging.Interpolation { [InterpolatedStringHandler] public class BepInExLogInterpolatedStringHandler { private const int GUESSED_LENGTH_PER_HOLE = 11; private readonly StringBuilder sb; public bool Enabled { get; } public BepInExLogInterpolatedStringHandler(int literalLength, int formattedCount, LogLevel logLevel, out bool isEnabled) { Enabled = (logLevel & Logger.ListenedLogLevels) != 0; isEnabled = Enabled; sb = (Enabled ? new StringBuilder(literalLength + formattedCount * 11) : null); } public void AppendLiteral(string s) { if (Enabled) { sb.Append(s); } } public void AppendFormatted<T>(T t) { if (Enabled) { sb.Append(t); } } public void AppendFormatted<T>(T t, string format) where T : IFormattable { if (Enabled) { sb.Append(t?.ToString(format, null)); } } public void AppendFormatted(IntPtr t, string format) { if (Enabled) { sb.Append(t.ToString(format)); } } public override string ToString() { return sb?.ToString() ?? string.Empty; } } [InterpolatedStringHandler] public class BepInExFatalLogInterpolatedStringHandler : BepInExLogInterpolatedStringHandler { public BepInExFatalLogInterpolatedStringHandler(int literalLength, int formattedCount, out bool isEnabled) : base(literalLength, formattedCount, LogLevel.Fatal, out isEnabled) { } } [InterpolatedStringHandler] public class BepInExErrorLogInterpolatedStringHandler : BepInExLogInterpolatedStringHandler { public BepInExErrorLogInterpolatedStringHandler(int literalLength, int formattedCount, out bool isEnabled) : base(literalLength, formattedCount, LogLevel.Error, out isEnabled) { } } [InterpolatedStringHandler] public class BepInExWarningLogInterpolatedStringHandler : BepInExLogInterpolatedStringHandler { public BepInExWarningLogInterpolatedStringHandler(int literalLength, int formattedCount, out bool isEnabled) : base(literalLength, formattedCount, LogLevel.Warning, out isEnabled) { } } [InterpolatedStringHandler] public class BepInExMessageLogInterpolatedStringHandler : BepInExLogInterpolatedStringHandler { public BepInExMessageLogInterpolatedStringHandler(int literalLength, int formattedCount, out bool isEnabled) : base(literalLength, formattedCount, LogLevel.Message, out isEnabled) { } } [InterpolatedStringHandler] public class BepInExInfoLogInterpolatedStringHandler : BepInExLogInterpolatedStringHandler { public BepInExInfoLogInterpolatedStringHandler(int literalLength, int formattedCount, out bool isEnabled) : base(literalLength, formattedCount, LogLevel.Info, out isEnabled) { } } [InterpolatedStringHandler] public class BepInExDebugLogInterpolatedStringHandler : BepInExLogInterpolatedStringHandler { public BepInExDebugLogInterpolatedStringHandler(int literalLength, int formattedCount, out bool isEnabled) : base(literalLength, formattedCount, LogLevel.Debug, out isEnabled) { } } } namespace BepInEx.ConsoleUtil { internal class Kon { private struct CONSOLE_SCREEN_BUFFER_INFO { internal COORD dwSize; internal COORD dwCursorPosition; internal short wAttributes; internal SMALL_RECT srWindow; internal COORD dwMaximumWindowSize; } private struct COORD { internal short X; internal short Y; } private struct SMALL_RECT { internal short Left; internal short Top; internal short Right; internal short Bottom; } private static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); internal static IntPtr conOut = IntPtr.Zero; public static ConsoleColor ForegroundColor { get { return GetConsoleColor(isBackground: false); } set { SetConsoleColor(isBackground: false, value); } } public static ConsoleColor BackgroundColor { get { return GetConsoleColor(isBackground: true); } set { SetConsoleColor(isBackground: true, value); } } [DllImport("kernel32.dll", SetLastError = true)] private static extern bool GetConsoleScreenBufferInfo(IntPtr hConsoleOutput, out CONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool SetConsoleTextAttribute(IntPtr hConsoleOutput, short attributes); [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr GetStdHandle(int nStdHandle); private static short ConsoleColorToColorAttribute(short color, bool isBackground) { if ((color & -16) != 0) { throw new ArgumentException("Arg_InvalidConsoleColor"); } if (isBackground) { color <<= 4; } return color; } private static CONSOLE_SCREEN_BUFFER_INFO GetBufferInfo(bool throwOnNoConsole, out bool succeeded) { succeeded = false; if (!(conOut == INVALID_HANDLE_VALUE)) { if (!GetConsoleScreenBufferInfo(conOut, out var lpConsoleScreenBufferInfo)) { bool consoleScreenBufferInfo = GetConsoleScreenBufferInfo(GetStdHandle(-12), out lpConsoleScreenBufferInfo); if (!consoleScreenBufferInfo) { consoleScreenBufferInfo = GetConsoleScreenBufferInfo(GetStdHandle(-10), out lpConsoleScreenBufferInfo); } if (!consoleScreenBufferInfo && Marshal.GetLastWin32Error() == 6 && !throwOnNoConsole) { return default(CONSOLE_SCREEN_BUFFER_INFO); } } succeeded = true; return lpConsoleScreenBufferInfo; } if (!throwOnNoConsole) { return default(CONSOLE_SCREEN_BUFFER_INFO); } throw new Exception("IO.IO_NoConsole"); } private static void SetConsoleColor(bool isBackground, ConsoleColor c) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) ((CodeAccessPermission)new UIPermission((UIPermissionWindow)2)).Demand(); short num = ConsoleColorToColorAttribute((short)c, isBackground); bool succeeded; CONSOLE_SCREEN_BUFFER_INFO bufferInfo = GetBufferInfo(throwOnNoConsole: false, out succeeded); if (succeeded) { short wAttributes = bufferInfo.wAttributes; wAttributes &= (short)(isBackground ? (-241) : (-16)); wAttributes = (short)((ushort)wAttributes | (ushort)num); SetConsoleTextAttribute(conOut, wAttributes); } } private static ConsoleColor GetConsoleColor(bool isBackground) { bool succeeded; CONSOLE_SCREEN_BUFFER_INFO bufferInfo = GetBufferInfo(throwOnNoConsole: false, out succeeded); if (!succeeded) { if (!isBackground) { return ConsoleColor.Gray; } return ConsoleColor.Black; } return ColorAttributeToConsoleColor((short)(bufferInfo.wAttributes & 0xF0)); } private static ConsoleColor ColorAttributeToConsoleColor(short c) { if ((short)(c & 0xFF) != 0) { c >>= 4; } return (ConsoleColor)c; } public static void ResetConsoleColor() { SetConsoleColor(isBackground: true, ConsoleColor.Black); SetConsoleColor(isBackground: false, ConsoleColor.Gray); } } } namespace BepInEx.Unix { internal static class ConsoleWriter { private static Func<Stream, Encoding, bool, StreamWriter> cStreamWriterConstructor; private static Func<Stream, Encoding, bool, StreamWriter> CStreamWriterConstructor { get { if (cStreamWriterConstructor != null) { return cStreamWriterConstructor; } Type cStreamWriter = AccessTools.TypeByName("System.IO.CStreamWriter"); cStreamWriterConstructor = new int[2][] { new int[3] { 0, 1, 2 }, new int[2] { 0, 1 } }.Select(GetCtor).FirstOrDefault((Func<Stream, Encoding, bool, StreamWriter> f) => f != null); if (cStreamWriterConstructor == null) { throw new AmbiguousMatchException("Failed to find suitable constructor for CStreamWriter"); } return cStreamWriterConstructor; Func<Stream, Encoding, bool, StreamWriter> GetCtor(int[] perm) { Type[] parameters = new Type[3] { typeof(Stream), typeof(Encoding), typeof(bool) }; ConstructorInfo ctor = AccessTools.Constructor(cStreamWriter, perm.Select((int i) => parameters[i]).ToArray(), false); if ((object)ctor != null) { return delegate(Stream stream, Encoding encoding, bool l) { object[] vals = new object[3] { stream, encoding, l }; return (StreamWriter)ctor.Invoke(perm.Select((int i) => vals[i]).ToArray()); }; } return null; } } } public static TextWriter CreateConsoleStreamWriter(Stream stream, Encoding encoding, bool leaveOpen) { StreamWriter streamWriter = CStreamWriterConstructor(stream, encoding, leaveOpen); streamWriter.AutoFlush = true; return streamWriter; } } internal class LinuxConsoleDriver : IConsoleDriver { private static readonly ConfigEntry<bool> ForceCustomTtyDriverConfig; public static bool UseMonoTtyDriver { get; } public bool StdoutRedirected { get; private set; } public TtyInfo TtyInfo { get; private set; } public TextWriter StandardOut { get; private set; } public TextWriter ConsoleOut { get; private set; } public bool ConsoleActive { get; private set; } public bool ConsoleIsExternal => false; static LinuxConsoleDriver() { ForceCustomTtyDriverConfig = ConfigFile.CoreConfig.Bind("Logging.Console", "ForceBepInExTTYDriver", defaultValue: false, "If enabled, forces to use custom BepInEx TTY driver for handling terminal output on unix."); UseMonoTtyDriver = false; if (!ForceCustomTtyDriverConfig.Value && (object)typeof(Console).Assembly.GetType("System.ConsoleDriver") != null) { UseMonoTtyDriver = (object)typeof(Console).Assembly.GetType("System.ParameterizedStrings") != null; } } public void PreventClose() { } public void Initialize(bool alreadyActive, bool useManagedEncoder) { ConsoleActive = true; StdoutRedirected = UnixStreamHelper.isatty(1) != 1; Stream stream = UnixStreamHelper.CreateDuplicateStream(1); if (UseMonoTtyDriver && !StdoutRedirected) { TextWriter textWriter = ConsoleWriter.CreateConsoleStreamWriter(stream, Console.Out.Encoding, leaveOpen: true); StandardOut = TextWriter.Synchronized(textWriter); object value = AccessTools.Field(AccessTools.TypeByName("System.ConsoleDriver"), "driver").GetValue(null); AccessTools.Field(AccessTools.TypeByName("System.TermInfoDriver"), "stdout").SetValue(value, textWriter); } else { StreamWriter streamWriter = new StreamWriter(stream, Console.Out.Encoding); streamWriter.AutoFlush = true; StandardOut = TextWriter.Synchronized(streamWriter); TtyInfo = TtyHandler.GetTtyInfo(); } ConsoleOut = StandardOut; } public void CreateConsole(uint codepage) { Logger.Log(LogLevel.Warning, "An external console currently cannot be spawned on a Unix platform."); } public void DetachConsole() { throw new PlatformNotSupportedException("Cannot detach console on a Unix platform"); } public void SetConsoleColor(ConsoleColor color) { if (!StdoutRedirected) { if (UseMonoTtyDriver) { SafeConsole.ForegroundColor = color; } else { ConsoleOut.Write(TtyInfo.GetAnsiCode(color)); } } } public void SetConsoleTitle(string title) { if (!StdoutRedirected) { if (UseMonoTtyDriver && SafeConsole.TitleExists) { SafeConsole.Title = title; } else { ConsoleOut.Write("\u001b]2;" + title.Replace("\\", "\\\\") + "\a"); } } } } internal class TtyInfo { public string TerminalType { get; set; } = "default"; public int MaxColors { get; set; } public string[] ForegroundColorStrings { get; set; } public static TtyInfo Default { get; } = new TtyInfo { MaxColors = 0 }; public string GetAnsiCode(ConsoleColor color) { if (MaxColors <= 0 || ForegroundColorStrings == null) { return string.Empty; } int num = (int)color % MaxColors; return ForegroundColorStrings[num]; } } internal static class TtyHandler { private static readonly string[] ncursesLocations = new string[4] { "/usr/share/terminfo", "/etc/terminfo", "/usr/lib/terminfo", "/lib/terminfo" }; private static string TryTermInfoDir(string dir, string term) { string text = $"{dir}/{(int)term[0]:x}/{term}"; if (File.Exists(text)) { return text; } text = Utility.CombinePaths(dir, term.Substring(0, 1), term); if (File.Exists(text)) { return text; } return null; } private static string FindTermInfoPath(string term) { if (string.IsNullOrEmpty(term)) { return null; } string environmentVariable = Environment.GetEnvironmentVariable("TERMINFO"); if (environmentVariable != null && Directory.Exists(environmentVariable)) { string text = TryTermInfoDir(environmentVariable, term); if (text != null) { return text; } } string[] array = ncursesLocations; foreach (string text2 in array) { if (Directory.Exists(text2)) { string text3 = TryTermInfoDir(text2, term); if (text3 != null) { return text3; } } } return null; } public static TtyInfo GetTtyInfo(string terminal = null) { terminal = terminal ?? Environment.GetEnvironmentVariable("TERM"); string text = FindTermInfoPath(terminal); if (text == null) { return TtyInfo.Default; } TtyInfo ttyInfo = TtyInfoParser.Parse(File.ReadAllBytes(text)); ttyInfo.TerminalType = terminal; return ttyInfo; } } internal static class TtyInfoParser { internal enum TermInfoNumbers { MaxColors = 13 } internal enum TermInfoStrings { SetAForeground = 359 } private static readonly int[] ansiColorMapping = new int[16] { 0, 4, 2, 6, 1, 5, 3, 7, 8, 12, 10, 14, 9, 13, 11, 15 }; public static TtyInfo Parse(byte[] buffer) { int num; switch (GetInt16(buffer, 0)) { case 282: num = 2; break; case 542: num = 4; break; default: return TtyInfo.Default; } int @int = GetInt16(buffer, 4); GetInt16(buffer, 6); GetInt16(buffer, 8); int num2 = 12 + GetString(buffer, 12).Length + 1 + @int; int offset = num2 + num2 % 2 + num * 13; return new TtyInfo { MaxColors = GetInteger(num, buffer, offset), ForegroundColorStrings = ansiColorMapping.Select((int x) => $"\u001b[{((x > 7) ? (82 + x) : (30 + x))}m").ToArray() }; } private static int GetInt32(byte[] buffer, int offset) { return buffer[offset] | (buffer[offset + 1] << 8) | (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24); } private static short GetInt16(byte[] buffer, int offset) { return (short)(buffer[offset] | (buffer[offset + 1] << 8)); } private static int GetInteger(int intSize, byte[] buffer, int offset) { if (intSize != 2) { return GetInt32(buffer, offset); } return GetInt16(buffer, offset); } private static string GetString(byte[] buffer, int offset) { int i; for (i = 0; buffer[offset + i] != 0; i++) { } return Encoding.ASCII.GetString(buffer, offset, i); } } internal class UnixStream : Stream { public override bool CanRead { get { if (Access != FileAccess.Read) { return Access == FileAccess.ReadWrite; } return true; } } public override bool CanSeek => false; public override bool CanWrite { get { if (Access != FileAccess.Write) { return Access == FileAccess.ReadWrite; } return true; } } public override long Length { get { throw new InvalidOperationException(); } } public override long Position { get { throw new InvalidOperationException(); } set { throw new InvalidOperationException(); } } public FileAccess Access { get; } public IntPtr FileHandle { get; } public UnixStream(int fileDescriptor, FileAccess access) { Access = access; int fd = UnixStreamHelper.dup(fileDescriptor); FileHandle = UnixStreamHelper.fdopen(fd, (access == FileAccess.Write) ? "w" : "r"); } public override void Flush() { UnixStreamHelper.fflush(FileHandle); } public override long Seek(long offset, SeekOrigin origin) { throw new InvalidOperationException(); } public override void SetLength(long value) { throw new InvalidOperationException(); } public override int Read(byte[] buffer, int offset, int count) { GCHandle gCHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned); IntPtr intPtr = UnixStreamHelper.fread(new IntPtr(gCHandle.AddrOfPinnedObject().ToInt64() + offset), (IntPtr)count, (IntPtr)1, FileHandle); gCHandle.Free(); return intPtr.ToInt32(); } public override void Write(byte[] buffer, int offset, int count) { GCHandle gCHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned); UnixStreamHelper.fwrite(new IntPtr(gCHandle.AddrOfPinnedObject().ToInt64() + offset), (IntPtr)count, (IntPtr)1, FileHandle); gCHandle.Free(); } private void ReleaseUnmanagedResources() { UnixStreamHelper.fclose(FileHandle); } protected override void Dispose(bool disposing) { ReleaseUnmanagedResources(); base.Dispose(disposing); } ~UnixStream() { Dispose(disposing: false); } } internal static class UnixStreamHelper { public delegate int dupDelegate(int fd); public delegate int fcloseDelegate(IntPtr stream); public delegate IntPtr fdopenDelegate(int fd, string mode); public delegate int fflushDelegate(IntPtr stream); public delegate IntPtr freadDelegate(IntPtr ptr, IntPtr size, IntPtr nmemb, IntPtr stream); public delegate int fwriteDelegate(IntPtr ptr, IntPtr size, IntPtr nmemb, IntPtr stream); public delegate int isattyDelegate(int fd); [DynDllImport("libc", new string[] { })] public static dupDelegate dup; [DynDllImport("libc", new string[] { })] public static fdopenDelegate fdopen; [DynDllImport("libc", new string[] { })] public static freadDelegate fread; [DynDllImport("libc", new string[] { })] public static fwriteDelegate fwrite; [DynDllImport("libc", new string[] { })] public static fcloseDelegate fclose; [DynDllImport("libc", new string[] { })] public static fflushDelegate fflush; [DynDllImport("libc", new string[] { })] public static isattyDelegate isatty; static UnixStreamHelper() { Dictionary<string, List<DynDllMapping>> dictionary = new Dictionary<string, List<DynDllMapping>> { ["libc"] = new List<DynDllMapping> { DynDllMapping.op_Implicit("libc.so.6"), DynDllMapping.op_Implicit("libc"), DynDllMapping.op_Implicit("/usr/lib/libSystem.dylib") } }; DynDll.ResolveDynDllImports(typeof(UnixStreamHelper), dictionary); } public static Stream CreateDuplicateStream(int fileDescriptor) { return new UnixStream(dup(fileDescriptor), FileAccess.Write); } } } namespace BepInEx.Configuration { public abstract class AcceptableValueBase { public Type ValueType { get; } protected AcceptableValueBase(Type valueType) { ValueType = valueType; } public abstract object Clamp(object value); public abstract bool IsValid(object value); public abstract string ToDescriptionString(); } public class AcceptableValueList<T> : AcceptableValueBase where T : IEquatable<T> { public virtual T[] AcceptableValues { get; } public AcceptableValueList(params T[] acceptableValues) : base(typeof(T)) { if (acceptableValues == null) { throw new ArgumentNullException("acceptableValues"); } if (acceptableValues.Length == 0) { throw new ArgumentException("At least one acceptable value is needed", "acceptableValues"); } AcceptableValues = acceptableValues; } public override object Clamp(object value) { if (IsValid(value)) { return value; } return AcceptableValues[0]; } public override bool IsValid(object value) { if (value is T) { T v = (T)value; return AcceptableValues.Any((T x) => x.Equals(v)); } return false; } public override string ToDescriptionString() { return "# Acceptable values: " + string.Join(", ", AcceptableValues.Select((T x) => x.ToString()).ToArray()); } } public class AcceptableValueRange<T> : AcceptableValueBase where T : IComparable { public virtual T MinValue { get; } public virtual T MaxValue { get; } public AcceptableValueRange(T minValue, T maxValue) : base(typeof(T)) { if (maxValue == null) { throw new ArgumentNullException("maxValue"); } if (minValue == null) { throw new ArgumentNullException("minValue"); } if (minValue.CompareTo(maxValue) >= 0) { throw new ArgumentException("minValue has to be lower than maxValue"); } MinValue = minValue; MaxValue = maxValue; } public override object Clamp(object value) { if (MinValue.CompareTo(value) > 0) { return MinValue; } if (MaxValue.CompareTo(value) < 0) { return MaxValue; } return value; } public override bool IsValid(object value) { if (MinValue.CompareTo(value) <= 0) { return MaxValue.CompareTo(value) >= 0; } return false; } public override string ToDescriptionString() { return $"# Acceptable value range: From {MinValue} to {MaxValue}"; } } public class ConfigDefinition : IEquatable<ConfigDefinition> { private static readonly char[] _invalidConfigChars = new char[8] { '=', '\n', '\t', '\\', '"', '\'', '[', ']' }; public string Section { get; } public string Key { get; } public ConfigDefinition(string section, string key) { CheckInvalidConfigChars(section, "section"); CheckInvalidConfigChars(key, "key"); Key = key; Section = section; } [Obsolete("description argument is no longer used, put it in a ConfigDescription instead")] public ConfigDefinition(string section, string key, string description) { Key = key ?? ""; Section = section ?? ""; } public bool Equals(ConfigDefinition other) { if (other == null) { return false; } if (string.Equals(Key, other.Key)) { return string.Equals(Section, other.Section); } return false; } private static void CheckInvalidConfigChars(string val, string name) { if (val == null) { throw new ArgumentNullException(name); } if (val != val.Trim()) { throw new ArgumentException("Cannot use whitespace characters at start or end of section and key names", name); } if (val.Any((char c) => _invalidConfigChars.Contains(c))) { throw new ArgumentException("Cannot use any of the following characters in section and key names: = \\n \\t \\ \" ' [ ]", name); } } public override bool Equals(object obj) { if (obj == null) { return false; } if (this == obj) { return true; } return Equals(obj as ConfigDefinition); } public override int GetHashCode() { return (((Key != null) ? Key.GetHashCode() : 0) * 397) ^ ((Section != null) ? Section.GetHashCode() : 0); } public static bool operator ==(ConfigDefinition left, ConfigDefinition right) { return object.Equals(left, right); } public static bool operator !=(ConfigDefinition left, ConfigDefinition right) { return !object.Equals(left, right); } public override string ToString() { return Section + "." + Key; } } public class ConfigDescription { public string Description { get; } public AcceptableValueBase AcceptableValues { get; } public object[] Tags { get; } public static ConfigDescription Empty { get; } = new ConfigDescription("", null); public ConfigDescription(string description, AcceptableValueBase acceptableValues = null, params object[] tags) { AcceptableValues = acceptableValues; Tags = tags; Description = description ?? throw new ArgumentNullException("description"); } } public sealed class ConfigEntry<T> : ConfigEntryBase { private T _typedValue; public T Value { get { return _typedValue; } set { value = ClampValue(value); if (!object.Equals(_typedValue, value)) { _typedValue = value; OnSettingChanged(this); } } } public override object BoxedValue { get { return Value; } set { Value = (T)value; } } public event EventHandler SettingChanged; internal ConfigEntry(ConfigFile configFile, ConfigDefinition definition, T defaultValue, ConfigDescription configDescription) : base(configFile, definition, typeof(T), defaultValue, configDescription) { configFile.SettingChanged += delegate(object sender, SettingChangedEventArgs args) { if (args.ChangedSetting == this) { this.SettingChanged?.Invoke(sender, args); } }; } } public abstract class ConfigEntryBase { public ConfigFile ConfigFile { get; } public ConfigDefinition Definition { get; } public ConfigDescription Description { get; } public Type SettingType { get; } public object DefaultValue { get; } public abstract object BoxedValue { get; set; } protected internal ConfigEntryBase(ConfigFile configFile, ConfigDefinition definition, Type settingType, object defaultValue, ConfigDescription configDescription) { ConfigFile = configFile ?? throw new ArgumentNullException("configFile"); Definition = definition ?? throw new ArgumentNullException("definition"); SettingType = settingType ?? throw new ArgumentNullException("settingType"); Description = configDescription ?? ConfigDescription.Empty; if (Description.AcceptableValues != null && !SettingType.IsAssignableFrom(Description.AcceptableValues.ValueType)) { throw new ArgumentException("configDescription.AcceptableValues is for a different type than the type of this setting"); } DefaultValue = defaultValue; BoxedValue = defaultValue; } public string GetSerializedValue() { return TomlTypeConverter.ConvertToString(BoxedValue, SettingType); } public void SetSerializedValue(string value) { try { object boxedValue = TomlTypeConverter.ConvertToValue(value, SettingType); BoxedValue = boxedValue; } catch (Exception ex) { LogLevel logLevel = LogLevel.Warning; bool isEnabled; BepInExLogInterpolatedStringHandler bepInExLogInterpolatedStringHandler = new BepInExLogInterpolatedStringHandler(85, 3, logLevel, out isEnabled); if (isEnabled) { bepInExLogInterpolatedStringHandler.AppendLiteral("Config value of setting \""); bepInExLogInterpolatedStringHandler.AppendFormatted(Definition); bepInExLogInterpolatedStringHandler.AppendLiteral("\" could not be parsed and will be ignored. Reason: "); bepInExLogInterpolatedStringHandler.AppendFormatted(ex.Message); bepInExLogInterpolatedStringHandler.AppendLiteral("; Value: "); bepInExLogInterpolatedStringHandler.AppendFormatted(value); } Logger.Log(logLevel, bepInExLogInterpolatedStringHandler); } } protected T ClampValue<T>(T value) { if (Description.AcceptableValues != null) { return (T)Description.AcceptableValues.Clamp(value); } return value; } protected void OnSettingChanged(object sender) { ConfigFile.OnSettingChanged(sender, this); } public void WriteDescription(StreamWriter writer) { if (!string.IsNullOrEmpty(Description.Description)) { writer.WriteLine("## " + Description.Description.Replace("\n", "\n## ")); } writer.WriteLine("# Setting type: " + SettingType.Name); writer.WriteLine("# Default value: " + TomlTypeConverter.ConvertToString(DefaultValue, SettingType)); if (Description.AcceptableValues != null) { writer.WriteLine(Description.AcceptableValues.ToDescriptionString()); } else if (SettingType.IsEnum) { writer.WriteLine("# Acceptable values: " + string.Join(", ", Enum.GetNames(SettingType))); if (SettingType.GetCustomAttributes(typeof(FlagsAttribute), inherit: true).Any()) { writer.WriteLine("# Multiple values can be set at the same time by separating them with , (e.g. Debug, Warning)"); } } } } public class ConfigFile : IDictionary<ConfigDefinition, ConfigEntryBase>, ICollection<KeyValuePair<ConfigDefinition, ConfigEntryBase>>, IEnumerable<KeyValuePair<ConfigDefinition, ConfigEntryBase>>, IEnumerable { private readonly BepInPlugin _ownerMetadata; private readonly object _ioLock = new object(); public static ConfigFile CoreConfig { get; } = new ConfigFile(Paths.BepInExConfigPath, saveOnInit: true); protected Dictionary<ConfigDefinition, ConfigEntryBase> Entries { get; } = new Dictionary<ConfigDefinition, ConfigEntryBase>(); private Dictionary<ConfigDefinition, string> OrphanedEntries { get; } = new Dictionary<ConfigDefinition, string>(); [Obsolete("Use Keys instead")] public ReadOnlyCollection<ConfigDefinition> ConfigDefinitions { get { lock (_ioLock) { return Entries.Keys.ToList().AsReadOnly(); } } } public string ConfigFilePath { get; } public bool SaveOnConfigSet { get; set; } = true; public ConfigEntryBase this[ConfigDefinition key] { get { lock (_ioLock) { return Entries[key]; } } } public ConfigEntryBase this[string section, string key] => this[new ConfigDefinition(section, key)]; public int Count { get { lock (_ioLock) { return Entries.Count; } } } public bool IsReadOnly => false; ConfigEntryBase IDictionary<ConfigDefinition, ConfigEntryBase>.this[ConfigDefinition key] { get { lock (_ioLock) { return Entries[key]; } } set { throw new InvalidOperationException("Directly setting a config entry is not supported"); } } public ICollection<ConfigDefinition> Keys { get { lock (_ioLock) { return Entries.Keys.ToArray(); } } } public ICollection<ConfigEntryBase> Values { get { lock (_ioLock) { return Entries.Values.ToArray(); } } } public bool GenerateSettingDescriptions { get; set; } = true; public event EventHandler ConfigReloaded; public event EventHandler<SettingChangedEventArgs> SettingChanged; public ConfigFile(string configPath, bool saveOnInit) : this(configPath, saveOnInit, null) { } public ConfigFile(string configPath, bool saveOnInit, BepInPlugin ownerMetadata) { _ownerMetadata = ownerMetadata; if (configPath == null) { throw new ArgumentNullException("configPath"); } configPath = Path.GetFullPath(configPath); ConfigFilePath = configPath; if (File.Exists(ConfigFilePath)) { Reload(); } else if (saveOnInit) { Save(); } } public IEnumerator<KeyValuePair<ConfigDefinition, ConfigEntryBase>> GetEnumerator() { return Entries.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } void ICollection<KeyValuePair<ConfigDefinition, ConfigEntryBase>>.Add(KeyValuePair<ConfigDefinition, ConfigEntryBase> item) { lock (_ioLock) { Entries.Add(item.Key, item.Value); } } public bool Contains(KeyValuePair<ConfigDefinition, ConfigEntryBase> item) { lock (_ioLock) { return ((ICollection<KeyValuePair<ConfigDefinition, ConfigEntryBase>>)Entries).Contains(item); } } void ICollection<KeyValuePair<ConfigDefinition, ConfigEntryBase>>.CopyTo(KeyValuePair<ConfigDefinition, ConfigEntryBase>[] array, int arrayIndex) { lock (_ioLock) { ((ICollection<KeyValuePair<ConfigDefinition, ConfigEntryBase>>)Entries).CopyTo(array, arrayIndex); } } bool ICollection<KeyValuePair<ConfigDefinition, ConfigEntryBase>>.Remove(KeyValuePair<ConfigDefinition, ConfigEntryBase> item) { lock (_ioLock) { return Entries.Remove(item.Key); } } public bool ContainsKey(ConfigDefinition key) { lock (_ioLock) { return Entries.ContainsKey(key); } } public void Add(ConfigDefinition key, ConfigEntryBase value) { throw new InvalidOperationException("Directly adding a config entry is not supported"); } public bool Remove(ConfigDefinition key) { lock (_ioLock) { return Entries.Remove(key); } } public void Clear() { lock (_ioLock) { Entries.Clear(); } } bool IDictionary<ConfigDefinition, ConfigEntryBase>.TryGetValue(ConfigDefinition key, out ConfigEntryBase value) { lock (_ioLock) { return Entries.TryGetValue(key, out value); } } [Obsolete("Use Values instead")] public ConfigEntryBase[] GetConfigEntries() { lock (_ioLock) { return Entries.Values.ToArray(); } } public void Reload() { lock (_ioLock) { OrphanedEntries.Clear(); string section = string.Empty; string[] array = File.ReadAllLines(ConfigFilePath); for (int i = 0; i < array.Length; i++) { string text = array[i].Trim(); if (text.StartsWith("#")) { continue; } if (text.StartsWith("[") && text.EndsWith("]")) { section = text.Substring(1, text.Length - 2); continue; } string[] array2 = text.Split(new char[1] { '=' }, 2); if (array2.Length == 2) { string key = array2[0].Trim(); string text2 = array2[1].Trim(); ConfigDefinition key2 = new ConfigDefinition(section, key); Entries.TryGetValue(key2, out var value); if (value != null) { value.SetSerializedValue(text2); } else { OrphanedEntries[key2] = text2; } } } } OnConfigReloaded(); } public void Save() { lock (_ioLock) { string directoryName = Path.GetDirectoryName(ConfigFilePath); if (directoryName != null) { Directory.CreateDirectory(directoryName); } using StreamWriter streamWriter = new StreamWriter(ConfigFilePath, append: false, Utility.UTF8NoBom); if (_ownerMetadata != null) { streamWriter.WriteLine($"## Settings file was created by plugin {_ownerMetadata.Name} v{_ownerMetadata.Version}"); streamWriter.WriteLine("## Plugin GUID: " + _ownerMetadata.GUID); streamWriter.WriteLine(); } foreach (var item in from x in Entries.Select((KeyValuePair<ConfigDefinition, ConfigEntryBase> x) => new { Key = x.Key, entry = x.Value, value = x.Value.GetSerializedValue() }).Concat(OrphanedEntries.Select((KeyValuePair<ConfigDefinition, string> x) => new { Key = x.Key, entry = (ConfigEntryBase)null, value = x.Value })) group x by x.Key.Section into x orderby x.Key select x) { streamWriter.WriteLine("[" + item.Key + "]"); foreach (var item2 in item) { if (GenerateSettingDescriptions) { streamWriter.WriteLine(); item2.entry?.WriteDescription(streamWriter); } streamWriter.WriteLine(item2.Key.Key + " = " + item2.value); } streamWriter.WriteLine(); } } } [Obsolete("Use ConfigFile[key] or TryGetEntry instead")] public ConfigEntry<T> GetSetting<T>(ConfigDefinition configDefinition) { if (!TryGetEntry(configDefinition, out ConfigEntry<T> entry)) { return null; } return entry; } [Obsolete("Use ConfigFile[key] or TryGetEntry instead")] public ConfigEntry<T> GetSetting<T>(string section, string key) { if (!TryGetEntry(section, key, out ConfigEntry<T> entry)) { return null; } return entry; } public bool TryGetEntry<T>(ConfigDefinition configDefinition, out ConfigEntry<T> entry) { lock (_ioLock) { if (Entries.TryGetValue(configDefinition, out var value)) { entry = (ConfigEntry<T>)value; return true; } entry = null; return false; } } public bool TryGetEntry<T>(string section, string key, out ConfigEntry<T> entry) { return TryGetEntry(new ConfigDefinition(section, key), out entry); } public ConfigEntry<T> Bind<T>(ConfigDefinition configDefinition, T defaultValue, ConfigDescription configDescription = null) { if (!TomlTypeConverter.CanConvert(typeof(T))) { throw new ArgumentException(string.Format("Type {0} is not supported by the config system. Supported types: {1}", typeof(T), string.Join(", ", (from x in TomlTypeConverter.GetSupportedTypes() select x.Name).ToArray()))); } lock (_ioLock) { if (Entries.TryGetValue(configDefinition, out var value)) { return (ConfigEntry<T>)value; } ConfigEntry<T> configEntry = new ConfigEntry<T>(this, configDefinition, defaultValue, configDescription); Entries[configDefinition] = configEntry; if (OrphanedEntries.TryGetValue(configDefinition, out var value2)) { configEntry.SetSerializedValue(value2); OrphanedEntries.Remove(configDefinition); } if (SaveOnConfigSet) { Save(); } return configEntry; } } public ConfigEntry<T> Bind<T>(string section, string key, T defaultValue, ConfigDescription configDescription = null) { return Bind(new ConfigDefinition(section, key), defaultValue, configDescription); } public ConfigEntry<T> Bind<T>(string section, string key, T defaultValue, string description) { return Bind(new ConfigDefinition(section, key), defaultValue, new ConfigDescription(description, null)); } [Obsolete("Use Bind instead")] public ConfigEntry<T> AddSetting<T>(ConfigDefinition configDefinition, T defaultValue, ConfigDescription configDescription = null) { return Bind(configDefinition, defaultValue, configDescription); } [Obsolete("Use Bind instead")] public ConfigEntry<T> AddSetting<T>(string section, string key, T defaultValue, ConfigDescription configDescription = null) { return Bind(new ConfigDefinition(section, key), defaultValue, configDescription); } [Obsolete("Use Bind instead")] public ConfigEntry<T> AddSetting<T>(string section, string key, T defaultValue, string description) { return Bind(new ConfigDefinition(section, key), defaultValue, new ConfigDescription(description, null)); } [Obsolete("Use Bind instead")] public ConfigWrapper<T> Wrap<T>(string section, string key, string description = null, T defaultValue = default(T)) { lock (_ioLock) { ConfigDefinition configDefinition = new ConfigDefinition(section, key, description); return new ConfigWrapper<T>(Bind(configDefinition, defaultValue, string.IsNullOrEmpty(description) ? null : new ConfigDescription(description, null))); } } [Obsolete("Use Bind instead")] public ConfigWrapper<T> Wrap<T>(ConfigDefinition configDefinition, T defaultValue = default(T)) { return Wrap(configDefinition.Section, configDefinition.Key, null, defaultValue); } internal void OnSettingChanged(object sender, ConfigEntryBase changedEntryBase) { if (changedEntryBase == null) { throw new ArgumentNullException("changedEntryBase"); } if (SaveOnConfigSet) { Save(); } EventHandler<SettingChangedEventArgs> eventHandler = this.SettingChanged; if (eventHandler == null) { return; } SettingChangedEventArgs e = new SettingChangedEventArgs(changedEntryBase); Delegate[] invocationList = eventHandler.GetInvocationList(); for (int i = 0; i < invocationList.Length; i++) { EventHandler<SettingChangedEventArgs> eventHandler2 = (EventHandler<SettingChangedEventArgs>)invocationList[i]; try { eventHandler2(sender, e); } catch (Exception data) { Logger.Log(LogLevel.Error, data); } } } private void OnConfigReloaded() { EventHandler eventHandler = this.ConfigReloaded; if (eventHandler == null) { return; } Delegate[] invocationList = eventHandler.GetInvocationList(); for (int i = 0; i < invocationList.Length; i++) { EventHandler eventHandler2 = (EventHandler)invocationList[i]; try { eventHandler2(this, EventArgs.Empty); } catch (Exception data) { Logger.Log(LogLevel.Error, data); } } } } [Obsolete("Use ConfigFile from new Bind overloads instead")] public sealed class ConfigWrapper<T> { public ConfigEntry<T> ConfigEntry { get; } public ConfigDefinition Definition => ConfigEntry.Definition; public ConfigFile ConfigFile => ConfigEntry.ConfigFile; public T Value { get { return ConfigEntry.Value; } set { ConfigEntry.Value = value; } } public event EventHandler SettingChanged; internal ConfigWrapper(ConfigEntry<T> configEntry) { ConfigWrapper<T> configWrapper = this; ConfigEntry = configEntry ?? throw new ArgumentNullException("configEntry"); configEntry.ConfigFile.SettingChanged += delegate(object sender, SettingChangedEventArgs args) { if (args.ChangedSetting == configEntry) { configWrapper.SettingChanged?.Invoke(sender, args); } }; } } public sealed class SettingChangedEventArgs : EventArgs { public ConfigEntryBase ChangedSetting { get; } public SettingChangedEventArgs(ConfigEntryBase changedSetting) { ChangedSetting = changedSetting; } } public static class TomlTypeConverter { private static Dictionary<Type, TypeConverter> TypeConverters { get; } = new Dictionary<Type, TypeConverter> { [typeof(string)] = new TypeConverter { ConvertToString = (object obj, Type type) => ((string)obj).Escape(), ConvertToObject = (string str, Type type) => Regex.IsMatch(str, "^\"?\\w:\\\\(?!\\\\)(?!.+\\\\\\\\)") ? str : str.Unescape() }, [typeof(bool)] = new TypeConverter { ConvertToString = (object obj, Type type) => obj.ToString().ToLowerInvariant(), ConvertToObject = (string str, Type type) => bool.Parse(str) }, [typeof(byte)] = new TypeConverter { ConvertToString = (object obj, Type type) => obj.ToString(), ConvertToObject = (string str, Type type) => byte.Parse(str) }, [typeof(sbyte)] = new TypeConverter { ConvertToString = (object obj, Type type) => obj.ToString(), ConvertToObject = (string str, Type type) => sbyte.Parse(str) }, [typeof(byte)] = new TypeConverter { ConvertToString = (object obj, Type type) => obj.ToString(), ConvertToObject = (string str, Type type) => byte.Parse(str) }, [typeof(short)] = new TypeConverter { ConvertToString = (object obj, Type type) => obj.ToString(), ConvertToObject = (string str, Type type) => short.Parse(str) }, [typeof(ushort)] = new TypeConverter { ConvertToString = (object obj, Type type) => obj.ToString(), ConvertToObject = (string str, Type type) => ushort.Parse(str) }, [typeof(int)] = new TypeConverter { ConvertToString = (object obj, Type type) => obj.ToString(), ConvertToObject = (string str, Type type) => int.Parse(str) }, [typeof(uint)] = new TypeConverter { ConvertToString = (object obj, Type type) => obj.ToString(), ConvertToObject = (string str, Type type) => uint.Parse(str) }, [typeof(long)] = new TypeConverter { ConvertToString = (object obj, Type type) => obj.ToString(), ConvertToObject = (string str, Type type) => long.Parse(str) }, [typeof(ulong)] = new TypeConverter { ConvertToString = (object obj, Type type) => obj.ToString(), ConvertToObject = (string str, Type type) => ulong.Parse(str) }, [typeof(float)] = new TypeConverter { ConvertToString = (object obj, Type type) => ((float)obj).ToString(NumberFormatInfo.InvariantInfo), ConvertToObject = (string str, Type type) => float.Parse(str, NumberFormatInfo.InvariantInfo) }, [typeof(double)] = new TypeConverter { ConvertToString = (object obj, Type type) => ((double)obj).ToString(NumberFormatInfo.InvariantInfo), ConvertToObject = (string str, Type type) => double.Parse(str, NumberFormatInfo.InvariantInfo) }, [typeof(decimal)] = new TypeConverter { ConvertToString = (object obj, Type type) => ((decimal)obj).ToString(NumberFormatInfo.InvariantInfo), ConvertToObject = (string str, Type type) => decimal.Parse(str, NumberFormatInfo.InvariantInfo) }, [typeof(Enum)] = new TypeConverter { ConvertToString = (object obj, Type type) => obj.ToString(), ConvertToObject = (string str, Type type) => Enum.Parse(type, str, ignoreCase: true) } }; public static string ConvertToString(object value, Type valueType) { return (GetConverter(valueType) ?? throw new InvalidOperationException($"Cannot convert from type {valueType}")).ConvertToString(value, valueType); } public static T ConvertToValue<T>(string value) { return (T)ConvertToValue(value, typeof(T)); } public static object ConvertToValue(string value, Type valueType) { return (GetConverter(valueType) ?? throw new InvalidOperationException("Cannot convert to type " + valueType.Name)).ConvertToObject(value, valueType); } public static TypeConverter GetConverter(Type valueType) { if ((object)valueType == null) { throw new ArgumentNullException("valueType"); } if (valueType.IsEnum) { return TypeConverters[typeof(Enum)]; } TypeConverters.TryGetValue(valueType, out var value); return value; } public static bool AddConverter(Type type, TypeConverter converter) { if ((object)type == null) { throw new ArgumentNullException("type"); }
BepInExPack\BepInEx\core\BepInEx.Preloader.Core.dll
Decompiled 2 months agousing System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Core.Logging.Interpolation; using BepInEx.Logging; using HarmonyLib; using Mono.Cecil; using MonoMod.Utils; using SemanticVersioning; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("BepInEx.Unity.Mono.Preloader")] [assembly: InternalsVisibleTo("BepInEx.NET.Framework.Launcher")] [assembly: InternalsVisibleTo("BepInEx.NET.CoreCLR")] [assembly: InternalsVisibleTo("BepInEx.Unity.IL2CPP")] [assembly: AssemblyCompany("BepInEx")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © 2022 BepInEx Team")] [assembly: AssemblyDescription("Core classes and utilities for BepInEx Preloader")] [assembly: AssemblyFileVersion("6.0.0.0")] [assembly: AssemblyInformationalVersion("6.0.0-be.697+53625800b86f6c68751445248260edf0b27a71c2")] [assembly: AssemblyProduct("BepInEx.Preloader.Core")] [assembly: AssemblyTitle("BepInEx.Preloader.Core")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("6.0.0.0")] [module: UnverifiableCode] namespace BepInEx.Preloader.RuntimeFixes { public static class ConsoleSetOutFix { private static LoggedTextWriter loggedTextWriter; internal static ManualLogSource ConsoleLogSource = Logger.CreateLogSource("Console"); public static void Apply() { loggedTextWriter = new LoggedTextWriter { Parent = Console.Out }; Console.SetOut(loggedTextWriter); Harmony.CreateAndPatchAll(typeof(ConsoleSetOutFix), (string)null); } [HarmonyPatch(typeof(Console), "SetOut")] [HarmonyPrefix] private static bool OnSetOut(TextWriter newOut) { loggedTextWriter.Parent = newOut; return false; } } internal class LoggedTextWriter : TextWriter { public override Encoding Encoding { get; } = Encoding.UTF8; public TextWriter Parent { get; set; } public override void Flush() { Parent.Flush(); } public override void Write(string value) { ConsoleSetOutFix.ConsoleLogSource.Log((LogLevel)16, (object)value); Parent.Write(value); } public override void WriteLine(string value) { ConsoleSetOutFix.ConsoleLogSource.Log((LogLevel)16, (object)value); Parent.WriteLine(value); } } public static class HarmonyBackendFix { private enum MonoModBackend { [Description("Auto")] auto, [Description("DynamicMethod")] dynamicmethod, [Description("MethodBuilder")] methodbuilder, [Description("Cecil")] cecil } private static readonly ConfigEntry<MonoModBackend> ConfigHarmonyBackend = ConfigFile.CoreConfig.Bind<MonoModBackend>("Preloader", "HarmonyBackend", MonoModBackend.auto, "Specifies which MonoMod backend to use for Harmony patches. Auto uses the best available backend.\nThis setting should only be used for development purposes (e.g. debugging in dnSpy). Other code might override this setting."); public static void Initialize() { switch (ConfigHarmonyBackend.Value) { case MonoModBackend.dynamicmethod: case MonoModBackend.methodbuilder: case MonoModBackend.cecil: Environment.SetEnvironmentVariable("MONOMOD_DMD_TYPE", ConfigHarmonyBackend.Value.ToString()); break; default: throw new ArgumentOutOfRangeException("ConfigHarmonyBackend", ConfigHarmonyBackend.Value, "Unknown backend"); case MonoModBackend.auto: break; } } } } namespace BepInEx.Preloader.Core { public class AssemblyBuildInfo { public enum FrameworkType { Unknown, NetFramework, NetStandard, NetCore } public Version NetFrameworkVersion { get; private set; } public bool IsAnyCpu { get; set; } public bool Is64Bit { get; set; } public FrameworkType AssemblyFrameworkType { get; set; } private void SetNet4Version(AssemblyDefinition assemblyDefinition) { //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_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) NetFrameworkVersion = new Version(0, 0); AssemblyFrameworkType = FrameworkType.Unknown; CustomAttribute val = ((IEnumerable<CustomAttribute>)assemblyDefinition.CustomAttributes).FirstOrDefault((Func<CustomAttribute, bool>)((CustomAttribute x) => ((MemberReference)x.AttributeType).FullName == "System.Runtime.Versioning.TargetFrameworkAttribute")); if (val == null || val.ConstructorArguments.Count < 1) { return; } CustomAttributeArgument val2 = val.ConstructorArguments[0]; if (((MemberReference)((CustomAttributeArgument)(ref val2)).Type).Name != "String") { return; } val2 = val.ConstructorArguments[0]; string[] array = ((string)((CustomAttributeArgument)(ref val2)).Value).Split(new char[1] { ',' }); foreach (string text in array) { if (text.StartsWith(".NET")) { AssemblyFrameworkType = text switch { ".NETFramework" => FrameworkType.NetFramework, ".NETCoreApp" => FrameworkType.NetCore, ".NETStandard" => FrameworkType.NetStandard, _ => FrameworkType.Unknown, }; } else if (text.StartsWith("Version=v")) { try { NetFrameworkVersion = new Version(text.Substring("Version=v".Length)); } catch { } } } } public static AssemblyBuildInfo DetermineInfo(AssemblyDefinition assemblyDefinition) { //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_002b: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Invalid comparison between Unknown and I4 //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Invalid comparison between Unknown and I4 //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0071: 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) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Invalid comparison between Unknown and I4 //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Invalid comparison between Unknown and I4 //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Invalid comparison between Unknown and I4 //IL_009e: 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_00e2: Invalid comparison between Unknown and I4 //IL_00c3: Unknown result type (might be due to invalid IL or missing references) AssemblyBuildInfo assemblyBuildInfo = new AssemblyBuildInfo(); TargetRuntime runtime = assemblyDefinition.MainModule.Runtime; if ((int)runtime == 0) { assemblyBuildInfo.NetFrameworkVersion = new Version(1, 0); assemblyBuildInfo.AssemblyFrameworkType = FrameworkType.NetFramework; } else if ((int)runtime == 1) { assemblyBuildInfo.NetFrameworkVersion = new Version(1, 1); assemblyBuildInfo.AssemblyFrameworkType = FrameworkType.NetFramework; } else if ((int)runtime == 2) { assemblyBuildInfo.NetFrameworkVersion = new Version(3, 5); assemblyBuildInfo.AssemblyFrameworkType = FrameworkType.NetFramework; } else { assemblyBuildInfo.SetNet4Version(assemblyDefinition); } TargetArchitecture architecture = assemblyDefinition.MainModule.Architecture; ModuleAttributes attributes = assemblyDefinition.MainModule.Attributes; if ((int)architecture == 34404) { assemblyBuildInfo.Is64Bit = true; assemblyBuildInfo.IsAnyCpu = false; } else if ((int)architecture == 332 && HasFlag(attributes, (ModuleAttributes)131074)) { assemblyBuildInfo.Is64Bit = false; assemblyBuildInfo.IsAnyCpu = true; } else if ((int)architecture == 332 && HasFlag(attributes, (ModuleAttributes)2)) { assemblyBuildInfo.Is64Bit = false; assemblyBuildInfo.IsAnyCpu = false; } else { if ((int)architecture != 332) { throw new Exception("Unable to determine assembly architecture"); } assemblyBuildInfo.Is64Bit = true; assemblyBuildInfo.IsAnyCpu = true; } return assemblyBuildInfo; } private static bool HasFlag(ModuleAttributes value, ModuleAttributes flag) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Unknown result type (might be due to invalid IL or missing references) return (ModuleAttributes)(value & flag) == flag; } public override string ToString() { string arg = AssemblyFrameworkType switch { FrameworkType.NetFramework => "Framework", FrameworkType.NetStandard => "Standard", FrameworkType.NetCore => "Core", FrameworkType.Unknown => "Unknown", _ => throw new ArgumentOutOfRangeException(), }; if (IsAnyCpu) { return string.Format(".NET {0} {1}, AnyCPU ({2}-bit preferred)", arg, NetFrameworkVersion, Is64Bit ? "64" : "32"); } return string.Format(".NET {0} {1}, {2}", arg, NetFrameworkVersion, Is64Bit ? "x64" : "x86"); } } public static class EnvVars { public static string DOORSTOP_INVOKE_DLL_PATH { get; private set; } public static string DOORSTOP_MANAGED_FOLDER_DIR { get; private set; } public static string DOORSTOP_PROCESS_PATH { get; private set; } public static string[] DOORSTOP_DLL_SEARCH_DIRS { get; private set; } public static string DOORSTOP_MONO_LIB_PATH { get; private set; } internal static void LoadVars() { DOORSTOP_INVOKE_DLL_PATH = Environment.GetEnvironmentVariable("DOORSTOP_INVOKE_DLL_PATH"); DOORSTOP_MANAGED_FOLDER_DIR = Environment.GetEnvironmentVariable("DOORSTOP_MANAGED_FOLDER_DIR"); DOORSTOP_PROCESS_PATH = Environment.GetEnvironmentVariable("DOORSTOP_PROCESS_PATH"); DOORSTOP_MONO_LIB_PATH = Environment.GetEnvironmentVariable("DOORSTOP_MONO_LIB_PATH"); DOORSTOP_DLL_SEARCH_DIRS = Environment.GetEnvironmentVariable("DOORSTOP_DLL_SEARCH_DIRS")?.Split(new char[1] { Path.PathSeparator }) ?? new string[0]; } } public static class PreloaderLogger { public static ManualLogSource Log { get; } = Logger.CreateLogSource("Preloader"); } internal static class PlatformUtils { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] [return: MarshalAs(UnmanagedType.LPStr)] private delegate string GetWineVersionDelegate(); [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 1)] public struct WindowsOSVersionInfoExW { public uint dwOSVersionInfoSize; public uint dwMajorVersion; public uint dwMinorVersion; public uint dwBuildNumber; public uint dwPlatformId; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] public string szCSDVersion; public ushort wServicePackMajor; public ushort wServicePackMinor; public ushort wSuiteMask; public byte wProductType; public byte wReserved; public WindowsOSVersionInfoExW() { dwOSVersionInfoSize = (uint)Marshal.SizeOf(typeof(WindowsOSVersionInfoExW)); dwMajorVersion = 0u; dwMinorVersion = 0u; dwBuildNumber = 0u; dwPlatformId = 0u; szCSDVersion = null; wServicePackMajor = 0; wServicePackMinor = 0; wSuiteMask = 0; wProductType = 0; wReserved = 0; } } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct utsname_osx { private const int osx_utslen = 256; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string sysname; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string nodename; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string release; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string version; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)] public string machine; } [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct utsname_linux { private const int linux_utslen = 65; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)] public string sysname; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)] public string nodename; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)] public string release; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)] public string version; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)] public string machine; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)] public string domainname; } public static readonly bool ProcessIs64Bit = IntPtr.Size >= 8; public static Version WindowsVersion { get; set; } public static string WineVersion { get; set; } public static string LinuxArchitecture { get; set; } public static string LinuxKernelVersion { get; set; } [DllImport("libc.so.6", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, EntryPoint = "uname")] private static extern IntPtr uname_linux(ref utsname_linux utsname); [DllImport("/usr/lib/libSystem.dylib", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, EntryPoint = "uname")] private static extern IntPtr uname_osx(ref utsname_osx utsname); [DllImport("ntdll.dll", SetLastError = true)] private static extern bool RtlGetVersion(ref WindowsOSVersionInfoExW versionInfo); [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr LoadLibrary(string libraryName); [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr GetProcAddress(IntPtr hModule, string procName); private static bool Is(this Platform current, Platform expected) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Unknown result type (might be due to invalid IL or missing references) return (Platform)(current & expected) == expected; } public static void SetPlatform() { //IL_0002: 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_0081: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: 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_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_015b: 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_0162: Unknown result type (might be due to invalid IL or missing references) //IL_01b5: Unknown result type (might be due to invalid IL or missing references) //IL_0198: Unknown result type (might be due to invalid IL or missing references) //IL_01c2: Unknown result type (might be due to invalid IL or missing references) //IL_01c3: Unknown result type (might be due to invalid IL or missing references) //IL_01b1: Unknown result type (might be due to invalid IL or missing references) //IL_01b2: Unknown result type (might be due to invalid IL or missing references) //IL_01c4: 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) //IL_01ed: 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_029a: Unknown result type (might be due to invalid IL or missing references) //IL_02a0: Unknown result type (might be due to invalid IL or missing references) //IL_02a1: 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_0275: Unknown result type (might be due to invalid IL or missing references) //IL_0276: Unknown result type (might be due to invalid IL or missing references) Platform val = (Platform)17; PropertyInfo property = typeof(Environment).GetProperty("Platform", BindingFlags.Static | BindingFlags.NonPublic); string text = (((object)property == null) ? Environment.OSVersion.Platform.ToString() : property.GetValue(null, new object[0]).ToString()); text = text.ToLowerInvariant(); if (text.Contains("win")) { val = (Platform)37; } else if (text.Contains("mac") || text.Contains("osx")) { val = (Platform)73; } else if (text.Contains("lin") || text.Contains("unix")) { val = (Platform)137; } if (val.Is((Platform)137) && Directory.Exists("/data") && File.Exists("/system/build.prop")) { val = (Platform)393; } else if (val.Is((Platform)8) && Directory.Exists("/System/Library/AccessibilityBundles")) { val = (Platform)585; } if (val.Is((Platform)37)) { WindowsOSVersionInfoExW versionInfo = new WindowsOSVersionInfoExW(); RtlGetVersion(ref versionInfo); WindowsVersion = new Version((int)versionInfo.dwMajorVersion, (int)versionInfo.dwMinorVersion, 0, (int)versionInfo.dwBuildNumber); IntPtr intPtr = LoadLibrary("ntdll.dll"); if (intPtr != IntPtr.Zero) { IntPtr procAddress = GetProcAddress(intPtr, "wine_get_version"); if (procAddress != IntPtr.Zero) { val = (Platform)(val | 0x20000); WineVersion = DynDll.AsDelegate<GetWineVersionDelegate>(procAddress)(); } } } MethodInfo methodInfo = typeof(Environment).GetProperty("Is64BitOperatingSystem")?.GetGetMethod(); val = (Platform)(((object)methodInfo == null) ? (val | ((IntPtr.Size >= 8) ? 2 : 0)) : (val | (((bool)methodInfo.Invoke(null, new object[0])) ? 2 : 0))); if ((val.Is((Platform)73) || val.Is((Platform)137)) && (object)Type.GetType("Mono.Runtime") != null) { IntPtr intPtr2; string machine; if (val.Is((Platform)73)) { utsname_osx utsname = default(utsname_osx); intPtr2 = uname_osx(ref utsname); machine = utsname.machine; } else { utsname_linux utsname2 = default(utsname_linux); intPtr2 = uname_linux(ref utsname2); machine = utsname2.machine; LinuxArchitecture = utsname2.machine; LinuxKernelVersion = utsname2.version; } if (intPtr2 == IntPtr.Zero && (machine.StartsWith("aarch") || machine.StartsWith("arm"))) { val = (Platform)(val | 0x10000); } } else { typeof(object).Module.GetPEKind(out var _, out var machine2); if (machine2 == ImageFileMachine.ARM) { val = (Platform)(val | 0x10000); } } PlatformHelper.Current = val; } } } namespace BepInEx.Preloader.Core.Patching { public class AssemblyPatcher : IDisposable { private static readonly string CurrentAssemblyName = Assembly.GetExecutingAssembly().GetName().Name; private Func<byte[], string, Assembly> assemblyLoader; private static readonly ConfigEntry<bool> ConfigDumpAssemblies = ConfigFile.CoreConfig.Bind<bool>("Preloader", "DumpAssemblies", false, "If enabled, BepInEx will save patched assemblies into BepInEx/DumpedAssemblies.\nThis can be used by developers to inspect and debug preloader patchers."); private static readonly ConfigEntry<bool> ConfigLoadDumpedAssemblies = ConfigFile.CoreConfig.Bind<bool>("Preloader", "LoadDumpedAssemblies", false, "If enabled, BepInEx will load patched assemblies from BepInEx/DumpedAssemblies instead of memory.\nThis can be used to be able to load patched assemblies into debuggers like dnSpy.\nIf set to true, will override DumpAssemblies."); private static readonly ConfigEntry<bool> ConfigBreakBeforeLoadAssemblies = ConfigFile.CoreConfig.Bind<bool>("Preloader", "BreakBeforeLoadAssemblies", false, "If enabled, BepInEx will call Debugger.Break() once before loading patched assemblies.\nThis can be used with debuggers like dnSpy to install breakpoints into patched assemblies before they are loaded."); public PatcherContext PatcherContext { get; } = new PatcherContext { DumpedAssembliesPath = Utility.CombinePaths(new string[3] { Paths.BepInExRootPath, "DumpedAssemblies", Paths.ProcessName }) }; private IEnumerable<BasePatcher> PatcherPluginsSafe => PatcherContext.PatcherPlugins.ToList(); private ManualLogSource Logger { get; } = Logger.CreateLogSource("AssemblyPatcher"); private static Regex allowedGuidRegex { get; } = new Regex("^[a-zA-Z0-9\\._\\-]+$"); public AssemblyPatcher(Func<byte[], string, Assembly> assemblyLoader) { this.assemblyLoader = assemblyLoader; } public void Dispose() { foreach (KeyValuePair<string, AssemblyDefinition> availableAssembly in PatcherContext.AvailableAssemblies) { availableAssembly.Value.Dispose(); } PatcherContext.AvailableAssemblies.Clear(); PatcherContext.AvailableAssembliesPaths.Clear(); PatcherContext.PatcherPlugins.Clear(); } private PatcherPluginMetadata ToPatcherPlugin(TypeDefinition type, string assemblyPath) { //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_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Expected O, but got Unknown //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00be: 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_00c8: Expected O, but got Unknown //IL_0088: 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_0129: Unknown result type (might be due to invalid IL or missing references) //IL_012a: Unknown result type (might be due to invalid IL or missing references) //IL_012b: Unknown result type (might be due to invalid IL or missing references) //IL_012f: 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_0139: Expected O, but got Unknown //IL_017b: Unknown result type (might be due to invalid IL or missing references) //IL_017c: 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_0181: Unknown result type (might be due to invalid IL or missing references) //IL_0184: Unknown result type (might be due to invalid IL or missing references) //IL_018b: Expected O, but got Unknown //IL_0162: Unknown result type (might be due to invalid IL or missing references) //IL_01b4: Unknown result type (might be due to invalid IL or missing references) if (type.IsInterface || (type.IsAbstract && !type.IsSealed)) { return null; } try { if (!Utility.IsSubtypeOf(type, typeof(BasePatcher))) { return null; } } catch (AssemblyResolutionException) { return null; } PatcherPluginInfoAttribute patcherPluginInfoAttribute = PatcherPluginInfoAttribute.FromCecilType(type); bool flag = default(bool); if (patcherPluginInfoAttribute == null) { ManualLogSource logger = Logger; LogLevel val = (LogLevel)4; LogLevel val2 = val; BepInExLogInterpolatedStringHandler val3 = new BepInExLogInterpolatedStringHandler(59, 1, val, ref flag); if (flag) { val3.AppendLiteral("Skipping over type ["); val3.AppendFormatted<string>(((MemberReference)type).FullName); val3.AppendLiteral("] as no metadata attribute is specified"); } logger.Log(val2, val3); return null; } if (string.IsNullOrEmpty(patcherPluginInfoAttribute.GUID) || !allowedGuidRegex.IsMatch(patcherPluginInfoAttribute.GUID)) { ManualLogSource logger2 = Logger; LogLevel val2 = (LogLevel)4; LogLevel val = val2; BepInExLogInterpolatedStringHandler val3 = new BepInExLogInterpolatedStringHandler(60, 2, val2, ref flag); if (flag) { val3.AppendLiteral("Skipping type ["); val3.AppendFormatted<string>(((MemberReference)type).FullName); val3.AppendLiteral("] because its GUID ["); val3.AppendFormatted<string>(patcherPluginInfoAttribute.GUID); val3.AppendLiteral("] is of an illegal format"); } logger2.Log(val, val3); return null; } if (patcherPluginInfoAttribute.Version == (Version)null) { ManualLogSource logger3 = Logger; LogLevel val = (LogLevel)4; LogLevel val2 = val; BepInExLogInterpolatedStringHandler val3 = new BepInExLogInterpolatedStringHandler(47, 1, val, ref flag); if (flag) { val3.AppendLiteral("Skipping type ["); val3.AppendFormatted<string>(((MemberReference)type).FullName); val3.AppendLiteral("] because its version is invalid"); } logger3.Log(val2, val3); return null; } if (patcherPluginInfoAttribute.Name == null) { ManualLogSource logger4 = Logger; LogLevel val2 = (LogLevel)4; LogLevel val = val2; BepInExLogInterpolatedStringHandler val3 = new BepInExLogInterpolatedStringHandler(41, 1, val2, ref flag); if (flag) { val3.AppendLiteral("Skipping type ["); val3.AppendFormatted<string>(((MemberReference)type).FullName); val3.AppendLiteral("] because its name is null"); } logger4.Log(val, val3); return null; } return new PatcherPluginMetadata { TypeName = ((MemberReference)type).FullName }; } private bool HasPatcherPlugins(AssemblyDefinition ass) { if (((IEnumerable<AssemblyNameReference>)ass.MainModule.AssemblyReferences).All((AssemblyNameReference r) => r.Name != CurrentAssemblyName) && ((AssemblyNameReference)ass.Name).Name != CurrentAssemblyName) { return false; } if (ass.MainModule.GetTypeReferences().All((TypeReference r) => ((MemberReference)r).FullName != typeof(BasePatcher).FullName)) { return false; } return true; } public void AddPatchersFromDirectory(string directory) { //IL_0277: Unknown result type (might be due to invalid IL or missing references) //IL_0279: 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_0280: Unknown result type (might be due to invalid IL or missing references) //IL_0284: Unknown result type (might be due to invalid IL or missing references) //IL_028b: Expected O, but got Unknown //IL_02d9: Unknown result type (might be due to invalid IL or missing references) //IL_031e: Unknown result type (might be due to invalid IL or missing references) //IL_0320: Unknown result type (might be due to invalid IL or missing references) //IL_0322: Unknown result type (might be due to invalid IL or missing references) //IL_0327: 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_0332: Expected O, but got Unknown //IL_03bc: Unknown result type (might be due to invalid IL or missing references) //IL_01b0: Unknown result type (might be due to invalid IL or missing references) //IL_01b2: Unknown result type (might be due to invalid IL or missing references) //IL_01b4: 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_01bd: Unknown result type (might be due to invalid IL or missing references) //IL_01c4: Expected O, but got Unknown //IL_01ee: Unknown result type (might be due to invalid IL or missing references) if (!Directory.Exists(directory)) { return; } List<PatchDefinition> sortedPatchers = new List<PatchDefinition>(); bool flag = default(bool); foreach (KeyValuePair<string, List<PatcherPluginMetadata>> item in TypeLoader.FindPluginTypes<PatcherPluginMetadata>(directory, (Func<TypeDefinition, string, PatcherPluginMetadata>)ToPatcherPlugin, (Func<AssemblyDefinition, bool>)HasPatcherPlugins, (string)null)) { string key = item.Key; List<PatcherPluginMetadata> value = item.Value; if (value.Count == 0) { continue; } Assembly assembly = Assembly.LoadFrom(key); LogLevel val; LogLevel val2; BepInExLogInterpolatedStringHandler val3; foreach (PatcherPluginMetadata item2 in value) { try { Type? type = assembly.GetType(item2.TypeName); BasePatcher basePatcher = (BasePatcher)Activator.CreateInstance(type); basePatcher.Context = PatcherContext; PatcherContext.PatcherPlugins.Add(basePatcher); MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (MethodInfo methodInfo in methods) { TargetAssemblyAttribute[] attributes = MetadataHelper.GetAttributes<TargetAssemblyAttribute>((MemberInfo)methodInfo); TargetTypeAttribute[] attributes2 = MetadataHelper.GetAttributes<TargetTypeAttribute>((MemberInfo)methodInfo); if (attributes.Length == 0 && attributes2.Length == 0) { continue; } ParameterInfo[] parameters = methodInfo.GetParameters(); if (parameters.Length < 1 || parameters.Length > 2 || ((object)parameters[0].ParameterType != typeof(AssemblyDefinition) && ((object)parameters[0].ParameterType != typeof(AssemblyDefinition).MakeByRefType() || attributes2.Length != 0) && ((object)parameters[0].ParameterType != typeof(TypeDefinition) || attributes.Length != 0)) || (parameters.Length == 2 && (object)parameters[1].ParameterType != typeof(string)) || ((object)methodInfo.ReturnType != typeof(void) && (object)methodInfo.ReturnType != typeof(bool))) { ManualLogSource logger = Logger; val = (LogLevel)4; val2 = val; val3 = new BepInExLogInterpolatedStringHandler(54, 1, val, ref flag); if (flag) { val3.AppendLiteral("Skipping method ["); val3.AppendFormatted<string>(GeneralExtensions.FullDescription((MethodBase)methodInfo)); val3.AppendLiteral("] as it is not a valid patcher method"); } logger.Log(val2, val3); } else { TargetAssemblyAttribute[] array = attributes; foreach (TargetAssemblyAttribute targetAssembly in array) { AddDefinition(new PatchDefinition(targetAssembly, basePatcher, methodInfo)); } TargetTypeAttribute[] array2 = attributes2; foreach (TargetTypeAttribute targetType in array2) { AddDefinition(new PatchDefinition(targetType, basePatcher, methodInfo)); } } } } catch (Exception ex) { ManualLogSource logger2 = Logger; val2 = (LogLevel)2; val = val2; val3 = new BepInExLogInterpolatedStringHandler(38, 2, val2, ref flag); if (flag) { val3.AppendLiteral("Failed to load patchers from type ["); val3.AppendFormatted<string>(item2.TypeName); val3.AppendLiteral("]: "); val3.AppendFormatted<string>((ex is ReflectionTypeLoadException ex2) ? TypeLoader.TypeLoadExceptionToString(ex2) : ex.ToString()); } logger2.Log(val, val3); } } AssemblyName name = assembly.GetName(); ManualLogSource logger3 = Logger; val = (LogLevel)(value.Any() ? 16 : 32); val2 = val; val3 = new BepInExLogInterpolatedStringHandler(29, 4, val, ref flag); if (flag) { val3.AppendLiteral("Loaded "); val3.AppendFormatted<int>(value.Count); val3.AppendLiteral(" patcher type"); val3.AppendFormatted<string>((value.Count == 1) ? "" : "s"); val3.AppendLiteral(" from ["); val3.AppendFormatted<string>(name.Name); val3.AppendLiteral(" "); val3.AppendFormatted<Version>(name.Version); val3.AppendLiteral("]"); } logger3.Log(val2, val3); } PatcherContext.PatchDefinitions.AddRange(sortedPatchers); void AddDefinition(PatchDefinition definition) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000e: 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_0017: Expected O, but got Unknown //IL_003c: Unknown result type (might be due to invalid IL or missing references) ManualLogSource logger4 = Logger; LogLevel val4 = (LogLevel)32; LogLevel val5 = val4; bool flag2 = default(bool); BepInExLogInterpolatedStringHandler val6 = new BepInExLogInterpolatedStringHandler(19, 1, val4, ref flag2); if (flag2) { val6.AppendLiteral("Discovered patch ["); val6.AppendFormatted<string>(definition.FullName); val6.AppendLiteral("]"); } logger4.Log(val5, val6); sortedPatchers.Add(definition); } } public void LoadAssemblyDirectories(params string[] directories) { LoadAssemblyDirectories(directories, new string[1] { "dll" }); } public void LoadAssemblyDirectories(IEnumerable<string> directories, IEnumerable<string> assemblyExtensions) { //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Expected O, but got Unknown bool flag = default(bool); foreach (string item in assemblyExtensions.SelectMany((string ext) => Utility.GetUniqueFilesInDirectories(directories, "*." + ext))) { if (!TryLoadAssembly(item, out var assembly)) { continue; } if (((AssemblyNameReference)assembly.Name).Name == "System" || ((AssemblyNameReference)assembly.Name).Name == "mscorlib") { assembly.Dispose(); continue; } string fileName = Path.GetFileName(item); PatcherContext.AvailableAssemblies.Add(fileName, assembly); PatcherContext.AvailableAssembliesPaths.Add(fileName, item); ManualLogSource logger = Logger; BepInExDebugLogInterpolatedStringHandler val = new BepInExDebugLogInterpolatedStringHandler(17, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Assembly loaded: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(Path.GetFileName(item)); } logger.LogDebug(val); } } public static bool TryLoadAssembly(string path, out AssemblyDefinition assembly) { try { assembly = AssemblyDefinition.ReadAssembly(path, TypeLoader.ReaderParameters); return true; } catch (BadImageFormatException) { assembly = null; return false; } } public void PatchAndLoad() { //IL_004d: 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_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Expected O, but got Unknown //IL_06ee: Unknown result type (might be due to invalid IL or missing references) //IL_06f0: Unknown result type (might be due to invalid IL or missing references) //IL_06f2: Unknown result type (might be due to invalid IL or missing references) //IL_06f7: Unknown result type (might be due to invalid IL or missing references) //IL_06fb: Unknown result type (might be due to invalid IL or missing references) //IL_0702: Expected O, but got Unknown //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_073a: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: 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_00f1: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_00fc: Expected O, but got Unknown //IL_012f: Unknown result type (might be due to invalid IL or missing references) //IL_04f5: Unknown result type (might be due to invalid IL or missing references) //IL_04f7: Unknown result type (might be due to invalid IL or missing references) //IL_04f9: Unknown result type (might be due to invalid IL or missing references) //IL_04fe: Unknown result type (might be due to invalid IL or missing references) //IL_0502: Unknown result type (might be due to invalid IL or missing references) //IL_0509: Expected O, but got Unknown //IL_0535: Unknown result type (might be due to invalid IL or missing references) //IL_0546: Unknown result type (might be due to invalid IL or missing references) //IL_0548: Unknown result type (might be due to invalid IL or missing references) //IL_054a: Unknown result type (might be due to invalid IL or missing references) //IL_054f: Unknown result type (might be due to invalid IL or missing references) //IL_0553: Unknown result type (might be due to invalid IL or missing references) //IL_055a: Expected O, but got Unknown //IL_057c: Unknown result type (might be due to invalid IL or missing references) //IL_065a: Unknown result type (might be due to invalid IL or missing references) //IL_065c: Unknown result type (might be due to invalid IL or missing references) //IL_065e: Unknown result type (might be due to invalid IL or missing references) //IL_0663: Unknown result type (might be due to invalid IL or missing references) //IL_0667: Unknown result type (might be due to invalid IL or missing references) //IL_066e: Expected O, but got Unknown //IL_0698: Unknown result type (might be due to invalid IL or missing references) Dictionary<string, AssemblyDefinition> dictionary = new Dictionary<string, AssemblyDefinition>(PatcherContext.AvailableAssemblies, StringComparer.InvariantCultureIgnoreCase); bool flag = default(bool); LogLevel val2; LogLevel val; BepInExLogInterpolatedStringHandler val3; foreach (BasePatcher item in PatcherPluginsSafe) { try { item.Initialize(); } catch (Exception ex) { ManualLogSource logger = Logger; val = (LogLevel)2; val2 = val; val3 = new BepInExLogInterpolatedStringHandler(31, 2, val, ref flag); if (flag) { val3.AppendLiteral("Failed to run initializer of "); val3.AppendFormatted<string>(item.Info.GUID); val3.AppendLiteral(": "); val3.AppendFormatted<Exception>(ex); } logger.Log(val2, val3); } } HashSet<string> patchedAssemblies = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase); Dictionary<string, string> dictionary2 = new Dictionary<string, string>(); HashSet<string> invalidAssemblies = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase); ManualLogSource logger2 = Logger; val2 = (LogLevel)8; val = val2; val3 = new BepInExLogInterpolatedStringHandler(20, 1, val2, ref flag); if (flag) { val3.AppendLiteral("Executing "); val3.AppendFormatted<int>(PatcherContext.PatchDefinitions.Count); val3.AppendLiteral(" patch(es)"); } logger2.Log(val, val3); AssemblyName assemblyName = default(AssemblyName); foreach (PatchDefinition item2 in PatcherContext.PatchDefinitions.ToList()) { PatchDefinition patchDefinition = item2; string text = patchDefinition.TargetAssembly?.TargetAssembly ?? patchDefinition.TargetType.TargetAssembly; bool isAssemblyPatch = patchDefinition.TargetAssembly != null; if (text == "_all") { foreach (KeyValuePair<string, AssemblyDefinition> item3 in PatcherContext.AvailableAssemblies.ToList()) { if (!invalidAssemblies.Contains(item3.Key)) { RunPatcher(item3.Value, item3.Key); } } } else { if (!PatcherContext.AvailableAssemblies.TryGetValue(text, out var value) || invalidAssemblies.Contains(text)) { continue; } RunPatcher(value, text); } Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in assemblies) { string key = (Utility.TryParseAssemblyName(assembly.FullName, ref assemblyName) ? assemblyName.Name : assembly.FullName); if (!dictionary2.ContainsKey(key)) { dictionary2[key] = patchDefinition.MethodInfo.DeclaringType.ToString(); } } bool RunPatcher(AssemblyDefinition val5, string targetDll) { //IL_0189: 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_018d: Unknown result type (might be due to invalid IL or missing references) //IL_0192: Unknown result type (might be due to invalid IL or missing references) //IL_0196: Unknown result type (might be due to invalid IL or missing references) //IL_019d: Expected O, but got Unknown //IL_01f2: 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_005e: Expected O, but got Unknown //IL_0139: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Expected O, but got Unknown try { object[] array = new object[patchDefinition.MethodInfo.GetParameters().Length]; if (!isAssemblyPatch) { TypeDefinition val4 = ((IEnumerable<TypeDefinition>)val5.MainModule.Types).FirstOrDefault((Func<TypeDefinition, bool>)((TypeDefinition x) => ((MemberReference)x).FullName == patchDefinition.TargetType.TargetType)); if (val4 == null) { ManualLogSource logger7 = Logger; bool flag2 = default(bool); BepInExWarningLogInterpolatedStringHandler val6 = new BepInExWarningLogInterpolatedStringHandler(52, 2, ref flag2); if (flag2) { ((BepInExLogInterpolatedStringHandler)val6).AppendLiteral("Unable to find type ["); ((BepInExLogInterpolatedStringHandler)val6).AppendFormatted<string>(patchDefinition.TargetType.TargetType); ((BepInExLogInterpolatedStringHandler)val6).AppendLiteral("] defined in "); ((BepInExLogInterpolatedStringHandler)val6).AppendFormatted<string>(patchDefinition.MethodInfo.Name); ((BepInExLogInterpolatedStringHandler)val6).AppendLiteral(". Skipping patcher"); } logger7.LogWarning(val6); return false; } array[0] = val4; } else { array[0] = val5; } if (array.Length > 1) { array[1] = targetDll; } object obj = patchDefinition.MethodInfo.Invoke(patchDefinition.Instance, array); if ((object)patchDefinition.MethodInfo.ReturnType == typeof(void) || ((object)patchDefinition.MethodInfo.ReturnType == typeof(bool) && (bool)obj)) { if (isAssemblyPatch) { val5 = (AssemblyDefinition)array[0]; PatcherContext.AvailableAssemblies[targetDll] = val5; } patchedAssemblies.Add(targetDll); } return true; } catch (Exception ex3) { ManualLogSource logger8 = Logger; LogLevel val7 = (LogLevel)2; LogLevel val8 = val7; bool flag3 = default(bool); BepInExLogInterpolatedStringHandler val9 = new BepInExLogInterpolatedStringHandler(77, 3, val7, ref flag3); if (flag3) { val9.AppendLiteral("Failed to run ["); val9.AppendFormatted<string>(patchDefinition.FullName); val9.AppendLiteral("] when patching ["); val9.AppendFormatted<string>(((AssemblyNameReference)val5.Name).Name); val9.AppendLiteral("]. This assembly will not be patched. Error: "); val9.AppendFormatted<Exception>(ex3); } logger8.Log(val8, val9); patchedAssemblies.Remove(targetDll); invalidAssemblies.Add(targetDll); return false; } } } HashSet<string> patchedAssemblyNames = new HashSet<string>(from kv in dictionary where patchedAssemblies.Contains(kv.Key) select ((AssemblyNameReference)kv.Value.Name).Name, StringComparer.InvariantCultureIgnoreCase); List<KeyValuePair<string, string>> list = dictionary2.Where((KeyValuePair<string, string> kv) => patchedAssemblyNames.Contains(kv.Key)).ToList(); if (list.Count != 0) { Logger.Log((LogLevel)4, (object)new StringBuilder().AppendLine("The following assemblies have been loaded too early and will not be patched by preloader:").AppendLine(string.Join(Environment.NewLine, list.Select((KeyValuePair<string, string> kv) => "* [" + kv.Key + "] (first loaded by [" + kv.Value + "])").ToArray())).AppendLine("Expect unexpected behavior and issues with plugins and patchers not being loaded.") .ToString()); } Dictionary<string, string> dictionary3 = new Dictionary<string, string>(); if (ConfigDumpAssemblies.Value || ConfigLoadDumpedAssemblies.Value) { if (!Directory.Exists(PatcherContext.DumpedAssembliesPath)) { Directory.CreateDirectory(PatcherContext.DumpedAssembliesPath); } FileStream fileStream = default(FileStream); foreach (KeyValuePair<string, AssemblyDefinition> item4 in dictionary) { string key2 = item4.Key; string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(key2); string extension = Path.GetExtension(key2); AssemblyDefinition value2 = item4.Value; if (!patchedAssemblies.Contains(key2)) { continue; } int num = 0; string text3; while (true) { string text2 = ((num > 0) ? $"_{num}" : ""); text3 = Path.Combine(PatcherContext.DumpedAssembliesPath, fileNameWithoutExtension + text2 + extension); if (Utility.TryOpenFileStream(text3, FileMode.Create, ref fileStream, FileAccess.ReadWrite, FileShare.Read)) { break; } num++; } value2.Write((Stream)fileStream); fileStream.Dispose(); dictionary3[key2] = text3; } } if (ConfigBreakBeforeLoadAssemblies.Value) { ManualLogSource logger3 = Logger; val = (LogLevel)16; val2 = val; val3 = new BepInExLogInterpolatedStringHandler(48, 1, val, ref flag); if (flag) { val3.AppendLiteral("BepInEx is about load the following assemblies:\n"); val3.AppendFormatted<string>(string.Join("\n", patchedAssemblies.ToArray())); } logger3.Log(val2, val3); ManualLogSource logger4 = Logger; val2 = (LogLevel)16; val = val2; val3 = new BepInExLogInterpolatedStringHandler(32, 1, val2, ref flag); if (flag) { val3.AppendLiteral("The assemblies were dumped into "); val3.AppendFormatted<string>(PatcherContext.DumpedAssembliesPath); } logger4.Log(val, val3); Logger.Log((LogLevel)16, (object)"Load any assemblies into the debugger, set breakpoints and continue execution."); Debugger.Break(); } foreach (KeyValuePair<string, AssemblyDefinition> item5 in dictionary) { string key3 = item5.Key; AssemblyDefinition value3 = item5.Value; if (patchedAssemblies.Contains(key3)) { Assembly value5; if (ConfigLoadDumpedAssemblies.Value && dictionary3.TryGetValue(key3, out var value4)) { value5 = Assembly.LoadFrom(value4); } else { using MemoryStream memoryStream = new MemoryStream(); value3.Write((Stream)memoryStream); value5 = assemblyLoader(memoryStream.ToArray(), PatcherContext.AvailableAssembliesPaths[key3]); } PatcherContext.LoadedAssemblies.Add(key3, value5); ManualLogSource logger5 = Logger; val = (LogLevel)32; val2 = val; val3 = new BepInExLogInterpolatedStringHandler(21, 1, val, ref flag); if (flag) { val3.AppendLiteral("Loaded '"); val3.AppendFormatted<string>(value3.FullName); val3.AppendLiteral("' into memory"); } logger5.Log(val2, val3); } value3.Dispose(); } foreach (BasePatcher item6 in PatcherPluginsSafe) { try { item6.Finalizer(); } catch (Exception ex2) { ManualLogSource logger6 = Logger; val2 = (LogLevel)2; val = val2; val3 = new BepInExLogInterpolatedStringHandler(29, 2, val2, ref flag); if (flag) { val3.AppendLiteral("Failed to run finalizer of "); val3.AppendFormatted<string>(item6.Info.GUID); val3.AppendLiteral(": "); val3.AppendFormatted<Exception>(ex2); } logger6.Log(val, val3); } } } } [AttributeUsage(AttributeTargets.Class)] public class PatcherPluginInfoAttribute : Attribute { public string GUID { get; protected set; } public string Name { get; protected set; } public Version Version { get; protected set; } public PatcherPluginInfoAttribute(string GUID, string Name, string Version) { this.GUID = GUID; this.Name = Name; this.Version = TryParseLongVersion(Version); } private static Version TryParseLongVersion(string version) { //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Expected O, but got Unknown Version result = default(Version); if (Version.TryParse(version, ref result)) { return result; } try { Version version2 = new Version(version); return new Version(version2.Major, version2.Minor, (version2.Build != -1) ? version2.Build : 0, (string)null, (string)null); } catch { } return null; } internal static PatcherPluginInfoAttribute FromCecilType(TypeDefinition td) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0032: 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_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) CustomAttribute val = MetadataHelper.GetCustomAttributes<PatcherPluginInfoAttribute>(td, false).FirstOrDefault(); if (val == null) { return null; } CustomAttributeArgument val2 = val.ConstructorArguments[0]; string gUID = (string)((CustomAttributeArgument)(ref val2)).Value; val2 = val.ConstructorArguments[1]; string name = (string)((CustomAttributeArgument)(ref val2)).Value; val2 = val.ConstructorArguments[2]; return new PatcherPluginInfoAttribute(gUID, name, (string)((CustomAttributeArgument)(ref val2)).Value); } internal static PatcherPluginInfoAttribute FromType(Type type) { object[] customAttributes = type.GetCustomAttributes(typeof(PatcherPluginInfoAttribute), inherit: false); if (customAttributes.Length == 0) { return null; } return (PatcherPluginInfoAttribute)customAttributes[0]; } } [AttributeUsage(AttributeTargets.Method)] public class TargetAssemblyAttribute : Attribute { public const string AllAssemblies = "_all"; public string TargetAssembly { get; } public TargetAssemblyAttribute(string targetAssembly) { TargetAssembly = targetAssembly; } } [AttributeUsage(AttributeTargets.Method)] public class TargetTypeAttribute : Attribute { public string TargetAssembly { get; } public string TargetType { get; } public TargetTypeAttribute(string targetAssembly, string targetType) { TargetAssembly = targetAssembly; TargetType = targetType; } } public abstract class BasePatcher { public ManualLogSource Log { get; } public ConfigFile Config { get; } public PatcherPluginInfoAttribute Info { get; } public PatcherContext Context { get; set; } protected BasePatcher() { //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Expected O, but got Unknown //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Expected O, but got Unknown Info = PatcherPluginInfoAttribute.FromType(GetType()); Log = Logger.CreateLogSource(Info.Name); Config = new ConfigFile(Utility.CombinePaths(new string[2] { Paths.ConfigPath, Info.GUID + ".cfg" }), false, new BepInPlugin(Info.GUID, Info.Name, ((object)Info.Version).ToString())); } public virtual void Initialize() { } public virtual void Finalizer() { } } public class PatchDefinition { public TargetAssemblyAttribute TargetAssembly { get; } public TargetTypeAttribute TargetType { get; } public BasePatcher Instance { get; } public MethodInfo MethodInfo { get; } public string FullName { get; } public PatchDefinition(TargetAssemblyAttribute targetAssembly, BasePatcher instance, MethodInfo methodInfo) { TargetAssembly = targetAssembly; Instance = instance; MethodInfo = methodInfo; FullName = MethodInfo.DeclaringType.FullName + "/" + MethodInfo.Name + " -> " + TargetAssembly.TargetAssembly; } public PatchDefinition(TargetTypeAttribute targetType, BasePatcher instance, MethodInfo methodInfo) { TargetType = targetType; Instance = instance; MethodInfo = methodInfo; FullName = MethodInfo.DeclaringType.FullName + "/" + MethodInfo.Name + " -> " + TargetType.TargetAssembly + "/" + TargetType.TargetType; } } public class PatcherContext { public Dictionary<string, AssemblyDefinition> AvailableAssemblies { get; } = new Dictionary<string, AssemblyDefinition>(); public Dictionary<string, string> AvailableAssembliesPaths { get; } = new Dictionary<string, string>(); public Dictionary<string, Assembly> LoadedAssemblies { get; } = new Dictionary<string, Assembly>(); public List<BasePatcher> PatcherPlugins { get; } = new List<BasePatcher>(); public List<PatchDefinition> PatchDefinitions { get; } = new List<PatchDefinition>(); public string DumpedAssembliesPath { get; internal set; } } internal class PatcherPluginMetadata : ICacheable { public string TypeName { get; set; } = string.Empty; public void Save(BinaryWriter bw) { bw.Write(TypeName); } public void Load(BinaryReader br) { TypeName = br.ReadString(); } } } namespace BepInEx.Preloader.Core.Logging { public static class ChainloaderLogHelper { private static Dictionary<string, string> MacOSVersions { get; } = new Dictionary<string, string> { ["16.0.0"] = "10.12", ["16.5.0"] = "10.12.4", ["16.6.0"] = "10.12.6", ["17.5.0"] = "10.13.4", ["17.6.0"] = "10.13.5", ["17.7.0"] = "10.13.6", ["18.2.0"] = "10.14.1", ["19.2.0"] = "10.15.2", ["19.3.0"] = "10.15.3", ["19.5.0"] = "10.15.5.1", ["20.1.0"] = "11.0", ["20.2.0"] = "11.1", ["20.3.0"] = "11.2", ["20.4.0"] = "11.3", ["20.5.0"] = "11.4", ["21.0.1"] = "12.0", ["21.1.0"] = "12.0.1", ["21.2.0"] = "12.1" }; public static void PrintLogInfo(ManualLogSource log) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Expected O, but got Unknown //IL_0093: 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_009a: 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_00a5: Expected O, but got Unknown //IL_005a: 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_005c: 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_0064: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Expected O, but got Unknown //IL_00ca: 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_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Expected O, but got Unknown //IL_0088: Unknown result type (might be due to invalid IL or missing references) Version bepInExVersion = Paths.BepInExVersion; Version arg = new Version(bepInExVersion.Major, bepInExVersion.Minor, bepInExVersion.Patch, bepInExVersion.PreRelease, (string)null); string text = $"BepInEx {arg} - {Paths.ProcessName}"; log.Log((LogLevel)8, (object)text); if (ConsoleManager.ConsoleActive) { ConsoleManager.SetConsoleTitle(text); } bool flag = default(bool); LogLevel val2; BepInExLogInterpolatedStringHandler val3; if (!string.IsNullOrEmpty(bepInExVersion.Build)) { LogLevel val = (LogLevel)8; val2 = val; val3 = new BepInExLogInterpolatedStringHandler(18, 1, val, ref flag); if (flag) { val3.AppendLiteral("Built from commit "); val3.AppendFormatted<string>(bepInExVersion.Build); } log.Log(val2, val3); } val2 = (LogLevel)16; LogLevel val4 = val2; val3 = new BepInExLogInterpolatedStringHandler(17, 1, val2, ref flag); if (flag) { val3.AppendLiteral("System platform: "); val3.AppendFormatted<string>(GetPlatformString()); } Logger.Log(val4, val3); val2 = (LogLevel)16; LogLevel val5 = val2; val3 = new BepInExLogInterpolatedStringHandler(17, 1, val2, ref flag); if (flag) { val3.AppendLiteral("Process bitness: "); val3.AppendFormatted<string>(PlatformUtils.ProcessIs64Bit ? "64-bit (x64)" : "32-bit (x86)"); } Logger.Log(val5, val3); } private static string GetPlatformString() { StringBuilder stringBuilder = new StringBuilder(); Version version = Environment.OSVersion.Version; if (PlatformHelper.Is((Platform)37)) { version = PlatformUtils.WindowsVersion; stringBuilder.Append("Windows "); if (version.Major >= 10 && version.Build >= 22000) { stringBuilder.Append("11"); } else if (version.Major >= 10) { stringBuilder.Append("10"); } else if (version.Major == 6 && version.Minor == 3) { stringBuilder.Append("8.1"); } else if (version.Major == 6 && version.Minor == 2) { stringBuilder.Append("8"); } else if (version.Major == 6 && version.Minor == 1) { stringBuilder.Append("7"); } else if (version.Major == 6 && version.Minor == 0) { stringBuilder.Append("Vista"); } else if (version.Major <= 5) { stringBuilder.Append("XP"); } if (PlatformHelper.Is((Platform)131072)) { stringBuilder.AppendFormat(" (Wine {0})", PlatformUtils.WineVersion); } } else if (PlatformHelper.Is((Platform)73)) { stringBuilder.Append("macOS "); string key = version.ToString(3); if (MacOSVersions.TryGetValue(key, out var value)) { stringBuilder.Append(value); } else { stringBuilder.AppendFormat("Unknown (kernel {0})", version); } } else if (PlatformHelper.Is((Platform)137)) { stringBuilder.Append("Linux"); if (PlatformUtils.LinuxKernelVersion != null) { stringBuilder.AppendFormat(" (kernel {0})", PlatformUtils.LinuxKernelVersion); } } stringBuilder.Append(PlatformHelper.Is((Platform)2) ? " 64-bit" : " 32-bit"); if (PlatformHelper.Is((Platform)393)) { stringBuilder.Append(" Android"); } if (PlatformHelper.Is((Platform)65536)) { stringBuilder.Append(" ARM"); if (PlatformHelper.Is((Platform)2)) { stringBuilder.Append("64"); } } return stringBuilder.ToString(); } public static void RewritePreloaderLogs() { if (PreloaderConsoleListener.LogEvents == null || PreloaderConsoleListener.LogEvents.Count == 0) { return; } ILogListener val = ((IEnumerable<ILogListener>)Logger.Listeners).FirstOrDefault((Func<ILogListener, bool>)((ILogListener logger) => logger is ConsoleLogListener)); if (val != null) { Logger.Listeners.Remove(val); } foreach (LogEventArgs logEvent in PreloaderConsoleListener.LogEvents) { Logger.InternalLogEvent((object)PreloaderLogger.Log, logEvent); } if (val != null) { Logger.Listeners.Add(val); } } } public class PreloaderConsoleListener : ILogListener, IDisposable { private static readonly ConfigEntry<LogLevel> ConfigConsoleDisplayedLevel = ConfigFile.CoreConfig.Bind<LogLevel>("Logging.Console", "LogLevels", (LogLevel)31, "Which log levels to show in the console output."); public static List<LogEventArgs> LogEvents { get; } = new List<LogEventArgs>(); public LogLevel LogLevelFilter => ConfigConsoleDisplayedLevel.Value; public void LogEvent(object sender, LogEventArgs eventArgs) { LogEvents.Add(eventArgs); } public void Dispose() { } } }
BepInExPack\BepInEx\core\BepInEx.Unity.Common.dll
Decompiled 2 months agousing System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Security; using System.Security.Permissions; using System.Text; using AssetRipper.Primitives; using MonoMod.Utils; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("BepInEx.Unity.Mono.Preloader")] [assembly: InternalsVisibleTo("BepInEx.Unity.Mono")] [assembly: InternalsVisibleTo("BepInEx.Unity.IL2CPP")] [assembly: AssemblyCompany("BepInEx")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © 2022 BepInEx Team")] [assembly: AssemblyDescription("BepInEx common code for Unity games")] [assembly: AssemblyFileVersion("6.0.0.0")] [assembly: AssemblyInformationalVersion("6.0.0-be.697+53625800b86f6c68751445248260edf0b27a71c2")] [assembly: AssemblyProduct("BepInEx.Unity.Common")] [assembly: AssemblyTitle("BepInEx.Unity.Common")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("6.0.0.0")] [module: UnverifiableCode] namespace BepInEx.Unity.Common; public static class UnityInfo { private class ManagerLookup { private readonly string filePath; private readonly int[] lookupOffsets; public ManagerLookup(string filePath, params int[] lookupOffsets) { this.filePath = filePath; this.lookupOffsets = lookupOffsets; } public bool TryLookup(out UnityVersion version) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0087: 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) string path = Path.Combine(GameDataPath, filePath); if (!File.Exists(path)) { version = default(UnityVersion); return false; } using FileStream fileStream = File.OpenRead(path); int[] array = lookupOffsets; foreach (int num in array) { StringBuilder stringBuilder = new StringBuilder(); fileStream.Position = num; byte value; while ((value = (byte)fileStream.ReadByte()) != 0) { stringBuilder.Append((char)value); } try { version = UnityVersion.Parse(stringBuilder.ToString()); return true; } catch (Exception) { } } version = default(UnityVersion); return false; } } private static readonly ManagerLookup[] ManagerVersionLookup = new ManagerLookup[3] { new ManagerLookup("globalgamemanagers", 20, 48), new ManagerLookup("data.unity3d", 18), new ManagerLookup("mainData", 20) }; private static bool initialized; public static string PlayerPath { get; private set; } public static string GameDataPath { get; private set; } public static UnityVersion Version { get; private set; } internal static void Initialize(string unityPlayerPath, string gameDataPath) { if (!initialized) { PlayerPath = Path.GetFullPath(unityPlayerPath ?? throw new ArgumentNullException("unityPlayerPath")); GameDataPath = Path.GetFullPath(gameDataPath ?? throw new ArgumentNullException("gameDataPath")); DetermineVersion(); initialized = true; } } internal static void SetRuntimeUnityVersion(string version) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) Version = UnityVersion.Parse(version); } private static void DetermineVersion() { //IL_009d: 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_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) ManagerLookup[] managerVersionLookup = ManagerVersionLookup; for (int i = 0; i < managerVersionLookup.Length; i++) { if (managerVersionLookup[i].TryLookup(out var version)) { Version = version; return; } } if (PlatformHelper.Is((Platform)37)) { try { Version version2 = new Version(FileVersionInfo.GetVersionInfo(PlayerPath).FileVersion); Version = new UnityVersion((ushort)version2.Major, (ushort)version2.Minor, (ushort)version2.Build); return; } catch (Exception) { } } if (File.Exists(Path.Combine(Path.Combine(GameDataPath, "Managed"), "UnityEngine.CoreModule.dll"))) { Version = new UnityVersion((ushort)2017, (ushort)0, (ushort)0, (UnityVersionType)5); } Version = default(UnityVersion); } }
BepInExPack\BepInEx\core\BepInEx.Unity.Mono.dll
Decompiled 2 months agousing System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading; using AssetRipper.Primitives; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Core.Logging.Interpolation; using BepInEx.Logging; using BepInEx.Preloader.Core.Logging; using BepInEx.Unity.Common; using BepInEx.Unity.Mono.Bootstrap; using BepInEx.Unity.Mono.Logging; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("UnityEngine")] [assembly: InternalsVisibleTo("UnityEngine.Core")] [assembly: AssemblyCompany("BepInEx")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © 2022 BepInEx Team")] [assembly: AssemblyDescription("BepInEx support library for Mono Unity games")] [assembly: AssemblyFileVersion("6.0.0.0")] [assembly: AssemblyInformationalVersion("6.0.0-be.697+53625800b86f6c68751445248260edf0b27a71c2")] [assembly: AssemblyProduct("BepInEx.Unity.Mono")] [assembly: AssemblyTitle("BepInEx.Unity.Mono")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("6.0.0.0")] [module: UnverifiableCode] namespace UnityEngine { internal sealed class UnityLogWriter { [MethodImpl(MethodImplOptions.InternalCall)] public static extern void WriteStringToUnityLogImpl(string s); [MethodImpl(MethodImplOptions.InternalCall)] public static extern void WriteStringToUnityLog(string s); } } namespace BepInEx.Unity.Mono { public abstract class BaseUnityPlugin : MonoBehaviour { public PluginInfo Info { get; } protected ManualLogSource Logger { get; } public ConfigFile Config { get; } protected BaseUnityPlugin() { //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0055: 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_0081: Expected O, but got Unknown //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Expected O, but got Unknown BepInPlugin metadata = MetadataHelper.GetMetadata((object)this); if (metadata == null) { throw new InvalidOperationException("Can't create an instance of " + ((object)this).GetType().FullName + " because it inherits from BaseUnityPlugin and the BepInPlugin attribute is missing."); } Info = new PluginInfo { Metadata = metadata, Instance = this, Dependencies = MetadataHelper.GetDependencies(((object)this).GetType()), Processes = MetadataHelper.GetAttributes<BepInProcess>(((object)this).GetType()), Location = ((object)this).GetType().Assembly.Location }; Logger = Logger.CreateLogSource(metadata.Name); Config = new ConfigFile(Utility.CombinePaths(new string[2] { Paths.ConfigPath, metadata.GUID + ".cfg" }), false, metadata); } } public static class BepInExInstance { public static UnityChainloader Chainloader { get; } } public sealed class ThreadingHelper : MonoBehaviour, ISynchronizeInvoke { private sealed class InvokeResult : IAsyncResult { internal bool ExceptionThrown; public bool IsCompleted { get; private set; } public WaitHandle AsyncWaitHandle { get; } public object AsyncState { get; private set; } public bool CompletedSynchronously { get; private set; } public InvokeResult() { AsyncWaitHandle = new EventWaitHandle(initialState: false, EventResetMode.ManualReset); } public void Finish(object result, bool completedSynchronously) { AsyncState = result; CompletedSynchronously = completedSynchronously; IsCompleted = true; ((EventWaitHandle)AsyncWaitHandle).Set(); } } private readonly object _invokeLock = new object(); private Action _invokeList; private Thread _mainThread; public static ThreadingHelper Instance { get; private set; } public static ISynchronizeInvoke SynchronizingObject => Instance; public bool InvokeRequired { get { if (_mainThread != null) { return _mainThread != Thread.CurrentThread; } return true; } } private void Update() { if (_mainThread == null) { _mainThread = Thread.CurrentThread; } if (_invokeList == null) { return; } Action invokeList; lock (_invokeLock) { invokeList = _invokeList; _invokeList = null; } foreach (Action item in invokeList.GetInvocationList().Cast<Action>()) { try { item(); } catch (Exception ex) { LogInvocationException(ex); } } } internal static void Initialize() { //IL_0005: 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_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Expected O, but got Unknown GameObject val = new GameObject("BepInEx_ThreadingHelper") { hideFlags = (HideFlags)61 }; Object.DontDestroyOnLoad((Object)val); Instance = val.AddComponent<ThreadingHelper>(); } public void StartSyncInvoke(Action action) { if (action == null) { throw new ArgumentNullException("action"); } lock (_invokeLock) { _invokeList = (Action)Delegate.Combine(_invokeList, action); } } public void StartAsyncInvoke(Func<Action> action) { if (!ThreadPool.QueueUserWorkItem(DoWork)) { throw new NotSupportedException("Failed to queue the action on ThreadPool"); } void DoWork(object _) { try { Action action2 = action(); if (action2 != null) { StartSyncInvoke(action2); } } catch (Exception ex) { LogInvocationException(ex); } } } private static void LogInvocationException(Exception ex) { //IL_0010: 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_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Expected O, but got Unknown Logger.Log((LogLevel)2, (object)ex); if (ex.InnerException != null) { LogLevel val = (LogLevel)2; bool flag = default(bool); BepInExLogInterpolatedStringHandler val2 = new BepInExLogInterpolatedStringHandler(7, 1, val, ref flag); if (flag) { val2.AppendLiteral("INNER: "); val2.AppendFormatted<Exception>(ex.InnerException); } Logger.Log(val, val2); } } IAsyncResult ISynchronizeInvoke.BeginInvoke(Delegate method, object[] args) { InvokeResult result = new InvokeResult(); if (!InvokeRequired) { result.Finish(Invoke(), completedSynchronously: true); } else { StartSyncInvoke(delegate { result.Finish(Invoke(), completedSynchronously: false); }); } return result; object Invoke() { try { return method.DynamicInvoke(args); } catch (Exception result2) { result.ExceptionThrown = true; return result2; } } } object ISynchronizeInvoke.EndInvoke(IAsyncResult result) { InvokeResult invokeResult = (InvokeResult)result; invokeResult.AsyncWaitHandle.WaitOne(); if (invokeResult.ExceptionThrown) { throw (Exception)invokeResult.AsyncState; } return invokeResult.AsyncState; } object ISynchronizeInvoke.Invoke(Delegate method, object[] args) { IAsyncResult result = ((ISynchronizeInvoke)this).BeginInvoke(method, args); return ((ISynchronizeInvoke)this).EndInvoke(result); } } public static class ThreadingExtensions { public static IEnumerable<TOut> RunParallel<TIn, TOut>(this IEnumerable<TIn> data, Func<TIn, TOut> work, int workerCount = -1) { foreach (TOut item in data.ToList().RunParallel(work)) { yield return item; } } public static IEnumerable<TOut> RunParallel<TIn, TOut>(this IList<TIn> data, Func<TIn, TOut> work, int workerCount = -1) { if (workerCount < 0) { workerCount = Mathf.Max(2, Environment.ProcessorCount); } else if (workerCount == 0) { throw new ArgumentException("Need at least 1 worker", "workerCount"); } int perThreadCount = Mathf.CeilToInt((float)data.Count / (float)workerCount); int doneCount = 0; object lockObj = new object(); ManualResetEvent are = new ManualResetEvent(initialState: false); IEnumerable<TOut> doneItems = null; Exception exceptionThrown = null; for (int i = 0; i < workerCount; i++) { int first = i * perThreadCount; int last = Mathf.Min(first + perThreadCount, data.Count); ThreadPool.QueueUserWorkItem(delegate { List<TOut> list = new List<TOut>(perThreadCount); try { for (int j = first; j < last; j++) { if (exceptionThrown != null) { break; } list.Add(work(data[j])); } } catch (Exception ex) { exceptionThrown = ex; } lock (lockObj) { IEnumerable<TOut> enumerable2; if (doneItems != null) { enumerable2 = list.Concat(doneItems); } else { IEnumerable<TOut> enumerable3 = list; enumerable2 = enumerable3; } doneItems = enumerable2; int num = doneCount; doneCount = num + 1; are.Set(); } }); } bool isDone; do { are.WaitOne(); IEnumerable<TOut> enumerable; lock (lockObj) { enumerable = doneItems; doneItems = null; isDone = doneCount == workerCount; } if (enumerable == null) { continue; } foreach (TOut item in enumerable) { yield return item; } } while (!isDone); if (exceptionThrown != null) { throw new TargetInvocationException("An exception was thrown inside one of the threads", exceptionThrown); } } public static void ForEachParallel<T>(this IList<T> data, Action<T> work, int workerCount = -1) { if (workerCount < 0) { workerCount = Mathf.Max(2, Environment.ProcessorCount); } else if (workerCount == 0) { throw new ArgumentException("Need at least 1 worker", "workerCount"); } int currentIndex = data.Count; ManualResetEvent are = new ManualResetEvent(initialState: false); int runningCount = workerCount; Exception exceptionThrown = null; for (int i = 0; i < workerCount - 1; i++) { ThreadPool.QueueUserWorkItem(DoWork); } DoWork(null); are.WaitOne(); if (exceptionThrown != null) { throw new TargetInvocationException("An exception was thrown inside one of the threads", exceptionThrown); } void DoWork(object _) { try { while (exceptionThrown == null) { int num = Interlocked.Decrement(ref currentIndex); if (num < 0) { break; } work(data[num]); } } catch (Exception ex) { exceptionThrown = ex; } finally { if (Interlocked.Decrement(ref runningCount) <= 0) { are.Set(); } } } } } internal static class UnityTomlTypeConverters { [MethodImpl(MethodImplOptions.NoInlining)] public static void AddUnityEngineConverters() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Expected O, but got Unknown //IL_0061: 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_008b: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Expected O, but got Unknown TypeConverter val = new TypeConverter { ConvertToString = (object obj, Type type) => ColorUtility.ToHtmlStringRGBA((Color)obj), ConvertToObject = delegate(string str, Type type) { //IL_0034: Unknown result type (might be due to invalid IL or missing references) Color val3 = default(Color); if (!ColorUtility.TryParseHtmlString("#" + str.Trim('#', ' '), ref val3)) { throw new FormatException("Invalid color string, expected hex #RRGGBBAA"); } return val3; } }; TomlTypeConverter.AddConverter(typeof(Color), val); TypeConverter val2 = new TypeConverter { ConvertToString = (object obj, Type type) => JsonUtility.ToJson(obj), ConvertToObject = (string str, Type type) => JsonUtility.FromJson(str, type) }; TomlTypeConverter.AddConverter(typeof(Vector2), val2); TomlTypeConverter.AddConverter(typeof(Vector3), val2); TomlTypeConverter.AddConverter(typeof(Vector4), val2); TomlTypeConverter.AddConverter(typeof(Quaternion), val2); } } } namespace BepInEx.Unity.Mono.Logging { public class UnityLogListener : ILogListener, IDisposable { internal static readonly Action<string> WriteStringToUnityLog; protected static readonly ConfigEntry<LogLevel> ConfigUnityLogLevel; private readonly ConfigEntry<bool> LogConsoleToUnity = ConfigFile.CoreConfig.Bind<bool>("Logging", "LogConsoleToUnityLog", false, new StringBuilder().AppendLine("If enabled, writes Standard Output messages to Unity log").AppendLine("NOTE: By default, Unity does so automatically. Only use this option if no console messages are visible in Unity log").ToString()); public LogLevel LogLevelFilter => ConfigUnityLogLevel.Value; static UnityLogListener() { ConfigUnityLogLevel = ConfigFile.CoreConfig.Bind<LogLevel>("Logging.Unity", "LogLevels", (LogLevel)31, "What log levels to log to Unity's output log."); MethodInfo[] methods = typeof(UnityLogWriter).GetMethods(BindingFlags.Static | BindingFlags.Public); foreach (MethodInfo methodInfo in methods) { try { methodInfo.Invoke(null, new object[1] { "" }); } catch { continue; } WriteStringToUnityLog = (Action<string>)Delegate.CreateDelegate(typeof(Action<string>), methodInfo); break; } if (WriteStringToUnityLog == null) { Logger.Log((LogLevel)2, (object)"Unable to start Unity log writer"); } } public void LogEvent(object sender, LogEventArgs eventArgs) { if (!(eventArgs.Source is UnityLogSource) && (LogConsoleToUnity.Value || eventArgs.Source.SourceName != "Console")) { WriteStringToUnityLog?.Invoke(eventArgs.ToStringLine()); } } public void Dispose() { } } public class UnityLogSource : ILogSource, IDisposable { private bool disposed; public string SourceName { get; } = "Unity Log"; public event EventHandler<LogEventArgs> LogEvent; private static event EventHandler<LogEventArgs> InternalUnityLogMessage; public UnityLogSource() { InternalUnityLogMessage += UnityLogMessageHandler; } public void Dispose() { if (!disposed) { InternalUnityLogMessage -= UnityLogMessageHandler; disposed = true; } } private void UnityLogMessageHandler(object sender, LogEventArgs eventArgs) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Expected O, but got Unknown LogEventArgs e = new LogEventArgs(eventArgs.Data, eventArgs.Level, (ILogSource)(object)this); this.LogEvent?.Invoke(this, e); } static UnityLogSource() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Expected O, but got Unknown LogCallback val = new LogCallback(OnUnityLogMessageReceived); EventInfo eventInfo = typeof(Application).GetEvent("logMessageReceived", BindingFlags.Static | BindingFlags.Public); if ((object)eventInfo != null) { eventInfo.AddEventHandler(null, (Delegate?)(object)val); return; } typeof(Application).GetMethod("RegisterLogCallback", BindingFlags.Static | BindingFlags.Public).Invoke(null, new object[1] { val }); } private static void OnUnityLogMessageReceived(string message, string stackTrace, LogType type) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Expected I4, but got Unknown //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Invalid comparison between Unknown and I4 //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Expected O, but got Unknown LogLevel val; switch ((int)type) { case 0: case 1: case 4: val = (LogLevel)2; break; case 2: val = (LogLevel)4; break; default: val = (LogLevel)16; break; } if ((int)type == 4) { message = message + "\nStack trace:\n" + stackTrace; } UnityLogSource.InternalUnityLogMessage?.Invoke(null, new LogEventArgs((object)message, val, (ILogSource)null)); } } } namespace BepInEx.Unity.Mono.Configuration { public struct KeyboardShortcut { public static readonly KeyboardShortcut Empty; public static readonly IEnumerable<KeyCode> AllKeyCodes; private static readonly KeyCode[] _modifierBlockKeyCodes; private readonly KeyCode[] _allKeys; public KeyCode MainKey { get { if (_allKeys != null && _allKeys.Length != 0) { return _allKeys[0]; } return (KeyCode)0; } } public IEnumerable<KeyCode> Modifiers => _allKeys?.Skip(1) ?? Enumerable.Empty<KeyCode>(); static KeyboardShortcut() { //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) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Expected O, but got Unknown Empty = default(KeyboardShortcut); AllKeyCodes = (KeyCode[])Enum.GetValues(typeof(KeyCode)); _modifierBlockKeyCodes = AllKeyCodes.Except((IEnumerable<KeyCode>)(object)new KeyCode[8] { (KeyCode)323, (KeyCode)324, (KeyCode)325, (KeyCode)326, (KeyCode)327, (KeyCode)328, (KeyCode)329, default(KeyCode) }).ToArray(); TomlTypeConverter.AddConverter(typeof(KeyboardShortcut), new TypeConverter { ConvertToString = (object o, Type type) => ((KeyboardShortcut)o).Serialize(), ConvertToObject = (string s, Type type) => Deserialize(s) }); } public KeyboardShortcut(KeyCode mainKey, params KeyCode[] modifiers) : this(((IEnumerable<KeyCode>)(object)new KeyCode[1] { (KeyCode)(int)mainKey }).Concat(modifiers).ToArray()) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected I4, but got Unknown //IL_001b: Unknown result type (might be due to invalid IL or missing references) if ((int)mainKey == 0 && modifiers.Any()) { throw new ArgumentException("Can't set mainKey to KeyCode.None if there are any modifiers"); } } private KeyboardShortcut(KeyCode[] keys) { _allKeys = SanitizeKeys(keys); } private static KeyCode[] SanitizeKeys(params KeyCode[] keys) { if (keys.Length == 0 || (int)keys[0] == 0) { return (KeyCode[])(object)new KeyCode[1]; } return ((IEnumerable<KeyCode>)(object)new KeyCode[1] { keys[0] }).Concat(from x in keys.Skip(1).Distinct() where (int)x != (int)keys[0] orderby (int)x select x).ToArray(); } public static KeyboardShortcut Deserialize(string str) { try { return new KeyboardShortcut(((IEnumerable<string>)str.Split(new char[5] { ' ', '+', ',', ';', '|' }, StringSplitOptions.RemoveEmptyEntries)).Select((Func<string, KeyCode>)((string x) => (KeyCode)Enum.Parse(typeof(KeyCode), x))).ToArray()); } catch (SystemException ex) { Logger.Log((LogLevel)2, (object)("Failed to read keybind from settings: " + ex.Message)); return Empty; } } public unsafe string Serialize() { if (_allKeys == null) { return string.Empty; } return string.Join(" + ", _allKeys.Select((KeyCode x) => ((object)(*(KeyCode*)(&x))/*cast due to .constrained prefix*/).ToString()).ToArray()); } public bool IsDown() { //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_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) KeyCode mainKey = MainKey; if ((int)mainKey == 0) { return false; } if (Input.GetKeyDown(mainKey)) { return ModifierKeyTest(); } return false; } public bool IsPressed() { //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_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) KeyCode mainKey = MainKey; if ((int)mainKey == 0) { return false; } if (Input.GetKey(mainKey)) { return ModifierKeyTest(); } return false; } public bool IsUp() { //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_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) KeyCode mainKey = MainKey; if ((int)mainKey == 0) { return false; } if (Input.GetKeyUp(mainKey)) { return ModifierKeyTest(); } return false; } private bool ModifierKeyTest() { //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) KeyCode[] allKeys = _allKeys; KeyCode mainKey = MainKey; if (!allKeys.All((KeyCode c) => c == mainKey || Input.GetKey(c))) { return false; } return _modifierBlockKeyCodes.All((KeyCode c) => !Input.GetKey(c) || allKeys.Contains(c)); } public unsafe override string ToString() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) if ((int)MainKey == 0) { return "Not set"; } return string.Join(" + ", _allKeys.Select((KeyCode c) => ((object)(*(KeyCode*)(&c))/*cast due to .constrained prefix*/).ToString()).ToArray()); } public override bool Equals(object obj) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (obj is KeyboardShortcut keyboardShortcut && MainKey == keyboardShortcut.MainKey) { return Modifiers.SequenceEqual(keyboardShortcut.Modifiers); } return false; } public override int GetHashCode() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) if ((int)MainKey == 0) { return 0; } return _allKeys.Aggregate(_allKeys.Length, (int current, KeyCode item) => current * 31 + item); } } } namespace BepInEx.Unity.Mono.Bootstrap { public class UnityChainloader : BaseChainloader<BaseUnityPlugin> { private static readonly ConfigEntry<bool> ConfigUnityLogging = ConfigFile.CoreConfig.Bind<bool>("Logging", "UnityLogListening", true, "Enables showing unity log messages in the BepInEx logging system."); private static readonly ConfigEntry<bool> ConfigDiskWriteUnityLog = ConfigFile.CoreConfig.Bind<bool>("Logging.Disk", "WriteUnityLog", false, "Include unity log messages in log file output."); private static readonly bool staticStartHasBeenCalled = false; private string _consoleTitle; public static UnityChainloader Instance { get; set; } public static GameObject ManagerObject { get; private set; } protected override string ConsoleTitle => _consoleTitle; private static string UnityVersion { [MethodImpl(MethodImplOptions.NoInlining)] get { return Application.unityVersion; } } [Obsolete("This method is public due to a limitation with Unity 4.x. DO NOT CALL", true)] public static void StaticStart(string gameExePath = null) { //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_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Expected O, but got Unknown try { if (staticStartHasBeenCalled) { throw new InvalidOperationException("Cannot call StaticStart again"); } Logger.Log((LogLevel)32, (object)"Entering chainloader StaticStart"); UnityChainloader unityChainloader = new UnityChainloader(); ((BaseChainloader<BaseUnityPlugin>)unityChainloader).Initialize(gameExePath); ((BaseChainloader<BaseUnityPlugin>)unityChainloader).Execute(); Logger.Log((LogLevel)32, (object)"Exiting chainloader StaticStart"); } catch (Exception ex) { LogLevel val = (LogLevel)1; bool flag = default(bool); BepInExLogInterpolatedStringHandler val2 = new BepInExLogInterpolatedStringHandler(44, 1, val, ref flag); if (flag) { val2.AppendLiteral("Unable to complete chainloader StaticStart: "); val2.AppendFormatted<string>(ex.Message); } Logger.Log(val, val2); Logger.Log((LogLevel)1, (object)ex.StackTrace); } } public override void Initialize(string gameExePath = null) { //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_004b: Expected O, but got Unknown //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: 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_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Expected O, but got Unknown try { Logger.Log((LogLevel)32, (object)"Entering chainloader initialize"); Instance = this; UnityTomlTypeConverters.AddUnityEngineConverters(); Logger.Log((LogLevel)32, (object)"Initializing ThreadingHelper"); ThreadingHelper.Initialize(); Logger.Log((LogLevel)32, (object)"Creating Manager object"); ManagerObject = new GameObject("BepInEx_Manager") { hideFlags = (HideFlags)61 }; Object.DontDestroyOnLoad((Object)(object)ManagerObject); Logger.Log((LogLevel)32, (object)"Getting game product name"); PropertyInfo property = typeof(Application).GetProperty("productName", BindingFlags.Static | BindingFlags.Public); _consoleTitle = $"{BaseChainloader<BaseUnityPlugin>.CurrentAssemblyName} {BaseChainloader<BaseUnityPlugin>.CurrentAssemblyVersion} - {property?.GetValue(null, null) ?? Path.GetFileNameWithoutExtension(Process.GetCurrentProcess().ProcessName)}"; Logger.Log((LogLevel)32, (object)"Falling back to BaseChainloader initializer"); base.Initialize(gameExePath); Logger.Log((LogLevel)32, (object)"Exiting chainloader initialize"); } catch (Exception ex) { LogLevel val = (LogLevel)1; bool flag = default(bool); BepInExLogInterpolatedStringHandler val2 = new BepInExLogInterpolatedStringHandler(37, 1, val, ref flag); if (flag) { val2.AppendLiteral("Unable to complete chainloader init: "); val2.AppendFormatted<string>(ex.Message); } Logger.Log(val, val2); Logger.Log((LogLevel)1, (object)ex.StackTrace); } } protected override void InitializeLoggers() { //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_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Expected O, but got Unknown //IL_0051: Unknown result type (might be due to invalid IL or missing references) base.InitializeLoggers(); Logger.Listeners.Add((ILogListener)(object)new UnityLogListener()); UnityVersion version = UnityInfo.Version; UnityInfo.SetRuntimeUnityVersion(UnityVersion); if (UnityInfo.Version != version) { LogLevel val = (LogLevel)16; bool flag = default(bool); BepInExLogInterpolatedStringHandler val2 = new BepInExLogInterpolatedStringHandler(21, 1, val, ref flag); if (flag) { val2.AppendLiteral("UnityPlayer version: "); val2.AppendFormatted<UnityVersion>(UnityInfo.Version); } Logger.Log(val, val2); } if (!ConfigDiskWriteUnityLog.Value) { DiskLogListener.BlacklistedSources.Add("Unity Log"); } ChainloaderLogHelper.RewritePreloaderLogs(); if (ConfigUnityLogging.Value) { Logger.Sources.Add((ILogSource)(object)new UnityLogSource()); } } public override BaseUnityPlugin LoadPlugin(PluginInfo pluginInfo, Assembly pluginAssembly) { return (BaseUnityPlugin)(object)ManagerObject.AddComponent(pluginAssembly.GetType(pluginInfo.TypeName)); } } }
BepInExPack\BepInEx\core\BepInEx.Unity.Mono.Preloader.dll
Decompiled 2 months agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using AssetRipper.Primitives; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Core.Logging.Interpolation; using BepInEx.Logging; using BepInEx.Preloader.Core; using BepInEx.Preloader.Core.Logging; using BepInEx.Preloader.Core.Patching; using BepInEx.Preloader.RuntimeFixes; using BepInEx.Unity.Common; using BepInEx.Unity.Mono.Preloader.RuntimeFixes; using BepInEx.Unity.Mono.Preloader.Utils; using HarmonyLib; using Microsoft.CodeAnalysis; using Mono.Cecil; using Mono.Cecil.Cil; using MonoMod.RuntimeDetour; using MonoMod.RuntimeDetour.Platforms; using MonoMod.Utils; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyCompany("BepInEx")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright © 2022 BepInEx Team")] [assembly: AssemblyDescription("BepInEx preloader module for UnityMono games")] [assembly: AssemblyFileVersion("6.0.0.0")] [assembly: AssemblyInformationalVersion("6.0.0-be.697+53625800b86f6c68751445248260edf0b27a71c2")] [assembly: AssemblyProduct("BepInEx.Unity.Mono.Preloader")] [assembly: AssemblyTitle("BepInEx.Unity.Mono.Preloader")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("6.0.0.0")] [module: UnverifiableCode] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NativeIntegerAttribute : Attribute { public readonly bool[] TransformFlags; public NativeIntegerAttribute() { TransformFlags = new bool[1] { true }; } public NativeIntegerAttribute(bool[] P_0) { TransformFlags = P_0; } } } namespace BepInEx.Unity.Mono.Preloader { [PatcherPluginInfo("io.bepinex.entrypointpatcher", "BepInEx Entrypoint", "1.0")] internal class EntrypointPatcher : BasePatcher { private static readonly ConfigEntry<string> ConfigEntrypointAssembly = ConfigFile.CoreConfig.Bind<string>("Preloader.Entrypoint", "Assembly", DefaultEntrypointAssembly, "The local filename of the assembly to target."); private static readonly ConfigEntry<string> ConfigEntrypointType = ConfigFile.CoreConfig.Bind<string>("Preloader.Entrypoint", "Type", DefaultEntrypointType, "The name of the type in the entrypoint assembly to search for the entrypoint method."); private static readonly ConfigEntry<string> ConfigEntrypointMethod = ConfigFile.CoreConfig.Bind<string>("Preloader.Entrypoint", "Method", ".cctor", "The name of the method in the specified entrypoint assembly and type to hook and load Chainloader from."); private static string DefaultEntrypointAssembly { get { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) UnityVersion version = UnityInfo.Version; if (!((UnityVersion)(ref version)).LessThan((ushort)2017)) { return "UnityEngine.CoreModule.dll"; } return "UnityEngine.dll"; } } private static string DefaultEntrypointType { get { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) UnityVersion version = UnityInfo.Version; if (!((UnityVersion)(ref version)).LessThan((ushort)5)) { return "Application"; } return "MonoBehaviour"; } } private bool HasLoaded { get; set; } [TargetAssembly("_all")] public bool PatchEntrypoint(ref AssemblyDefinition assembly, string filename) { //IL_0087: 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_008b: 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_0094: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Expected O, but got Unknown //IL_00d1: 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_013b: Unknown result type (might be due to invalid IL or missing references) //IL_0147: Expected O, but got Unknown //IL_0217: Unknown result type (might be due to invalid IL or missing references) //IL_021e: Expected O, but got Unknown //IL_0238: Unknown result type (might be due to invalid IL or missing references) //IL_02bb: Unknown result type (might be due to invalid IL or missing references) //IL_02d0: Unknown result type (might be due to invalid IL or missing references) if (HasLoaded || filename != ConfigEntrypointAssembly.Value) { return false; } if (((IEnumerable<AssemblyNameReference>)assembly.MainModule.AssemblyReferences).Any((AssemblyNameReference x) => x.Name.Contains("BepInEx"))) { throw new Exception("BepInEx has been detected to be patched! Please unpatch before using a patchless variant!"); } string entrypointType = ConfigEntrypointType.Value; string entrypointMethod = ConfigEntrypointMethod.Value; ManualLogSource log = ((BasePatcher)this).Log; LogLevel val = (LogLevel)32; LogLevel val2 = val; bool flag = default(bool); BepInExLogInterpolatedStringHandler val3 = new BepInExLogInterpolatedStringHandler(27, 2, val, ref flag); if (flag) { val3.AppendLiteral("Hooking chainloader into "); val3.AppendFormatted<string>(entrypointType); val3.AppendLiteral("::"); val3.AppendFormatted<string>(entrypointMethod); } log.Log(val2, val3); bool flag2 = Utility.IsNullOrWhiteSpace(entrypointMethod) || entrypointMethod == ".cctor"; TypeDefinition val4 = ((IEnumerable<TypeDefinition>)assembly.MainModule.Types).FirstOrDefault((Func<TypeDefinition, bool>)((TypeDefinition x) => ((MemberReference)x).Name == entrypointType)); if (val4 == null) { throw new Exception("The entrypoint type is invalid! Please check your config/BepInEx.cfg file"); } string text = Path.Combine(Paths.BepInExAssemblyDirectory, "BepInEx.Unity.Mono.dll"); ReaderParameters val5 = new ReaderParameters { AssemblyResolver = (IAssemblyResolver)(object)TypeLoader.CecilResolver }; AssemblyDefinition val6 = AssemblyDefinition.ReadAssembly(text, val5); try { MethodDefinition val7 = Utility.EnumerateAllMethods(((IEnumerable<TypeDefinition>)val6.MainModule.Types).First((TypeDefinition x) => ((MemberReference)x).Name == "UnityChainloader")).First((MethodDefinition x) => ((MemberReference)x).Name == "StaticStart"); MethodReference val8 = assembly.MainModule.ImportReference((MethodReference)(object)val7); List<MethodDefinition> list = new List<MethodDefinition>(); if (flag2) { MethodDefinition val9 = ((IEnumerable<MethodDefinition>)val4.Methods).FirstOrDefault((Func<MethodDefinition, bool>)((MethodDefinition m) => m.IsConstructor && m.IsStatic)); if (val9 == null) { val9 = new MethodDefinition(".cctor", (MethodAttributes)6289, assembly.MainModule.ImportReference(typeof(void))); val4.Methods.Add(val9); ILProcessor iLProcessor = val9.Body.GetILProcessor(); iLProcessor.Append(iLProcessor.Create(OpCodes.Ret)); } list.Add(val9); } else { list.AddRange(((IEnumerable<MethodDefinition>)val4.Methods).Where((MethodDefinition x) => ((MemberReference)x).Name == entrypointMethod)); } if (!list.Any()) { throw new Exception("The entrypoint method is invalid! Please check your config.ini"); } foreach (MethodDefinition item in list) { ILProcessor iLProcessor2 = item.Body.GetILProcessor(); Instruction val10 = ((IEnumerable<Instruction>)iLProcessor2.Body.Instructions).First(); iLProcessor2.InsertBefore(val10, iLProcessor2.Create(OpCodes.Ldnull)); iLProcessor2.InsertBefore(val10, iLProcessor2.Create(OpCodes.Call, val8)); } } finally { ((IDisposable)val6)?.Dispose(); } HasLoaded = true; return true; } public override void Finalizer() { //IL_000f: 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_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown //IL_004a: Unknown result type (might be due to invalid IL or missing references) if (!HasLoaded) { ManualLogSource log = ((BasePatcher)this).Log; LogLevel val = (LogLevel)1; LogLevel val2 = val; bool flag = default(bool); BepInExLogInterpolatedStringHandler val3 = new BepInExLogInterpolatedStringHandler(128, 1, val, ref flag); if (flag) { val3.AppendLiteral("Failed to patch BepInEx chainloader into assembly '"); val3.AppendFormatted<string>(ConfigEntrypointAssembly.Value); val3.AppendLiteral("', either due to error or not being able to find it. Is it spelled correctly?"); } log.Log(val2, val3); } } } internal static class UnityPreloader { internal static readonly ConfigEntry<bool> ConfigApplyRuntimePatches = ConfigFile.CoreConfig.Bind<bool>("Preloader", "ApplyRuntimePatches", true, "Enables or disables runtime patches.\nThis should always be true, unless you cannot start the game due to a Harmony related issue (such as running .NET Standard runtime) or you know what you're doing."); private static PreloaderConsoleListener PreloaderLog { get; set; } private static ManualLogSource Log => PreloaderLogger.Log; public static void Run() { //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Expected O, but got Unknown //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Expected O, but got Unknown //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_0091: 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_0098: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Expected O, but got Unknown //IL_00b8: 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_00c8: 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_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Expected O, but got Unknown //IL_00ae: 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_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0103: 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_010c: Expected O, but got Unknown //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_0134: Unknown result type (might be due to invalid IL or missing references) //IL_0135: 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_013a: 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_0143: Expected O, but got Unknown //IL_015d: Unknown result type (might be due to invalid IL or missing references) //IL_016b: Unknown result type (might be due to invalid IL or missing references) //IL_016c: Unknown result type (might be due to invalid IL or missing references) //IL_016d: Unknown result type (might be due to invalid IL or missing references) //IL_0171: Unknown result type (might be due to invalid IL or missing references) //IL_0174: Unknown result type (might be due to invalid IL or missing references) //IL_017a: Expected O, but got Unknown //IL_0194: Unknown result type (might be due to invalid IL or missing references) //IL_01a2: Unknown result type (might be due to invalid IL or missing references) //IL_01a3: 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_01a8: Unknown result type (might be due to invalid IL or missing references) //IL_01ab: Unknown result type (might be due to invalid IL or missing references) //IL_01b1: Expected O, but got Unknown //IL_01cb: Unknown result type (might be due to invalid IL or missing references) //IL_0237: Unknown result type (might be due to invalid IL or missing references) //IL_023e: Expected O, but got Unknown //IL_01db: Unknown result type (might be due to invalid IL or missing references) //IL_01dc: Unknown result type (might be due to invalid IL or missing references) //IL_01dd: Unknown result type (might be due to invalid IL or missing references) //IL_01e1: Unknown result type (might be due to invalid IL or missing references) //IL_01e4: Unknown result type (might be due to invalid IL or missing references) //IL_01ea: Expected O, but got Unknown //IL_025d: Unknown result type (might be due to invalid IL or missing references) //IL_025e: Unknown result type (might be due to invalid IL or missing references) //IL_025f: Unknown result type (might be due to invalid IL or missing references) //IL_0263: Unknown result type (might be due to invalid IL or missing references) //IL_0266: Unknown result type (might be due to invalid IL or missing references) //IL_026c: Expected O, but got Unknown //IL_0205: Unknown result type (might be due to invalid IL or missing references) //IL_02c3: 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_02de: 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_02e3: Unknown result type (might be due to invalid IL or missing references) //IL_02e6: Unknown result type (might be due to invalid IL or missing references) //IL_02ec: Expected O, but got Unknown //IL_0312: Unknown result type (might be due to invalid IL or missing references) try { HarmonyBackendFix.Initialize(); UnityInfo.Initialize(Paths.ExecutablePath, Paths.GameDataPath); ConsoleManager.Initialize(false, false); AllocateConsole(); Exception ex = default(Exception); Utility.TryDo((Action)delegate { if (ConfigApplyRuntimePatches.Value) { UnityPatches.Apply(); } }, ref ex); Logger.Sources.Add((ILogSource)new HarmonyLogSource()); Logger.Sources.Add(TraceLogSource.CreateSource()); PreloaderLog = new PreloaderConsoleListener(); Logger.Listeners.Add((ILogListener)(object)PreloaderLog); ChainloaderLogHelper.PrintLogInfo(Log); ManualLogSource log = Log; LogLevel val = (LogLevel)16; LogLevel val2 = val; bool flag = default(bool); BepInExLogInterpolatedStringHandler val3 = new BepInExLogInterpolatedStringHandler(20, 1, val, ref flag); if (flag) { val3.AppendLiteral("Running under Unity "); val3.AppendFormatted<UnityVersion>(UnityInfo.Version); } log.Log(val2, val3); ManualLogSource log2 = Log; val2 = (LogLevel)16; val = val2; val3 = new BepInExLogInterpolatedStringHandler(21, 1, val2, ref flag); if (flag) { val3.AppendLiteral("CLR runtime version: "); val3.AppendFormatted<Version>(Environment.Version); } log2.Log(val, val3); ManualLogSource log3 = Log; val = (LogLevel)16; val2 = val; val3 = new BepInExLogInterpolatedStringHandler(14, 1, val, ref flag); if (flag) { val3.AppendLiteral("Supports SRE: "); val3.AppendFormatted<bool>(Utility.CLRSupportsDynamicAssemblies); } log3.Log(val2, val3); ManualLogSource log4 = Log; val2 = (LogLevel)32; val = val2; val3 = new BepInExLogInterpolatedStringHandler(22, 1, val2, ref flag); if (flag) { val3.AppendLiteral("Game executable path: "); val3.AppendFormatted<string>(Paths.ExecutablePath); } log4.Log(val, val3); ManualLogSource log5 = Log; val = (LogLevel)32; val2 = val; val3 = new BepInExLogInterpolatedStringHandler(25, 1, val, ref flag); if (flag) { val3.AppendLiteral("Unity Managed directory: "); val3.AppendFormatted<string>(Paths.ManagedPath); } log5.Log(val2, val3); ManualLogSource log6 = Log; val2 = (LogLevel)32; val = val2; val3 = new BepInExLogInterpolatedStringHandler(19, 1, val2, ref flag); if (flag) { val3.AppendLiteral("BepInEx root path: "); val3.AppendFormatted<string>(Paths.BepInExRootPath); } log6.Log(val, val3); if (ex != null) { ManualLogSource log7 = Log; val = (LogLevel)4; val2 = val; val3 = new BepInExLogInterpolatedStringHandler(90, 1, val, ref flag); if (flag) { val3.AppendLiteral("Failed to apply runtime patches for Mono. See more info in the output log. Error message: "); val3.AppendFormatted<string>(ex.Message); } log7.Log(val2, val3); } Log.Log((LogLevel)8, (object)"Preloader started"); TypeLoader.SearchDirectories.UnionWith(Paths.DllSearchPaths); AssemblyPatcher val4 = new AssemblyPatcher((Func<byte[], string, Assembly>)MonoAssemblyHelper.LoadFromMemory); try { val4.AddPatchersFromDirectory(Paths.BepInExAssemblyDirectory); val4.AddPatchersFromDirectory(Paths.PatcherPluginPath); ManualLogSource log8 = Log; val2 = (LogLevel)16; val = val2; val3 = new BepInExLogInterpolatedStringHandler(22, 2, val2, ref flag); if (flag) { val3.AppendFormatted<int>(val4.PatcherContext.PatcherPlugins.Count); val3.AppendLiteral(" patcher plugin"); val3.AppendFormatted<string>((val4.PatcherContext.PatcherPlugins.Count == 1) ? "" : "s"); val3.AppendLiteral(" loaded"); } log8.Log(val, val3); val4.LoadAssemblyDirectories(Paths.DllSearchPaths); ManualLogSource log9 = Log; val = (LogLevel)16; val2 = val; val3 = new BepInExLogInterpolatedStringHandler(22, 1, val, ref flag); if (flag) { val3.AppendFormatted<int>(val4.PatcherContext.AvailableAssemblies.Count); val3.AppendLiteral(" assemblies discovered"); } log9.Log(val2, val3); val4.PatchAndLoad(); } finally { ((IDisposable)val4)?.Dispose(); } Log.Log((LogLevel)8, (object)"Preloader finished"); Logger.Listeners.Remove((ILogListener)(object)PreloaderLog); PreloaderLog.Dispose(); } catch (Exception ex2) { try { Log.Log((LogLevel)1, (object)"Could not run preloader!"); Log.Log((LogLevel)1, (object)ex2); if (!ConsoleManager.ConsoleActive) { AllocateConsole(); Console.Write(PreloaderLog); } } catch { } string text = string.Empty; try { text = string.Join("\r\n", PreloaderConsoleListener.LogEvents.Select((LogEventArgs x) => ((object)x).ToString()).ToArray()); text += "\r\n"; PreloaderConsoleListener preloaderLog = PreloaderLog; if (preloaderLog != null) { preloaderLog.Dispose(); } PreloaderLog = null; } catch { } File.WriteAllText(Path.Combine(Paths.GameRootPath, $"preloader_{DateTime.Now:yyyyMMdd_HHmmss_fff}.log"), text + ex2); } } public static void AllocateConsole() { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Expected O, but got Unknown if (!ConsoleManager.ConsoleEnabled) { return; } try { ConsoleManager.CreateConsole(); Logger.Listeners.Add((ILogListener)new ConsoleLogListener()); } catch (Exception ex) { Log.LogError((object)"Failed to allocate console!"); Log.LogError((object)ex); } } } internal static class UnityPreloaderRunner { private static readonly string[] CriticalAssemblies = new string[4] { "Mono.Cecil.dll", "Mono.Cecil.Mdb.dll", "Mono.Cecil.Pdb.dll", "Mono.Cecil.Rocks.dll" }; private static void LoadCriticalAssemblies() { string[] criticalAssemblies = CriticalAssemblies; foreach (string path in criticalAssemblies) { try { MonoAssemblyHelper.Load(Path.Combine(Paths.BepInExAssemblyDirectory, path)); } catch (Exception) { } } } public static void PreloaderPreMain() { PlatformUtils.SetPlatform(); string text = Utility.ParentDirectory(Path.GetFullPath(EnvVars.DOORSTOP_INVOKE_DLL_PATH), 2); Paths.SetExecutablePath(EnvVars.DOORSTOP_PROCESS_PATH, text, EnvVars.DOORSTOP_MANAGED_FOLDER_DIR, true, EnvVars.DOORSTOP_DLL_SEARCH_DIRS); LoadCriticalAssemblies(); AppDomain.CurrentDomain.AssemblyResolve += LocalResolve; PreloaderMain(); } private static void PreloaderMain() { if (UnityPreloader.ConfigApplyRuntimePatches.Value) { XTermFix.Apply(); ConsoleSetOutFix.Apply(); } UnityPreloader.Run(); } private static Assembly LocalResolve(object sender, ResolveEventArgs args) { AssemblyName assemblyName = default(AssemblyName); if (!Utility.TryParseAssemblyName(args.Name, ref assemblyName)) { return null; } AssemblyName assemblyName2 = default(AssemblyName); var source = (from a in AppDomain.CurrentDomain.GetAssemblies() select new { assembly = a, name = (Utility.TryParseAssemblyName(a.FullName, ref assemblyName2) ? assemblyName2 : null) } into a where a.name != null && a.name.Name == assemblyName.Name orderby a.name.Version descending select a).ToList(); Assembly assembly = (source.FirstOrDefault(a => a.name.Version == assemblyName.Version) ?? source.FirstOrDefault())?.assembly; if ((object)assembly != null) { return assembly; } if (MonoAssemblyHelper.TryResolveDllAssembly(assemblyName, Paths.BepInExAssemblyDirectory, out assembly) || MonoAssemblyHelper.TryResolveDllAssembly(assemblyName, Paths.PatcherPluginPath, out assembly) || MonoAssemblyHelper.TryResolveDllAssembly(assemblyName, Paths.PluginPath, out assembly)) { return assembly; } return null; } } } namespace BepInEx.Unity.Mono.Preloader.Utils { internal static class MonoAssemblyHelper { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate nint ImageOpenDelegate(nint data, uint dataLength, bool needCopy, out MonoImageOpenStatus status, bool refOnly, [MarshalAs(UnmanagedType.LPStr)] string name); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate nint AssemblyLoadDelegate(nint image, [MarshalAs(UnmanagedType.LPStr)] string fileName, out MonoImageOpenStatus status, bool refOnly); private enum MonoImageOpenStatus { MONO_IMAGE_OK, MONO_IMAGE_ERROR_ERRNO, MONO_IMAGE_MISSING_ASSEMBLYREF, MONO_IMAGE_IMAGE_INVALID } private class ReadAssemblyResult { public byte[] AssemblyData; public string AssemblyName; public unsafe Assembly Load(string fullPath) { Assembly assemblyByName = GetAssemblyByName(AssemblyName); if ((object)assemblyByName != null) { return assemblyByName; } fixed (byte* data = &AssemblyData[0]) { MonoImageOpenStatus status; nint image = imageOpen((nint)data, (uint)AssemblyData.Length, needCopy: true, out status, refOnly: false, fullPath); if (status != MonoImageOpenStatus.MONO_IMAGE_OK) { throw new BadImageFormatException($"Failed to load image {fullPath}: {status}"); } assemblyLoad(image, fullPath, out status, refOnly: false); if (status != MonoImageOpenStatus.MONO_IMAGE_OK) { throw new BadImageFormatException($"Failed to load assembly {fullPath}: {status}"); } return GetAssemblyByName(AssemblyName); } } } [DynDllImport("mono", new string[] { "mono_image_open_from_data_with_name" })] private static ImageOpenDelegate imageOpen; [DynDllImport("mono", new string[] { "mono_assembly_load_from_full" })] private static AssemblyLoadDelegate assemblyLoad; static MonoAssemblyHelper() { DynDll.ResolveDynDllImports(typeof(MonoAssemblyHelper), new Dictionary<string, List<DynDllMapping>> { ["mono"] = new List<DynDllMapping> { DynDllMapping.op_Implicit(EnvVars.DOORSTOP_MONO_LIB_PATH) } }); } private static ReadAssemblyResult ReadAssemblyData(string filePath) { return ReadAssemblyData(File.ReadAllBytes(filePath)); } private static ReadAssemblyResult ReadAssemblyData(byte[] assemblyData) { using MemoryStream memoryStream = new MemoryStream(assemblyData); AssemblyDefinition val = AssemblyDefinition.ReadAssembly((Stream)memoryStream); try { return new ReadAssemblyResult { AssemblyName = ((AssemblyNameReference)val.Name).Name, AssemblyData = assemblyData }; } finally { ((IDisposable)val)?.Dispose(); } } private static Assembly GetAssemblyByName(string assemblyName) { AssemblyName assemblyName2 = default(AssemblyName); return AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault((Assembly a) => Utility.TryParseAssemblyName(a.FullName, ref assemblyName2) && assemblyName2.Name == assemblyName); } public static bool TryResolveDllAssembly(AssemblyName assemblyName, string directory, out Assembly assembly) { return Utility.TryResolveDllAssembly<Assembly>(assemblyName, directory, (Func<string, Assembly>)Load, ref assembly); } public static Assembly LoadFromMemory(byte[] data, string filePath) { string fullPath = Path.GetFullPath(filePath); return ReadAssemblyData(data).Load(fullPath); } public static Assembly Load(string filePath) { string fullPath = Path.GetFullPath(filePath); return ReadAssemblyData(fullPath).Load(fullPath); } } } namespace BepInEx.Unity.Mono.Preloader.RuntimeFixes { internal static class TraceFix { private static Type TraceImplType; private static object ListenersSyncRoot; private static TraceListenerCollection Listeners; private static PropertyInfo prop_AutoFlush; private static bool AutoFlush => (bool)prop_AutoFlush.GetValue(null, null); public static void ApplyFix() { //IL_00b8: 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_00f7: Expected O, but got Unknown TraceImplType = AppDomain.CurrentDomain.GetAssemblies().First((Assembly x) => x.GetName().Name == "System").GetTypes() .FirstOrDefault((Type x) => x.Name == "TraceImpl"); if ((object)TraceImplType != null) { ListenersSyncRoot = AccessTools.Property(TraceImplType, "ListenersSyncRoot").GetValue(null, null); Listeners = (TraceListenerCollection)AccessTools.Property(TraceImplType, "Listeners").GetValue(null, null); prop_AutoFlush = AccessTools.Property(TraceImplType, "AutoFlush"); new Harmony("com.bepis.bepinex.tracefix").Patch((MethodBase)typeof(Trace).GetMethod("DoTrace", BindingFlags.Static | BindingFlags.NonPublic), new HarmonyMethod(typeof(TraceFix).GetMethod("DoTraceReplacement", BindingFlags.Static | BindingFlags.NonPublic)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } private static bool DoTraceReplacement(string kind, Assembly report, string message) { string source = string.Empty; try { source = report.GetName().Name; } catch (MethodAccessException) { } TraceEventType eventType = (TraceEventType)Enum.Parse(typeof(TraceEventType), kind); lock (ListenersSyncRoot) { foreach (TraceListener listener in Listeners) { listener.TraceEvent(new TraceEventCache(), source, eventType, 0, message); if (AutoFlush) { listener.Flush(); } } } return false; } } internal static class UnityPatches { private static Harmony HarmonyInstance { get; set; } public static void Apply() { HarmonyInstance = Harmony.CreateAndPatchAll(typeof(UnityPatches), (string)null); try { TraceFix.ApplyFix(); } catch { } } [HarmonyPrefix] [HarmonyPatch(typeof(Assembly), "LoadFile", new Type[] { typeof(string) })] [HarmonyPatch(typeof(Assembly), "LoadFrom", new Type[] { typeof(string) })] public static bool LoadFilePrefix(string __0, ref Assembly __result) { if (!File.Exists(__0)) { throw new FileNotFoundException(__0); } __result = MonoAssemblyHelper.Load(__0); return false; } } internal static class XTermFix { public static int intOffset; public static void Apply() { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Expected O, but got Unknown //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Expected O, but got Unknown //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Expected O, but got Unknown //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Expected O, but got Unknown //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_00f1: Expected O, but got Unknown //IL_0123: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Expected O, but got Unknown if (!PlatformHelper.Is((Platform)37) && (object)typeof(Console).Assembly.GetType("System.ConsoleDriver") != null && (object)AccessTools.Method("System.TermInfoReader:DetermineVersion", (Type[])null, (Type[])null) == null) { DetourHelper.Native = (IDetourNativePlatform)new DetourNativeX86Platform(); Harmony val = new Harmony("com.bepinex.xtermfix"); val.Patch((MethodBase)AccessTools.Method("System.TermInfoReader:ReadHeader", (Type[])null, (Type[])null), new HarmonyMethod(typeof(XTermFix), "ReadHeaderPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.Method("System.TermInfoReader:Get", new Type[1] { AccessTools.TypeByName("System.TermInfoNumbers") }, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(XTermFix), "GetTermInfoNumbersTranspiler", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.Method("System.TermInfoReader:Get", new Type[1] { AccessTools.TypeByName("System.TermInfoStrings") }, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(XTermFix), "GetTermInfoStringsTranspiler", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.Method("System.TermInfoReader:GetStringBytes", new Type[1] { AccessTools.TypeByName("System.TermInfoStrings") }, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(XTermFix), "GetTermInfoStringsTranspiler", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null); DetourHelper.Native = null; } } public static int GetInt32(byte[] buffer, int offset) { byte num = buffer[offset]; int num2 = buffer[offset + 1]; int num3 = buffer[offset + 2]; int num4 = buffer[offset + 3]; return num | (num2 << 8) | (num3 << 16) | (num4 << 24); } public static short GetInt16(byte[] buffer, int offset) { byte num = buffer[offset]; int num2 = buffer[offset + 1]; return (short)(num | (num2 << 8)); } public static int GetInteger(byte[] buffer, int offset) { if (intOffset != 2) { return GetInt32(buffer, offset); } return GetInt16(buffer, offset); } public static void DetermineVersion(short magic) { switch (magic) { case 282: intOffset = 2; break; case 542: intOffset = 4; break; default: throw new Exception($"Unknown xterm header format: {magic}"); } } public static bool ReadHeaderPrefix(byte[] buffer, ref int position, ref short ___boolSize, ref short ___numSize, ref short ___strOffsets) { short @int = GetInt16(buffer, position); position += 2; DetermineVersion(@int); position += 2; ___boolSize = GetInt16(buffer, position); position += 2; ___numSize = GetInt16(buffer, position); position += 2; ___strOffsets = GetInt16(buffer, position); position += 2; position += 2; return false; } public static IEnumerable<CodeInstruction> GetTermInfoNumbersTranspiler(IEnumerable<CodeInstruction> instructions) { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Expected O, but got Unknown //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Expected O, but got Unknown //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Expected O, but got Unknown List<CodeInstruction> list = instructions.ToList(); list[31] = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(XTermFix), "intOffset")); list[36] = new CodeInstruction(OpCodes.Nop, (object)null); list[39] = new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(XTermFix), "GetInteger", (Type[])null, (Type[])null)); return list; } public static IEnumerable<CodeInstruction> GetTermInfoStringsTranspiler(IEnumerable<CodeInstruction> instructions) { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Expected O, but got Unknown List<CodeInstruction> list = instructions.ToList(); list[32] = new CodeInstruction(OpCodes.Ldsfld, (object)AccessTools.Field(typeof(XTermFix), "intOffset")); return list; } } } namespace Doorstop { internal static class Entrypoint { public static void Start() { string text = $"preloader_{DateTime.Now:yyyyMMdd_HHmmss_fff}.log"; try { EnvVars.LoadVars(); text = Path.Combine(Path.GetDirectoryName(EnvVars.DOORSTOP_PROCESS_PATH) ?? ".", text); typeof(Entrypoint).Assembly.GetType("BepInEx.Unity.Mono.Preloader.UnityPreloaderRunner")?.GetMethod("PreloaderPreMain")?.Invoke(null, null); } catch (Exception ex) { File.WriteAllText(text, ex.ToString()); } } } }
BepInExPack\BepInEx\core\Mono.Cecil.dll
Decompiled 2 months ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security.Cryptography; using System.Text; using System.Threading; using Mono.Cecil; using Mono.Cecil.Cil; using Mono.Cecil.Metadata; using Mono.Cecil.PE; using Mono.Collections.Generic; using Mono.Security.Cryptography; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyProduct("Mono.Cecil")] [assembly: AssemblyCopyright("Copyright © 2008 - 2018 Jb Evain")] [assembly: ComVisible(false)] [assembly: AssemblyFileVersion("0.10.4.0")] [assembly: AssemblyInformationalVersion("0.10.4.0")] [assembly: AssemblyTitle("Mono.Cecil")] [assembly: Guid("fd225bb4-fa53-44b2-a6db-85f5e48dcb54")] [assembly: InternalsVisibleTo("Mono.Cecil.Pdb, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b5c9f7f04346c324a3176f8d3ee823bbf2d60efdbc35f86fd9e65ea3e6cd11bcdcba3a353e55133c8ac5c4caaba581b2c6dfff2cc2d0edc43959ddb86b973300a479a82419ef489c3225f1fe429a708507bd515835160e10bc743d20ca33ab9570cfd68d479fcf0bc797a763bec5d1000f0159ef619e709d915975e87beebaf")] [assembly: InternalsVisibleTo("Mono.Cecil.Mdb, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b5c9f7f04346c324a3176f8d3ee823bbf2d60efdbc35f86fd9e65ea3e6cd11bcdcba3a353e55133c8ac5c4caaba581b2c6dfff2cc2d0edc43959ddb86b973300a479a82419ef489c3225f1fe429a708507bd515835160e10bc743d20ca33ab9570cfd68d479fcf0bc797a763bec5d1000f0159ef619e709d915975e87beebaf")] [assembly: InternalsVisibleTo("Mono.Cecil.Rocks, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b5c9f7f04346c324a3176f8d3ee823bbf2d60efdbc35f86fd9e65ea3e6cd11bcdcba3a353e55133c8ac5c4caaba581b2c6dfff2cc2d0edc43959ddb86b973300a479a82419ef489c3225f1fe429a708507bd515835160e10bc743d20ca33ab9570cfd68d479fcf0bc797a763bec5d1000f0159ef619e709d915975e87beebaf")] [assembly: InternalsVisibleTo("Mono.Cecil.Tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b5c9f7f04346c324a3176f8d3ee823bbf2d60efdbc35f86fd9e65ea3e6cd11bcdcba3a353e55133c8ac5c4caaba581b2c6dfff2cc2d0edc43959ddb86b973300a479a82419ef489c3225f1fe429a708507bd515835160e10bc743d20ca33ab9570cfd68d479fcf0bc797a763bec5d1000f0159ef619e709d915975e87beebaf")] [assembly: AssemblyVersion("0.10.4.0")] internal static class Consts { public const string AssemblyName = "Mono.Cecil"; public const string PublicKey = "00240000048000009400000006020000002400005253413100040000010001002b5c9f7f04346c324a3176f8d3ee823bbf2d60efdbc35f86fd9e65ea3e6cd11bcdcba3a353e55133c8ac5c4caaba581b2c6dfff2cc2d0edc43959ddb86b973300a479a82419ef489c3225f1fe429a708507bd515835160e10bc743d20ca33ab9570cfd68d479fcf0bc797a763bec5d1000f0159ef619e709d915975e87beebaf"; } namespace Mono { internal static class Disposable { public static Disposable<T> Owned<T>(T value) where T : class, IDisposable { return new Disposable<T>(value, owned: true); } public static Disposable<T> NotOwned<T>(T value) where T : class, IDisposable { return new Disposable<T>(value, owned: false); } } internal struct Disposable<T> : IDisposable where T : class, IDisposable { internal readonly T value; private readonly bool owned; public Disposable(T value, bool owned) { this.value = value; this.owned = owned; } public void Dispose() { if (value != null && owned) { value.Dispose(); } } } internal static class Empty<T> { public static readonly T[] Array = new T[0]; } internal class ArgumentNullOrEmptyException : ArgumentException { public ArgumentNullOrEmptyException(string paramName) : base("Argument null or empty", paramName) { } } internal class MergeSort<T> { private readonly T[] elements; private readonly T[] buffer; private readonly IComparer<T> comparer; private MergeSort(T[] elements, IComparer<T> comparer) { this.elements = elements; buffer = new T[elements.Length]; Array.Copy(this.elements, buffer, elements.Length); this.comparer = comparer; } public static void Sort(T[] source, IComparer<T> comparer) { Sort(source, 0, source.Length, comparer); } public static void Sort(T[] source, int start, int length, IComparer<T> comparer) { new MergeSort<T>(source, comparer).Sort(start, length); } private void Sort(int start, int length) { TopDownSplitMerge(buffer, elements, start, length); } private void TopDownSplitMerge(T[] a, T[] b, int start, int end) { if (end - start >= 2) { int num = (end + start) / 2; TopDownSplitMerge(b, a, start, num); TopDownSplitMerge(b, a, num, end); TopDownMerge(a, b, start, num, end); } } private void TopDownMerge(T[] a, T[] b, int start, int middle, int end) { int num = start; int num2 = middle; for (int i = start; i < end; i++) { if (num < middle && (num2 >= end || comparer.Compare(a[num], a[num2]) <= 0)) { b[i] = a[num++]; } else { b[i] = a[num2++]; } } } } internal static class TypeExtensions { public static TypeCode GetTypeCode(this Type type) { return Type.GetTypeCode(type); } public static Assembly Assembly(this Type type) { return type.Assembly; } public static MethodBase DeclaringMethod(this Type type) { return type.DeclaringMethod; } public static Type[] GetGenericArguments(this Type type) { return type.GetGenericArguments(); } public static bool IsGenericType(this Type type) { return type.IsGenericType; } public static bool IsGenericTypeDefinition(this Type type) { return type.IsGenericTypeDefinition; } public static bool IsValueType(this Type type) { return type.IsValueType; } } } namespace Mono.Security.Cryptography { internal static class CryptoConvert { private static int ToInt32LE(byte[] bytes, int offset) { return (bytes[offset + 3] << 24) | (bytes[offset + 2] << 16) | (bytes[offset + 1] << 8) | bytes[offset]; } private static uint ToUInt32LE(byte[] bytes, int offset) { return (uint)((bytes[offset + 3] << 24) | (bytes[offset + 2] << 16) | (bytes[offset + 1] << 8) | bytes[offset]); } private static byte[] Trim(byte[] array) { for (int i = 0; i < array.Length; i++) { if (array[i] != 0) { byte[] array2 = new byte[array.Length - i]; Buffer.BlockCopy(array, i, array2, 0, array2.Length); return array2; } } return null; } private static RSA FromCapiPrivateKeyBlob(byte[] blob, int offset) { RSAParameters parameters = default(RSAParameters); try { if (blob[offset] != 7 || blob[offset + 1] != 2 || blob[offset + 2] != 0 || blob[offset + 3] != 0 || ToUInt32LE(blob, offset + 8) != 843141970) { throw new CryptographicException("Invalid blob header"); } int num = ToInt32LE(blob, offset + 12); byte[] array = new byte[4]; Buffer.BlockCopy(blob, offset + 16, array, 0, 4); Array.Reverse((Array)array); parameters.Exponent = Trim(array); int num2 = offset + 20; int num3 = num >> 3; parameters.Modulus = new byte[num3]; Buffer.BlockCopy(blob, num2, parameters.Modulus, 0, num3); Array.Reverse((Array)parameters.Modulus); num2 += num3; int num4 = num3 >> 1; parameters.P = new byte[num4]; Buffer.BlockCopy(blob, num2, parameters.P, 0, num4); Array.Reverse((Array)parameters.P); num2 += num4; parameters.Q = new byte[num4]; Buffer.BlockCopy(blob, num2, parameters.Q, 0, num4); Array.Reverse((Array)parameters.Q); num2 += num4; parameters.DP = new byte[num4]; Buffer.BlockCopy(blob, num2, parameters.DP, 0, num4); Array.Reverse((Array)parameters.DP); num2 += num4; parameters.DQ = new byte[num4]; Buffer.BlockCopy(blob, num2, parameters.DQ, 0, num4); Array.Reverse((Array)parameters.DQ); num2 += num4; parameters.InverseQ = new byte[num4]; Buffer.BlockCopy(blob, num2, parameters.InverseQ, 0, num4); Array.Reverse((Array)parameters.InverseQ); num2 += num4; parameters.D = new byte[num3]; if (num2 + num3 + offset <= blob.Length) { Buffer.BlockCopy(blob, num2, parameters.D, 0, num3); Array.Reverse((Array)parameters.D); } } catch (Exception inner) { throw new CryptographicException("Invalid blob.", inner); } RSA rSA = null; try { rSA = RSA.Create(); rSA.ImportParameters(parameters); } catch (CryptographicException) { bool flag = false; try { rSA = new RSACryptoServiceProvider(new CspParameters { Flags = CspProviderFlags.UseMachineKeyStore }); rSA.ImportParameters(parameters); } catch { flag = true; } if (flag) { throw; } } return rSA; } private static RSA FromCapiPublicKeyBlob(byte[] blob, int offset) { try { if (blob[offset] != 6 || blob[offset + 1] != 2 || blob[offset + 2] != 0 || blob[offset + 3] != 0 || ToUInt32LE(blob, offset + 8) != 826364754) { throw new CryptographicException("Invalid blob header"); } int num = ToInt32LE(blob, offset + 12); RSAParameters parameters = new RSAParameters { Exponent = new byte[3] }; parameters.Exponent[0] = blob[offset + 18]; parameters.Exponent[1] = blob[offset + 17]; parameters.Exponent[2] = blob[offset + 16]; int srcOffset = offset + 20; int num2 = num >> 3; parameters.Modulus = new byte[num2]; Buffer.BlockCopy(blob, srcOffset, parameters.Modulus, 0, num2); Array.Reverse((Array)parameters.Modulus); RSA rSA = null; try { rSA = RSA.Create(); rSA.ImportParameters(parameters); } catch (CryptographicException) { rSA = new RSACryptoServiceProvider(new CspParameters { Flags = CspProviderFlags.UseMachineKeyStore }); rSA.ImportParameters(parameters); } return rSA; } catch (Exception inner) { throw new CryptographicException("Invalid blob.", inner); } } public static RSA FromCapiKeyBlob(byte[] blob) { return FromCapiKeyBlob(blob, 0); } public static RSA FromCapiKeyBlob(byte[] blob, int offset) { if (blob == null) { throw new ArgumentNullException("blob"); } if (offset >= blob.Length) { throw new ArgumentException("blob is too small."); } switch (blob[offset]) { case 0: if (blob[offset + 12] == 6) { return FromCapiPublicKeyBlob(blob, offset + 12); } break; case 6: return FromCapiPublicKeyBlob(blob, offset); case 7: return FromCapiPrivateKeyBlob(blob, offset); } throw new CryptographicException("Unknown blob format."); } } } namespace Mono.Collections.Generic { public class Collection<T> : IList<T>, ICollection<T>, IEnumerable<T>, IEnumerable, IList, ICollection { public struct Enumerator : IEnumerator<T>, IDisposable, IEnumerator { private Collection<T> collection; private T current; private int next; private readonly int version; public T Current => current; object IEnumerator.Current { get { CheckState(); if (next <= 0) { throw new InvalidOperationException(); } return current; } } internal Enumerator(Collection<T> collection) { this = default(Enumerator); this.collection = collection; version = collection.version; } public bool MoveNext() { CheckState(); if (next < 0) { return false; } if (next < collection.size) { current = collection.items[next++]; return true; } next = -1; return false; } public void Reset() { CheckState(); next = 0; } private void CheckState() { if (collection == null) { throw new ObjectDisposedException(GetType().FullName); } if (version != collection.version) { throw new InvalidOperationException(); } } public void Dispose() { collection = null; } } internal T[] items; internal int size; private int version; public int Count => size; public T this[int index] { get { if (index >= size) { throw new ArgumentOutOfRangeException(); } return items[index]; } set { CheckIndex(index); if (index == size) { throw new ArgumentOutOfRangeException(); } OnSet(value, index); items[index] = value; } } public int Capacity { get { return items.Length; } set { if (value < 0 || value < size) { throw new ArgumentOutOfRangeException(); } Resize(value); } } bool ICollection<T>.IsReadOnly => false; bool IList.IsFixedSize => false; bool IList.IsReadOnly => false; object IList.this[int index] { get { return this[index]; } set { CheckIndex(index); try { this[index] = (T)value; return; } catch (InvalidCastException) { } catch (NullReferenceException) { } throw new ArgumentException(); } } int ICollection.Count => Count; bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => this; public Collection() { items = Empty<T>.Array; } public Collection(int capacity) { if (capacity < 0) { throw new ArgumentOutOfRangeException(); } items = new T[capacity]; } public Collection(ICollection<T> items) { if (items == null) { throw new ArgumentNullException("items"); } this.items = new T[items.Count]; items.CopyTo(this.items, 0); size = this.items.Length; } public void Add(T item) { if (size == items.Length) { Grow(1); } OnAdd(item, size); items[size++] = item; version++; } public bool Contains(T item) { return IndexOf(item) != -1; } public int IndexOf(T item) { return Array.IndexOf(items, item, 0, size); } public void Insert(int index, T item) { CheckIndex(index); if (size == items.Length) { Grow(1); } OnInsert(item, index); Shift(index, 1); items[index] = item; version++; } public void RemoveAt(int index) { if (index < 0 || index >= size) { throw new ArgumentOutOfRangeException(); } T item = items[index]; OnRemove(item, index); Shift(index, -1); version++; } public bool Remove(T item) { int num = IndexOf(item); if (num == -1) { return false; } OnRemove(item, num); Shift(num, -1); version++; return true; } public void Clear() { OnClear(); Array.Clear(items, 0, size); size = 0; version++; } public void CopyTo(T[] array, int arrayIndex) { Array.Copy(items, 0, array, arrayIndex, size); } public T[] ToArray() { T[] array = new T[size]; Array.Copy(items, 0, array, 0, size); return array; } private void CheckIndex(int index) { if (index < 0 || index > size) { throw new ArgumentOutOfRangeException(); } } private void Shift(int start, int delta) { if (delta < 0) { start -= delta; } if (start < size) { Array.Copy(items, start, items, start + delta, size - start); } size += delta; if (delta < 0) { Array.Clear(items, size, -delta); } } protected virtual void OnAdd(T item, int index) { } protected virtual void OnInsert(T item, int index) { } protected virtual void OnSet(T item, int index) { } protected virtual void OnRemove(T item, int index) { } protected virtual void OnClear() { } internal virtual void Grow(int desired) { int num = size + desired; if (num > items.Length) { num = Math.Max(Math.Max(items.Length * 2, 4), num); Resize(num); } } protected void Resize(int new_size) { if (new_size != size) { if (new_size < size) { throw new ArgumentOutOfRangeException(); } items = items.Resize(new_size); } } int IList.Add(object value) { try { Add((T)value); return size - 1; } catch (InvalidCastException) { } catch (NullReferenceException) { } throw new ArgumentException(); } void IList.Clear() { Clear(); } bool IList.Contains(object value) { return ((IList)this).IndexOf(value) > -1; } int IList.IndexOf(object value) { try { return IndexOf((T)value); } catch (InvalidCastException) { } catch (NullReferenceException) { } return -1; } void IList.Insert(int index, object value) { CheckIndex(index); try { Insert(index, (T)value); return; } catch (InvalidCastException) { } catch (NullReferenceException) { } throw new ArgumentException(); } void IList.Remove(object value) { try { Remove((T)value); } catch (InvalidCastException) { } catch (NullReferenceException) { } } void IList.RemoveAt(int index) { RemoveAt(index); } void ICollection.CopyTo(Array array, int index) { Array.Copy(items, 0, array, index, size); } public Enumerator GetEnumerator() { return new Enumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(this); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return new Enumerator(this); } } public sealed class ReadOnlyCollection<T> : Collection<T>, ICollection<T>, IEnumerable<T>, IEnumerable, IList, ICollection { private static ReadOnlyCollection<T> empty; public static ReadOnlyCollection<T> Empty => empty ?? (empty = new ReadOnlyCollection<T>()); bool ICollection<T>.IsReadOnly => true; bool IList.IsFixedSize => true; bool IList.IsReadOnly => true; private ReadOnlyCollection() { } public ReadOnlyCollection(T[] array) { if (array == null) { throw new ArgumentNullException(); } Initialize(array, array.Length); } public ReadOnlyCollection(Collection<T> collection) { if (collection == null) { throw new ArgumentNullException(); } Initialize(collection.items, collection.size); } private void Initialize(T[] items, int size) { base.items = new T[size]; Array.Copy(items, 0, base.items, 0, size); base.size = size; } internal override void Grow(int desired) { throw new InvalidOperationException(); } protected override void OnAdd(T item, int index) { throw new InvalidOperationException(); } protected override void OnClear() { throw new InvalidOperationException(); } protected override void OnInsert(T item, int index) { throw new InvalidOperationException(); } protected override void OnRemove(T item, int index) { throw new InvalidOperationException(); } protected override void OnSet(T item, int index) { throw new InvalidOperationException(); } } } namespace Mono.Cecil { internal static class Mixin { public enum Argument { name, fileName, fullName, stream, type, method, field, parameters, module, modifierType, eventType, fieldType, declaringType, returnType, propertyType, interfaceType } public static Version ZeroVersion = new Version(0, 0, 0, 0); public const int NotResolvedMarker = -2; public const int NoDataMarker = -1; internal static object NoValue = new object(); internal static object NotResolved = new object(); public const string mscorlib = "mscorlib"; public const string system_runtime = "System.Runtime"; public const string system_private_corelib = "System.Private.CoreLib"; public const string netstandard = "netstandard"; public const int TableCount = 58; public const int CodedIndexCount = 14; public static bool IsNullOrEmpty<T>(this T[] self) { if (self != null) { return self.Length == 0; } return true; } public static bool IsNullOrEmpty<T>(this Collection<T> self) { if (self != null) { return self.size == 0; } return true; } public static T[] Resize<T>(this T[] self, int length) { Array.Resize(ref self, length); return self; } public static T[] Add<T>(this T[] self, T item) { if (self == null) { self = new T[1] { item }; return self; } self = self.Resize(self.Length + 1); self[^1] = item; return self; } public static Version CheckVersion(Version version) { if (version == null) { return ZeroVersion; } if (version.Build == -1) { return new Version(version.Major, version.Minor, 0, 0); } if (version.Revision == -1) { return new Version(version.Major, version.Minor, version.Build, 0); } return version; } public static bool TryGetUniqueDocument(this MethodDebugInformation info, out Document document) { document = info.SequencePoints[0].Document; for (int i = 1; i < info.SequencePoints.Count; i++) { if (info.SequencePoints[i].Document != document) { return false; } } return true; } public static void ResolveConstant(this IConstantProvider self, ref object constant, ModuleDefinition module) { if (module == null) { constant = NoValue; return; } lock (module.SyncRoot) { if (constant != NotResolved) { return; } if (module.HasImage()) { constant = module.Read(self, (IConstantProvider provider, MetadataReader reader) => reader.ReadConstant(provider)); } else { constant = NoValue; } } } public static bool GetHasCustomAttributes(this ICustomAttributeProvider self, ModuleDefinition module) { if (module.HasImage()) { return module.Read(self, (ICustomAttributeProvider provider, MetadataReader reader) => reader.HasCustomAttributes(provider)); } return false; } public static Collection<CustomAttribute> GetCustomAttributes(this ICustomAttributeProvider self, ref Collection<CustomAttribute> variable, ModuleDefinition module) { if (!module.HasImage()) { return variable = new Collection<CustomAttribute>(); } return module.Read(ref variable, self, (ICustomAttributeProvider provider, MetadataReader reader) => reader.ReadCustomAttributes(provider)); } public static bool ContainsGenericParameter(this IGenericInstance self) { Collection<TypeReference> genericArguments = self.GenericArguments; for (int i = 0; i < genericArguments.Count; i++) { if (genericArguments[i].ContainsGenericParameter) { return true; } } return false; } public static void GenericInstanceFullName(this IGenericInstance self, StringBuilder builder) { builder.Append("<"); Collection<TypeReference> genericArguments = self.GenericArguments; for (int i = 0; i < genericArguments.Count; i++) { if (i > 0) { builder.Append(","); } builder.Append(genericArguments[i].FullName); } builder.Append(">"); } public static bool GetHasGenericParameters(this IGenericParameterProvider self, ModuleDefinition module) { if (module.HasImage()) { return module.Read(self, (IGenericParameterProvider provider, MetadataReader reader) => reader.HasGenericParameters(provider)); } return false; } public static Collection<GenericParameter> GetGenericParameters(this IGenericParameterProvider self, ref Collection<GenericParameter> collection, ModuleDefinition module) { if (!module.HasImage()) { return collection = new GenericParameterCollection(self); } return module.Read(ref collection, self, (IGenericParameterProvider provider, MetadataReader reader) => reader.ReadGenericParameters(provider)); } public static bool GetHasMarshalInfo(this IMarshalInfoProvider self, ModuleDefinition module) { if (module.HasImage()) { return module.Read(self, (IMarshalInfoProvider provider, MetadataReader reader) => reader.HasMarshalInfo(provider)); } return false; } public static MarshalInfo GetMarshalInfo(this IMarshalInfoProvider self, ref MarshalInfo variable, ModuleDefinition module) { if (!module.HasImage()) { return null; } return module.Read(ref variable, self, (IMarshalInfoProvider provider, MetadataReader reader) => reader.ReadMarshalInfo(provider)); } public static bool GetAttributes(this uint self, uint attributes) { return (self & attributes) != 0; } public static uint SetAttributes(this uint self, uint attributes, bool value) { if (value) { return self | attributes; } return self & ~attributes; } public static bool GetMaskedAttributes(this uint self, uint mask, uint attributes) { return (self & mask) == attributes; } public static uint SetMaskedAttributes(this uint self, uint mask, uint attributes, bool value) { if (value) { self &= ~mask; return self | attributes; } return self & ~(mask & attributes); } public static bool GetAttributes(this ushort self, ushort attributes) { return (self & attributes) != 0; } public static ushort SetAttributes(this ushort self, ushort attributes, bool value) { if (value) { return (ushort)(self | attributes); } return (ushort)(self & ~attributes); } public static bool GetMaskedAttributes(this ushort self, ushort mask, uint attributes) { return (self & mask) == attributes; } public static ushort SetMaskedAttributes(this ushort self, ushort mask, uint attributes, bool value) { if (value) { self = (ushort)(self & ~mask); return (ushort)(self | attributes); } return (ushort)(self & ~(mask & attributes)); } public static bool HasImplicitThis(this IMethodSignature self) { if (self.HasThis) { return !self.ExplicitThis; } return false; } public static void MethodSignatureFullName(this IMethodSignature self, StringBuilder builder) { builder.Append("("); if (self.HasParameters) { Collection<ParameterDefinition> parameters = self.Parameters; for (int i = 0; i < parameters.Count; i++) { ParameterDefinition parameterDefinition = parameters[i]; if (i > 0) { builder.Append(","); } if (parameterDefinition.ParameterType.IsSentinel) { builder.Append("...,"); } builder.Append(parameterDefinition.ParameterType.FullName); } } builder.Append(")"); } public static void CheckModule(ModuleDefinition module) { if (module == null) { throw new ArgumentNullException(Argument.module.ToString()); } } public static bool TryGetAssemblyNameReference(this ModuleDefinition module, AssemblyNameReference name_reference, out AssemblyNameReference assembly_reference) { Collection<AssemblyNameReference> assemblyReferences = module.AssemblyReferences; for (int i = 0; i < assemblyReferences.Count; i++) { AssemblyNameReference assemblyNameReference = assemblyReferences[i]; if (Equals(name_reference, assemblyNameReference)) { assembly_reference = assemblyNameReference; return true; } } assembly_reference = null; return false; } private static bool Equals(byte[] a, byte[] b) { if (a == b) { return true; } if (a == null) { return false; } if (a.Length != b.Length) { return false; } for (int i = 0; i < a.Length; i++) { if (a[i] != b[i]) { return false; } } return true; } private static bool Equals<T>(T a, T b) where T : class, IEquatable<T> { if (a == b) { return true; } return a?.Equals(b) ?? false; } private static bool Equals(AssemblyNameReference a, AssemblyNameReference b) { if (a == b) { return true; } if (a.Name != b.Name) { return false; } if (!Equals(a.Version, b.Version)) { return false; } if (a.Culture != b.Culture) { return false; } if (!Equals(a.PublicKeyToken, b.PublicKeyToken)) { return false; } return true; } public static ParameterDefinition GetParameter(this Mono.Cecil.Cil.MethodBody self, int index) { MethodDefinition method = self.method; if (method.HasThis) { if (index == 0) { return self.ThisParameter; } index--; } Collection<ParameterDefinition> parameters = method.Parameters; if (index < 0 || index >= parameters.size) { return null; } return parameters[index]; } public static VariableDefinition GetVariable(this Mono.Cecil.Cil.MethodBody self, int index) { Collection<VariableDefinition> variables = self.Variables; if (index < 0 || index >= variables.size) { return null; } return variables[index]; } public static bool GetSemantics(this MethodDefinition self, MethodSemanticsAttributes semantics) { return (self.SemanticsAttributes & semantics) != 0; } public static void SetSemantics(this MethodDefinition self, MethodSemanticsAttributes semantics, bool value) { if (value) { self.SemanticsAttributes |= semantics; } else { self.SemanticsAttributes &= (MethodSemanticsAttributes)(ushort)(~(int)semantics); } } public static bool IsVarArg(this IMethodSignature self) { return self.CallingConvention == MethodCallingConvention.VarArg; } public static int GetSentinelPosition(this IMethodSignature self) { if (!self.HasParameters) { return -1; } Collection<ParameterDefinition> parameters = self.Parameters; for (int i = 0; i < parameters.Count; i++) { if (parameters[i].ParameterType.IsSentinel) { return i; } } return -1; } public static void CheckName(object name) { if (name == null) { throw new ArgumentNullException(Argument.name.ToString()); } } public static void CheckName(string name) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullOrEmptyException(Argument.name.ToString()); } } public static void CheckFileName(string fileName) { if (string.IsNullOrEmpty(fileName)) { throw new ArgumentNullOrEmptyException(Argument.fileName.ToString()); } } public static void CheckFullName(string fullName) { if (string.IsNullOrEmpty(fullName)) { throw new ArgumentNullOrEmptyException(Argument.fullName.ToString()); } } public static void CheckStream(object stream) { if (stream == null) { throw new ArgumentNullException(Argument.stream.ToString()); } } public static void CheckWriteSeek(Stream stream) { if (!stream.CanWrite || !stream.CanSeek) { throw new ArgumentException("Stream must be writable and seekable."); } } public static void CheckReadSeek(Stream stream) { if (!stream.CanRead || !stream.CanSeek) { throw new ArgumentException("Stream must be readable and seekable."); } } public static void CheckType(object type) { if (type == null) { throw new ArgumentNullException(Argument.type.ToString()); } } public static void CheckType(object type, Argument argument) { if (type == null) { throw new ArgumentNullException(argument.ToString()); } } public static void CheckField(object field) { if (field == null) { throw new ArgumentNullException(Argument.field.ToString()); } } public static void CheckMethod(object method) { if (method == null) { throw new ArgumentNullException(Argument.method.ToString()); } } public static void CheckParameters(object parameters) { if (parameters == null) { throw new ArgumentNullException(Argument.parameters.ToString()); } } public static uint GetTimestamp() { return (uint)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds; } public static bool HasImage(this ModuleDefinition self) { return self?.HasImage ?? false; } public static string GetFileName(this Stream self) { if (!(self is FileStream fileStream)) { return string.Empty; } return Path.GetFullPath(fileStream.Name); } public static void CopyTo(this Stream self, Stream target) { byte[] array = new byte[8192]; int count; while ((count = self.Read(array, 0, array.Length)) > 0) { target.Write(array, 0, count); } } public static TargetRuntime ParseRuntime(this string self) { if (string.IsNullOrEmpty(self)) { return TargetRuntime.Net_4_0; } switch (self[1]) { case '1': if (self[3] != '0') { return TargetRuntime.Net_1_1; } return TargetRuntime.Net_1_0; case '2': return TargetRuntime.Net_2_0; default: return TargetRuntime.Net_4_0; } } public static string RuntimeVersionString(this TargetRuntime runtime) { return runtime switch { TargetRuntime.Net_1_0 => "v1.0.3705", TargetRuntime.Net_1_1 => "v1.1.4322", TargetRuntime.Net_2_0 => "v2.0.50727", _ => "v4.0.30319", }; } public static bool IsWindowsMetadata(this ModuleDefinition module) { return module.MetadataKind != MetadataKind.Ecma335; } public static byte[] ReadAll(this Stream self) { MemoryStream memoryStream = new MemoryStream((int)self.Length); byte[] array = new byte[1024]; int count; while ((count = self.Read(array, 0, array.Length)) != 0) { memoryStream.Write(array, 0, count); } return memoryStream.ToArray(); } public static void Read(object o) { } public static bool GetHasSecurityDeclarations(this ISecurityDeclarationProvider self, ModuleDefinition module) { if (module.HasImage()) { return module.Read(self, (ISecurityDeclarationProvider provider, MetadataReader reader) => reader.HasSecurityDeclarations(provider)); } return false; } public static Collection<SecurityDeclaration> GetSecurityDeclarations(this ISecurityDeclarationProvider self, ref Collection<SecurityDeclaration> variable, ModuleDefinition module) { if (!module.HasImage()) { return variable = new Collection<SecurityDeclaration>(); } return module.Read(ref variable, self, (ISecurityDeclarationProvider provider, MetadataReader reader) => reader.ReadSecurityDeclarations(provider)); } public static TypeReference GetEnumUnderlyingType(this TypeDefinition self) { Collection<FieldDefinition> fields = self.Fields; for (int i = 0; i < fields.Count; i++) { FieldDefinition fieldDefinition = fields[i]; if (!fieldDefinition.IsStatic) { return fieldDefinition.FieldType; } } throw new ArgumentException(); } public static TypeDefinition GetNestedType(this TypeDefinition self, string fullname) { if (!self.HasNestedTypes) { return null; } Collection<TypeDefinition> nestedTypes = self.NestedTypes; for (int i = 0; i < nestedTypes.Count; i++) { TypeDefinition typeDefinition = nestedTypes[i]; if (typeDefinition.TypeFullName() == fullname) { return typeDefinition; } } return null; } public static bool IsPrimitive(this ElementType self) { switch (self) { case ElementType.Boolean: case ElementType.Char: case ElementType.I1: case ElementType.U1: case ElementType.I2: case ElementType.U2: case ElementType.I4: case ElementType.U4: case ElementType.I8: case ElementType.U8: case ElementType.R4: case ElementType.R8: case ElementType.I: case ElementType.U: return true; default: return false; } } public static string TypeFullName(this TypeReference self) { if (!string.IsNullOrEmpty(self.Namespace)) { return self.Namespace + "." + self.Name; } return self.Name; } public static bool IsTypeOf(this TypeReference self, string @namespace, string name) { if (self.Name == name) { return self.Namespace == @namespace; } return false; } public static bool IsTypeSpecification(this TypeReference type) { switch (type.etype) { case ElementType.Ptr: case ElementType.ByRef: case ElementType.Var: case ElementType.Array: case ElementType.GenericInst: case ElementType.FnPtr: case ElementType.SzArray: case ElementType.MVar: case ElementType.CModReqD: case ElementType.CModOpt: case ElementType.Sentinel: case ElementType.Pinned: return true; default: return false; } } public static TypeDefinition CheckedResolve(this TypeReference self) { return self.Resolve() ?? throw new ResolutionException(self); } public static bool TryGetCoreLibraryReference(this ModuleDefinition module, out AssemblyNameReference reference) { Collection<AssemblyNameReference> assemblyReferences = module.AssemblyReferences; for (int i = 0; i < assemblyReferences.Count; i++) { reference = assemblyReferences[i]; if (IsCoreLibrary(reference)) { return true; } } reference = null; return false; } public static bool IsCoreLibrary(this ModuleDefinition module) { if (module.Assembly == null) { return false; } if (!IsCoreLibrary(module.Assembly.Name)) { return false; } if (module.HasImage && module.Read(module, (ModuleDefinition m, MetadataReader reader) => reader.image.GetTableLength(Table.AssemblyRef) > 0)) { return false; } return true; } public static void KnownValueType(this TypeReference type) { if (!type.IsDefinition) { type.IsValueType = true; } } private static bool IsCoreLibrary(AssemblyNameReference reference) { string name = reference.Name; switch (name) { default: return name == "netstandard"; case "mscorlib": case "System.Runtime": case "System.Private.CoreLib": return true; } } public static ImageDebugHeaderEntry GetCodeViewEntry(this ImageDebugHeader header) { return header.GetEntry(ImageDebugType.CodeView); } public static ImageDebugHeaderEntry GetDeterministicEntry(this ImageDebugHeader header) { return header.GetEntry(ImageDebugType.Deterministic); } public static ImageDebugHeader AddDeterministicEntry(this ImageDebugHeader header) { ImageDebugDirectory directory = default(ImageDebugDirectory); directory.Type = ImageDebugType.Deterministic; ImageDebugHeaderEntry imageDebugHeaderEntry = new ImageDebugHeaderEntry(directory, Empty<byte>.Array); if (header == null) { return new ImageDebugHeader(imageDebugHeaderEntry); } ImageDebugHeaderEntry[] array = new ImageDebugHeaderEntry[header.Entries.Length + 1]; Array.Copy(header.Entries, array, header.Entries.Length); array[^1] = imageDebugHeaderEntry; return new ImageDebugHeader(array); } public static ImageDebugHeaderEntry GetEmbeddedPortablePdbEntry(this ImageDebugHeader header) { return header.GetEntry(ImageDebugType.EmbeddedPortablePdb); } private static ImageDebugHeaderEntry GetEntry(this ImageDebugHeader header, ImageDebugType type) { if (!header.HasEntries) { return null; } for (int i = 0; i < header.Entries.Length; i++) { ImageDebugHeaderEntry imageDebugHeaderEntry = header.Entries[i]; if (imageDebugHeaderEntry.Directory.Type == type) { return imageDebugHeaderEntry; } } return null; } public static string GetPdbFileName(string assemblyFileName) { return Path.ChangeExtension(assemblyFileName, ".pdb"); } public static string GetMdbFileName(string assemblyFileName) { return assemblyFileName + ".mdb"; } public static bool IsPortablePdb(string fileName) { using FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); return IsPortablePdb(stream); } public static bool IsPortablePdb(Stream stream) { if (stream.Length < 4) { return false; } long position = stream.Position; try { return new BinaryReader(stream).ReadUInt32() == 1112167234; } finally { stream.Position = position; } } public static uint ReadCompressedUInt32(this byte[] data, ref int position) { uint result; if ((data[position] & 0x80) == 0) { result = data[position]; position++; } else if ((data[position] & 0x40) == 0) { result = (uint)((data[position] & -129) << 8); result |= data[position + 1]; position += 2; } else { result = (uint)((data[position] & -193) << 24); result |= (uint)(data[position + 1] << 16); result |= (uint)(data[position + 2] << 8); result |= data[position + 3]; position += 4; } return result; } public static MetadataToken GetMetadataToken(this CodedIndex self, uint data) { uint rid; TokenType type; switch (self) { case CodedIndex.TypeDefOrRef: rid = data >> 2; switch (data & 3) { case 0u: break; case 1u: goto IL_006d; case 2u: goto IL_0078; default: goto end_IL_0001; } type = TokenType.TypeDef; goto IL_05b3; case CodedIndex.HasConstant: rid = data >> 2; switch (data & 3) { case 0u: break; case 1u: goto IL_00ad; case 2u: goto IL_00b8; default: goto end_IL_0001; } type = TokenType.Field; goto IL_05b3; case CodedIndex.HasCustomAttribute: rid = data >> 5; switch (data & 0x1F) { case 0u: break; case 1u: goto IL_013a; case 2u: goto IL_0145; case 3u: goto IL_0150; case 4u: goto IL_015b; case 5u: goto IL_0166; case 6u: goto IL_0171; case 7u: goto IL_017c; case 8u: goto IL_0183; case 9u: goto IL_018e; case 10u: goto IL_0199; case 11u: goto IL_01a4; case 12u: goto IL_01af; case 13u: goto IL_01ba; case 14u: goto IL_01c5; case 15u: goto IL_01d0; case 16u: goto IL_01db; case 17u: goto IL_01e6; case 18u: goto IL_01f1; case 19u: goto IL_01fc; case 20u: goto IL_0207; case 21u: goto IL_0212; default: goto end_IL_0001; } type = TokenType.Method; goto IL_05b3; case CodedIndex.HasFieldMarshal: { rid = data >> 1; uint num = data & 1u; if (num != 0) { if (num != 1) { break; } type = TokenType.Param; } else { type = TokenType.Field; } goto IL_05b3; } case CodedIndex.HasDeclSecurity: rid = data >> 2; switch (data & 3) { case 0u: break; case 1u: goto IL_0271; case 2u: goto IL_027c; default: goto end_IL_0001; } type = TokenType.TypeDef; goto IL_05b3; case CodedIndex.MemberRefParent: rid = data >> 3; switch (data & 7) { case 0u: break; case 1u: goto IL_02b9; case 2u: goto IL_02c4; case 3u: goto IL_02cf; case 4u: goto IL_02da; default: goto end_IL_0001; } type = TokenType.TypeDef; goto IL_05b3; case CodedIndex.HasSemantics: { rid = data >> 1; uint num = data & 1u; if (num != 0) { if (num != 1) { break; } type = TokenType.Property; } else { type = TokenType.Event; } goto IL_05b3; } case CodedIndex.MethodDefOrRef: { rid = data >> 1; uint num = data & 1u; if (num != 0) { if (num != 1) { break; } type = TokenType.MemberRef; } else { type = TokenType.Method; } goto IL_05b3; } case CodedIndex.MemberForwarded: { rid = data >> 1; uint num = data & 1u; if (num != 0) { if (num != 1) { break; } type = TokenType.Method; } else { type = TokenType.Field; } goto IL_05b3; } case CodedIndex.Implementation: rid = data >> 2; switch (data & 3) { case 0u: break; case 1u: goto IL_038d; case 2u: goto IL_0398; default: goto end_IL_0001; } type = TokenType.File; goto IL_05b3; case CodedIndex.CustomAttributeType: { rid = data >> 3; uint num = data & 7u; if (num != 2) { if (num != 3) { break; } type = TokenType.MemberRef; } else { type = TokenType.Method; } goto IL_05b3; } case CodedIndex.ResolutionScope: rid = data >> 2; switch (data & 3) { case 0u: break; case 1u: goto IL_03f8; case 2u: goto IL_0403; case 3u: goto IL_040e; default: goto end_IL_0001; } type = TokenType.Module; goto IL_05b3; case CodedIndex.TypeOrMethodDef: { rid = data >> 1; uint num = data & 1u; if (num != 0) { if (num != 1) { break; } type = TokenType.Method; } else { type = TokenType.TypeDef; } goto IL_05b3; } case CodedIndex.HasCustomDebugInformation: { rid = data >> 5; switch (data & 0x1F) { case 0u: break; case 1u: goto IL_04ce; case 2u: goto IL_04d9; case 3u: goto IL_04e4; case 4u: goto IL_04ef; case 5u: goto IL_04fa; case 6u: goto IL_0505; case 7u: goto IL_0510; case 8u: goto IL_0517; case 9u: goto IL_0522; case 10u: goto IL_052d; case 11u: goto IL_0535; case 12u: goto IL_053d; case 13u: goto IL_0545; case 14u: goto IL_054d; case 15u: goto IL_0555; case 16u: goto IL_055d; case 17u: goto IL_0565; case 18u: goto IL_056d; case 19u: goto IL_0575; case 20u: goto IL_057d; case 21u: goto IL_0585; case 22u: goto IL_058d; case 23u: goto IL_0595; case 24u: goto IL_059d; case 25u: goto IL_05a5; case 26u: goto IL_05ad; default: goto end_IL_0001; } type = TokenType.Method; goto IL_05b3; } IL_05ad: type = TokenType.ImportScope; goto IL_05b3; IL_05a5: type = TokenType.LocalConstant; goto IL_05b3; IL_059d: type = TokenType.LocalVariable; goto IL_05b3; IL_0595: type = TokenType.LocalScope; goto IL_05b3; IL_058d: type = TokenType.Document; goto IL_05b3; IL_0585: type = TokenType.MethodSpec; goto IL_05b3; IL_057d: type = TokenType.GenericParamConstraint; goto IL_05b3; IL_0575: type = TokenType.GenericParam; goto IL_05b3; IL_056d: type = TokenType.ManifestResource; goto IL_05b3; IL_0565: type = TokenType.ExportedType; goto IL_05b3; IL_055d: type = TokenType.File; goto IL_05b3; IL_0555: type = TokenType.AssemblyRef; goto IL_05b3; IL_054d: type = TokenType.Assembly; goto IL_05b3; IL_0545: type = TokenType.TypeSpec; goto IL_05b3; IL_053d: type = TokenType.ModuleRef; goto IL_05b3; IL_0535: type = TokenType.Signature; goto IL_05b3; IL_052d: type = TokenType.Event; goto IL_05b3; IL_0522: type = TokenType.Property; goto IL_05b3; IL_0517: type = TokenType.Permission; goto IL_05b3; IL_0510: type = TokenType.Module; goto IL_05b3; IL_0505: type = TokenType.MemberRef; goto IL_05b3; IL_04fa: type = TokenType.InterfaceImpl; goto IL_05b3; IL_04ef: type = TokenType.Param; goto IL_05b3; IL_04e4: type = TokenType.TypeDef; goto IL_05b3; IL_04d9: type = TokenType.TypeRef; goto IL_05b3; IL_04ce: type = TokenType.Field; goto IL_05b3; IL_01db: type = TokenType.File; goto IL_05b3; IL_01d0: type = TokenType.AssemblyRef; goto IL_05b3; IL_01ba: type = TokenType.TypeSpec; goto IL_05b3; IL_01c5: type = TokenType.Assembly; goto IL_05b3; IL_040e: type = TokenType.TypeRef; goto IL_05b3; IL_0403: type = TokenType.AssemblyRef; goto IL_05b3; IL_03f8: type = TokenType.ModuleRef; goto IL_05b3; IL_01af: type = TokenType.ModuleRef; goto IL_05b3; IL_01a4: type = TokenType.Signature; goto IL_05b3; IL_018e: type = TokenType.Property; goto IL_05b3; IL_0199: type = TokenType.Event; goto IL_05b3; IL_0398: type = TokenType.ExportedType; goto IL_05b3; IL_038d: type = TokenType.AssemblyRef; goto IL_05b3; IL_0183: type = TokenType.Permission; goto IL_05b3; IL_017c: type = TokenType.Module; goto IL_05b3; IL_0166: type = TokenType.InterfaceImpl; goto IL_05b3; IL_0171: type = TokenType.MemberRef; goto IL_05b3; IL_015b: type = TokenType.Param; goto IL_05b3; IL_0145: type = TokenType.TypeRef; goto IL_05b3; IL_0150: type = TokenType.TypeDef; goto IL_05b3; IL_013a: type = TokenType.Field; goto IL_05b3; IL_006d: type = TokenType.TypeRef; goto IL_05b3; IL_02da: type = TokenType.TypeSpec; goto IL_05b3; IL_02cf: type = TokenType.Method; goto IL_05b3; IL_02c4: type = TokenType.ModuleRef; goto IL_05b3; IL_02b9: type = TokenType.TypeRef; goto IL_05b3; IL_00b8: type = TokenType.Property; goto IL_05b3; IL_027c: type = TokenType.Assembly; goto IL_05b3; IL_0271: type = TokenType.Method; goto IL_05b3; IL_00ad: type = TokenType.Param; goto IL_05b3; IL_05b3: return new MetadataToken(type, rid); IL_0078: type = TokenType.TypeSpec; goto IL_05b3; IL_0212: type = TokenType.MethodSpec; goto IL_05b3; IL_0207: type = TokenType.GenericParamConstraint; goto IL_05b3; IL_01fc: type = TokenType.GenericParam; goto IL_05b3; IL_01f1: type = TokenType.ManifestResource; goto IL_05b3; IL_01e6: type = TokenType.ExportedType; goto IL_05b3; end_IL_0001: break; } return MetadataToken.Zero; } public static uint CompressMetadataToken(this CodedIndex self, MetadataToken token) { uint result = 0u; if (token.RID == 0) { return result; } switch (self) { case CodedIndex.TypeDefOrRef: result = token.RID << 2; switch (token.TokenType) { case TokenType.TypeDef: return result | 0u; case TokenType.TypeRef: return result | 1u; case TokenType.TypeSpec: return result | 2u; } break; case CodedIndex.HasConstant: result = token.RID << 2; switch (token.TokenType) { case TokenType.Field: return result | 0u; case TokenType.Param: return result | 1u; case TokenType.Property: return result | 2u; } break; case CodedIndex.HasCustomAttribute: result = token.RID << 5; switch (token.TokenType) { case TokenType.Method: return result | 0u; case TokenType.Field: return result | 1u; case TokenType.TypeRef: return result | 2u; case TokenType.TypeDef: return result | 3u; case TokenType.Param: return result | 4u; case TokenType.InterfaceImpl: return result | 5u; case TokenType.MemberRef: return result | 6u; case TokenType.Module: return result | 7u; case TokenType.Permission: return result | 8u; case TokenType.Property: return result | 9u; case TokenType.Event: return result | 0xAu; case TokenType.Signature: return result | 0xBu; case TokenType.ModuleRef: return result | 0xCu; case TokenType.TypeSpec: return result | 0xDu; case TokenType.Assembly: return result | 0xEu; case TokenType.AssemblyRef: return result | 0xFu; case TokenType.File: return result | 0x10u; case TokenType.ExportedType: return result | 0x11u; case TokenType.ManifestResource: return result | 0x12u; case TokenType.GenericParam: return result | 0x13u; case TokenType.GenericParamConstraint: return result | 0x14u; case TokenType.MethodSpec: return result | 0x15u; } break; case CodedIndex.HasFieldMarshal: result = token.RID << 1; switch (token.TokenType) { case TokenType.Field: return result | 0u; case TokenType.Param: return result | 1u; } break; case CodedIndex.HasDeclSecurity: result = token.RID << 2; switch (token.TokenType) { case TokenType.TypeDef: return result | 0u; case TokenType.Method: return result | 1u; case TokenType.Assembly: return result | 2u; } break; case CodedIndex.MemberRefParent: result = token.RID << 3; switch (token.TokenType) { case TokenType.TypeDef: return result | 0u; case TokenType.TypeRef: return result | 1u; case TokenType.ModuleRef: return result | 2u; case TokenType.Method: return result | 3u; case TokenType.TypeSpec: return result | 4u; } break; case CodedIndex.HasSemantics: result = token.RID << 1; switch (token.TokenType) { case TokenType.Event: return result | 0u; case TokenType.Property: return result | 1u; } break; case CodedIndex.MethodDefOrRef: result = token.RID << 1; switch (token.TokenType) { case TokenType.Method: return result | 0u; case TokenType.MemberRef: return result | 1u; } break; case CodedIndex.MemberForwarded: result = token.RID << 1; switch (token.TokenType) { case TokenType.Field: return result | 0u; case TokenType.Method: return result | 1u; } break; case CodedIndex.Implementation: result = token.RID << 2; switch (token.TokenType) { case TokenType.File: return result | 0u; case TokenType.AssemblyRef: return result | 1u; case TokenType.ExportedType: return result | 2u; } break; case CodedIndex.CustomAttributeType: result = token.RID << 3; switch (token.TokenType) { case TokenType.Method: return result | 2u; case TokenType.MemberRef: return result | 3u; } break; case CodedIndex.ResolutionScope: result = token.RID << 2; switch (token.TokenType) { case TokenType.Module: return result | 0u; case TokenType.ModuleRef: return result | 1u; case TokenType.AssemblyRef: return result | 2u; case TokenType.TypeRef: return result | 3u; } break; case CodedIndex.TypeOrMethodDef: result = token.RID << 1; switch (token.TokenType) { case TokenType.TypeDef: return result | 0u; case TokenType.Method: return result | 1u; } break; case CodedIndex.HasCustomDebugInformation: result = token.RID << 5; switch (token.TokenType) { case TokenType.Method: return result | 0u; case TokenType.Field: return result | 1u; case TokenType.TypeRef: return result | 2u; case TokenType.TypeDef: return result | 3u; case TokenType.Param: return result | 4u; case TokenType.InterfaceImpl: return result | 5u; case TokenType.MemberRef: return result | 6u; case TokenType.Module: return result | 7u; case TokenType.Permission: return result | 8u; case TokenType.Property: return result | 9u; case TokenType.Event: return result | 0xAu; case TokenType.Signature: return result | 0xBu; case TokenType.ModuleRef: return result | 0xCu; case TokenType.TypeSpec: return result | 0xDu; case TokenType.Assembly: return result | 0xEu; case TokenType.AssemblyRef: return result | 0xFu; case TokenType.File: return result | 0x10u; case TokenType.ExportedType: return result | 0x11u; case TokenType.ManifestResource: return result | 0x12u; case TokenType.GenericParam: return result | 0x13u; case TokenType.GenericParamConstraint: return result | 0x14u; case TokenType.MethodSpec: return result | 0x15u; case TokenType.Document: return result | 0x16u; case TokenType.LocalScope: return result | 0x17u; case TokenType.LocalVariable: return result | 0x18u; case TokenType.LocalConstant: return result | 0x19u; case TokenType.ImportScope: return result | 0x1Au; } break; } throw new ArgumentException(); } public static int GetSize(this CodedIndex self, Func<Table, int> counter) { int num; Table[] array; switch (self) { case CodedIndex.TypeDefOrRef: num = 2; array = new Table[3] { Table.TypeDef, Table.TypeRef, Table.TypeSpec }; break; case CodedIndex.HasConstant: num = 2; array = new Table[3] { Table.Field, Table.Param, Table.Property }; break; case CodedIndex.HasCustomAttribute: num = 5; array = new Table[22] { Table.Method, Table.Field, Table.TypeRef, Table.TypeDef, Table.Param, Table.InterfaceImpl, Table.MemberRef, Table.Module, Table.DeclSecurity, Table.Property, Table.Event, Table.StandAloneSig, Table.ModuleRef, Table.TypeSpec, Table.Assembly, Table.AssemblyRef, Table.File, Table.ExportedType, Table.ManifestResource, Table.GenericParam, Table.GenericParamConstraint, Table.MethodSpec }; break; case CodedIndex.HasFieldMarshal: num = 1; array = new Table[2] { Table.Field, Table.Param }; break; case CodedIndex.HasDeclSecurity: num = 2; array = new Table[3] { Table.TypeDef, Table.Method, Table.Assembly }; break; case CodedIndex.MemberRefParent: num = 3; array = new Table[5] { Table.TypeDef, Table.TypeRef, Table.ModuleRef, Table.Method, Table.TypeSpec }; break; case CodedIndex.HasSemantics: num = 1; array = new Table[2] { Table.Event, Table.Property }; break; case CodedIndex.MethodDefOrRef: num = 1; array = new Table[2] { Table.Method, Table.MemberRef }; break; case CodedIndex.MemberForwarded: num = 1; array = new Table[2] { Table.Field, Table.Method }; break; case CodedIndex.Implementation: num = 2; array = new Table[3] { Table.File, Table.AssemblyRef, Table.ExportedType }; break; case CodedIndex.CustomAttributeType: num = 3; array = new Table[2] { Table.Method, Table.MemberRef }; break; case CodedIndex.ResolutionScope: num = 2; array = new Table[4] { Table.Module, Table.ModuleRef, Table.AssemblyRef, Table.TypeRef }; break; case CodedIndex.TypeOrMethodDef: num = 1; array = new Table[2] { Table.TypeDef, Table.Method }; break; case CodedIndex.HasCustomDebugInformation: num = 5; array = new Table[27] { Table.Method, Table.Field, Table.TypeRef, Table.TypeDef, Table.Param, Table.InterfaceImpl, Table.MemberRef, Table.Module, Table.DeclSecurity, Table.Property, Table.Event, Table.StandAloneSig, Table.ModuleRef, Table.TypeSpec, Table.Assembly, Table.AssemblyRef, Table.File, Table.ExportedType, Table.ManifestResource, Table.GenericParam, Table.GenericParamConstraint, Table.MethodSpec, Table.Document, Table.LocalScope, Table.LocalVariable, Table.LocalConstant, Table.ImportScope }; break; default: throw new ArgumentException(); } int num2 = 0; for (int i = 0; i < array.Length; i++) { num2 = Math.Max(counter(array[i]), num2); } if (num2 >= 1 << 16 - num) { return 4; } return 2; } public static RSA CreateRSA(this StrongNameKeyPair key_pair) { if (!TryGetKeyContainer(key_pair, out var key, out var key_container)) { return CryptoConvert.FromCapiKeyBlob(key); } return new RSACryptoServiceProvider(new CspParameters { Flags = CspProviderFlags.UseMachineKeyStore, KeyContainerName = key_container, KeyNumber = 2 }); } private static bool TryGetKeyContainer(ISerializable key_pair, out byte[] key, out string key_container) { SerializationInfo serializationInfo = new SerializationInfo(typeof(StrongNameKeyPair), new FormatterConverter()); key_pair.GetObjectData(serializationInfo, default(StreamingContext)); key = (byte[])serializationInfo.GetValue("_keyPairArray", typeof(byte[])); key_container = serializationInfo.GetString("_keyPairContainer"); return key_container != null; } } public struct ArrayDimension { private int? lower_bound; private int? upper_bound; public int? LowerBound { get { return lower_bound; } set { lower_bound = value; } } public int? UpperBound { get { return upper_bound; } set { upper_bound = value; } } public bool IsSized { get { if (!lower_bound.HasValue) { return upper_bound.HasValue; } return true; } } public ArrayDimension(int? lowerBound, int? upperBound) { lower_bound = lowerBound; upper_bound = upperBound; } public override string ToString() { if (IsSized) { return lower_bound + "..." + upper_bound; } return string.Empty; } } public sealed class ArrayType : TypeSpecification { private Collection<ArrayDimension> dimensions; public Collection<ArrayDimension> Dimensions { get { if (dimensions != null) { return dimensions; } dimensions = new Collection<ArrayDimension>(); dimensions.Add(default(ArrayDimension)); return dimensions; } } public int Rank { get { if (dimensions != null) { return dimensions.Count; } return 1; } } public bool IsVector { get { if (dimensions == null) { return true; } if (dimensions.Count > 1) { return false; } return !dimensions[0].IsSized; } } public override bool IsValueType { get { return false; } set { throw new InvalidOperationException(); } } public override string Name => base.Name + Suffix; public override string FullName => base.FullName + Suffix; private string Suffix { get { if (IsVector) { return "[]"; } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("["); for (int i = 0; i < dimensions.Count; i++) { if (i > 0) { stringBuilder.Append(","); } stringBuilder.Append(dimensions[i].ToString()); } stringBuilder.Append("]"); return stringBuilder.ToString(); } } public override bool IsArray => true; public ArrayType(TypeReference type) : base(type) { Mixin.CheckType(type); etype = Mono.Cecil.Metadata.ElementType.Array; } public ArrayType(TypeReference type, int rank) : this(type) { Mixin.CheckType(type); if (rank != 1) { dimensions = new Collection<ArrayDimension>(rank); for (int i = 0; i < rank; i++) { dimensions.Add(default(ArrayDimension)); } etype = Mono.Cecil.Metadata.ElementType.Array; } } } public sealed class AssemblyDefinition : ICustomAttributeProvider, IMetadataTokenProvider, ISecurityDeclarationProvider, IDisposable { private AssemblyNameDefinition name; internal ModuleDefinition main_module; private Collection<ModuleDefinition> modules; private Collection<CustomAttribute> custom_attributes; private Collection<SecurityDeclaration> security_declarations; public AssemblyNameDefinition Name { get { return name; } set { name = value; } } public string FullName { get { if (name == null) { return string.Empty; } return name.FullName; } } public MetadataToken MetadataToken { get { return new MetadataToken(TokenType.Assembly, 1); } set { } } public Collection<ModuleDefinition> Modules { get { if (modules != null) { return modules; } if (main_module.HasImage) { return main_module.Read(ref modules, this, (AssemblyDefinition _, MetadataReader reader) => reader.ReadModules()); } return modules = new Collection<ModuleDefinition>(1) { main_module }; } } public ModuleDefinition MainModule => main_module; public MethodDefinition EntryPoint { get { return main_module.EntryPoint; } set { main_module.EntryPoint = value; } } public bool HasCustomAttributes { get { if (custom_attributes != null) { return custom_attributes.Count > 0; } return this.GetHasCustomAttributes(main_module); } } public Collection<CustomAttribute> CustomAttributes => custom_attributes ?? this.GetCustomAttributes(ref custom_attributes, main_module); public bool HasSecurityDeclarations { get { if (security_declarations != null) { return security_declarations.Count > 0; } return this.GetHasSecurityDeclarations(main_module); } } public Collection<SecurityDeclaration> SecurityDeclarations => security_declarations ?? this.GetSecurityDeclarations(ref security_declarations, main_module); internal AssemblyDefinition() { } public void Dispose() { if (modules == null) { main_module.Dispose(); return; } Collection<ModuleDefinition> collection = Modules; for (int i = 0; i < collection.Count; i++) { collection[i].Dispose(); } } public static AssemblyDefinition CreateAssembly(AssemblyNameDefinition assemblyName, string moduleName, ModuleKind kind) { return CreateAssembly(assemblyName, moduleName, new ModuleParameters { Kind = kind }); } public static AssemblyDefinition CreateAssembly(AssemblyNameDefinition assemblyName, string moduleName, ModuleParameters parameters) { if (assemblyName == null) { throw new ArgumentNullException("assemblyName"); } if (moduleName == null) { throw new ArgumentNullException("moduleName"); } Mixin.CheckParameters(parameters); if (parameters.Kind == ModuleKind.NetModule) { throw new ArgumentException("kind"); } AssemblyDefinition assembly = ModuleDefinition.CreateModule(moduleName, parameters).Assembly; assembly.Name = assemblyName; return assembly; } public static AssemblyDefinition ReadAssembly(string fileName) { return ReadAssembly(ModuleDefinition.ReadModule(fileName)); } public static AssemblyDefinition ReadAssembly(string fileName, ReaderParameters parameters) { return ReadAssembly(ModuleDefinition.ReadModule(fileName, parameters)); } public static AssemblyDefinition ReadAssembly(Stream stream) { return ReadAssembly(ModuleDefinition.ReadModule(stream)); } public static AssemblyDefinition ReadAssembly(Stream stream, ReaderParameters parameters) { return ReadAssembly(ModuleDefinition.ReadModule(stream, parameters)); } private static AssemblyDefinition ReadAssembly(ModuleDefinition module) { return module.Assembly ?? throw new ArgumentException(); } public void Write(string fileName) { Write(fileName, new WriterParameters()); } public void Write(string fileName, WriterParameters parameters) { main_module.Write(fileName, parameters); } public void Write() { main_module.Write(); } public void Write(WriterParameters parameters) { main_module.Write(parameters); } public void Write(Stream stream) { Write(stream, new WriterParameters()); } public void Write(Stream stream, WriterParameters parameters) { main_module.Write(stream, parameters); } public override string ToString() { return FullName; } } [Flags] public enum AssemblyAttributes : uint { PublicKey = 1u, SideBySideCompatible = 0u, Retargetable = 0x100u, WindowsRuntime = 0x200u, DisableJITCompileOptimizer = 0x4000u, EnableJITCompileTracking = 0x8000u } public enum AssemblyHashAlgorithm : uint { None = 0u, Reserved = 32771u, SHA1 = 32772u } public sealed class AssemblyLinkedResource : Resource { private AssemblyNameReference reference; public AssemblyNameReference Assembly { get { return reference; } set { reference = value; } } public override ResourceType ResourceType => ResourceType.AssemblyLinked; public AssemblyLinkedResource(string name, ManifestResourceAttributes flags) : base(name, flags) { } public AssemblyLinkedResource(string name, ManifestResourceAttributes flags, AssemblyNameReference reference) : base(name, flags) { this.reference = reference; } } public sealed class AssemblyNameDefinition : AssemblyNameReference { public override byte[] Hash => Empty<byte>.Array; internal AssemblyNameDefinition() { token = new MetadataToken(TokenType.Assembly, 1); } public AssemblyNameDefinition(string name, Version version) : base(name, version) { token = new MetadataToken(TokenType.Assembly, 1); } } public class AssemblyNameReference : IMetadataScope, IMetadataTokenProvider { private string name; private string culture; private Version version; private uint attributes; private byte[] public_key; private byte[] public_key_token; private AssemblyHashAlgorithm hash_algorithm; private byte[] hash; internal MetadataToken token; private string full_name; public string Name { get { return name; } set { name = value; full_name = null; } } public string Culture { get { return culture; } set { culture = value; full_name = null; } } public Version Version { get { return version; } set { version = Mixin.CheckVersion(value); full_name = null; } } public AssemblyAttributes Attributes { get { return (AssemblyAttributes)attributes; } set { attributes = (uint)value; } } public bool HasPublicKey { get { return attributes.GetAttributes(1u); } set { attributes = attributes.SetAttributes(1u, value); } } public bool IsSideBySideCompatible { get { return attributes.GetAttributes(0u); } set { attributes = attributes.SetAttributes(0u, value); } } public bool IsRetargetable { get { return attributes.GetAttributes(256u); } set { attributes = attributes.SetAttributes(256u, value); } } public bool IsWindowsRuntime { get { return attributes.GetAttributes(512u); } set { attributes = attributes.SetAttributes(512u, value); } } public byte[] PublicKey { get { return public_key ?? Empty<byte>.Array; } set { public_key = value; HasPublicKey = !public_key.IsNullOrEmpty(); public_key_token = Empty<byte>.Array; full_name = null; } } public byte[] PublicKeyToken { get { if (public_key_token.IsNullOrEmpty() && !public_key.IsNullOrEmpty()) { byte[] array = HashPublicKey(); byte[] array2 = new byte[8]; Array.Copy(array, array.Length - 8, array2, 0, 8); Array.Reverse((Array)array2, 0, 8); public_key_token = array2; } return public_key_token ?? Empty<byte>.Array; } set { public_key_token = value; full_name = null; } } public virtual MetadataScopeType MetadataScopeType => MetadataScopeType.AssemblyNameReference; public string FullName { get { if (full_name != null) { return full_name; } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(name); stringBuilder.Append(", "); stringBuilder.Append("Version="); stringBuilder.Append(version.ToString(4)); stringBuilder.Append(", "); stringBuilder.Append("Culture="); stringBuilder.Append(string.IsNullOrEmpty(culture) ? "neutral" : culture); stringBuilder.Append(", "); stringBuilder.Append("PublicKeyToken="); byte[] publicKeyToken = PublicKeyToken; if (!publicKeyToken.IsNullOrEmpty() && publicKeyToken.Length != 0) { for (int i = 0; i < publicKeyToken.Length; i++) { stringBuilder.Append(publicKeyToken[i].ToString("x2")); } } else { stringBuilder.Append("null"); } if (IsRetargetable) { stringBuilder.Append(", "); stringBuilder.Append("Retargetable=Yes"); } return full_name = stringBuilder.ToString(); } } public AssemblyHashAlgorithm HashAlgorithm { get { return hash_algorithm; } set { hash_algorithm = value; } } public virtual byte[] Hash { get { return hash; } set { hash = value; } } public MetadataToken MetadataToken { get { return token; } set { token = value; } } private byte[] HashPublicKey() { AssemblyHashAlgorithm assemblyHashAlgorithm = hash_algorithm; HashAlgorithm hashAlgorithm = ((assemblyHashAlgorithm != AssemblyHashAlgorithm.Reserved) ? ((HashAlgorithm)SHA1.Create()) : ((HashAlgorithm)MD5.Create())); using (hashAlgorithm) { return hashAlgorithm.ComputeHash(public_key); } } public static AssemblyNameReference Parse(string fullName) { if (fullName == null) { throw new ArgumentNullException("fullName"); } if (fullName.Length == 0) { throw new ArgumentException("Name can not be empty"); } AssemblyNameReference assemblyNameReference = new AssemblyNameReference(); string[] array = fullName.Split(new char[1] { ',' }); for (int i = 0; i < array.Length; i++) { string text = array[i].Trim(); if (i == 0) { assemblyNameReference.Name = text; continue; } string[] array2 = text.Split(new char[1] { '=' }); if (array2.Length != 2) { throw new ArgumentException("Malformed name"); } switch (array2[0].ToLowerInvariant()) { case "version": assemblyNameReference.Version = new Version(array2[1]); break; case "culture": assemblyNameReference.Culture = ((array2[1] == "neutral") ? "" : array2[1]); break; case "publickeytoken": { string text2 = array2[1]; if (!(text2 == "null")) { assemblyNameReference.PublicKeyToken = new byte[text2.Length / 2]; for (int j = 0; j < assemblyNameReference.PublicKeyToken.Length; j++) { assemblyNameReference.PublicKeyToken[j] = byte.Parse(text2.Substring(j * 2, 2), NumberStyles.HexNumber); } } break; } } } return assemblyNameReference; } internal AssemblyNameReference() { version = Mixin.ZeroVersion; token = new MetadataToken(TokenType.AssemblyRef); } public AssemblyNameReference(string name, Version version) { Mixin.CheckName(name); this.name = name; this.version = Mixin.CheckVersion(version); hash_algorithm = AssemblyHashAlgorithm.None; token = new MetadataToken(TokenType.AssemblyRef); } public override string ToString() { return FullName; } } internal abstract class ModuleReader { protected readonly ModuleDefinition module; protected ModuleReader(Image image, ReadingMode mode) { module = new ModuleDefinition(image); module.ReadingMode = mode; } protected abstract void ReadModule(); public abstract void ReadSymbols(ModuleDefinition module); protected void ReadModuleManifest(MetadataReader reader) { reader.Populate(module); ReadAssembly(reader); } private void ReadAssembly(MetadataReader reader) { AssemblyNameDefinition assemblyNameDefinition = reader.ReadAssemblyNameDefinition(); if (assemblyNameDefinition == null) { module.kind = ModuleKind.NetModule; return; } AssemblyDefinition assemblyDefinition = new AssemblyDefinition(); assemblyDefinition.Name = assemblyNameDefinition; module.assembly = assemblyDefinition; assemblyDefinition.main_module = module; } public static ModuleDefinition CreateModule(Image image, ReaderParameters parameters) { ModuleReader moduleReader = CreateModuleReader(image, parameters.ReadingMode); ModuleDefinition moduleDefinition = moduleReader.module; if (parameters.assembly_resolver != null) { moduleDefinition.assembly_resolver = Disposable.NotOwned(parameters.assembly_resolver); } if (parameters.metadata_resolver != null) { moduleDefinition.metadata_resolver = parameters.metadata_resolver; } if (parameters.metadata_importer_provider != null) { moduleDefinition.metadata_importer = parameters.metadata_importer_provider.GetMetadataImporter(moduleDefinition); } if (parameters.reflection_importer_provider != null) { moduleDefinition.reflection_importer = parameters.reflection_importer_provider.GetReflectionImporter(moduleDefinition); } GetMetadataKind(moduleDefinition, parameters); moduleReader.ReadModule(); ReadSymbols(moduleDefinition, parameters); moduleReader.ReadSymbols(moduleDefinition); if (parameters.ReadingMode == ReadingMode.Immediate) { moduleDefinition.MetadataSystem.Clear(); } return moduleDefinition; } private static void ReadSymbols(ModuleDefinition module, ReaderParameters parameters) { ISymbolReaderProvider symbolReaderProvider = parameters.SymbolReaderProvider; if (symbolReaderProvider == null && parameters.ReadSymbols) { symbolReaderProvider = new DefaultSymbolReaderProvider(); } if (symbolReaderProvider != null) { module.SymbolReaderProvider = symbolReaderProvider; ISymbolReader symbolReader = ((parameters.SymbolStream != null) ? symbolReaderProvider.GetSymbolReader(module, parameters.SymbolStream) : symbolReaderProvider.GetSymbolReader(module, module.FileName)); if (symbolReader != null) { try { module.ReadSymbols(symbolReader, parameters.ThrowIfSymbolsAreNotMatching); } catch (Exception) { symbolReader.Dispose(); throw; } } } if (module.Image.HasDebugTables()) { module.ReadSymbols(new PortablePdbReader(module.Image, module)); } } private static void GetMetadataKind(ModuleDefinition module, ReaderParameters parameters) { if (!parameters.ApplyWindowsRuntimeProjections) { module.MetadataKind = MetadataKind.Ecma335; return; } string runtimeVersion = module.RuntimeVersion; if (!runtimeVersion.Contains("WindowsRuntime")) { module.MetadataKind = MetadataKind.Ecma335; } else if (runtimeVersion.Contains("CLR")) { module.MetadataKind = MetadataKind.ManagedWindowsMetadata; } else { module.MetadataKind = MetadataKind.WindowsMetadata; } } private static ModuleReader CreateModuleReader(Image image, ReadingMode mode) { return mode switch { ReadingMode.Immediate => new ImmediateModuleReader(image), ReadingMode.Deferred => new DeferredModuleReader(image), _ => throw new ArgumentException(), }; } } internal sealed class ImmediateModuleReader : ModuleReader { private bool resolve_attributes; public ImmediateModuleReader(Image image) : base(image, ReadingMode.Immediate) { } protected override void ReadModule() { module.Read(module, delegate(ModuleDefinition module, MetadataReader reader) { ReadModuleManifest(reader); ReadModule(module, resolve_attributes: true); }); } public void ReadModule(ModuleDefinition module, bool resolve_attributes) { this.resolve_attributes = resolve_attributes; if (module.HasAssemblyReferences) { Mixin.Read(module.AssemblyReferences); } if (module.HasResources) { Mixin.Read(module.Resources); } if (module.HasModuleReferences) { Mixin.Read(module.ModuleReferences); } if (module.HasTypes) { ReadTypes(module.Types); } if (module.HasExportedTypes) { Mixin.Read(module.ExportedTypes); } ReadCustomAttributes(module); AssemblyDefinition assembly = module.Assembly; if (assembly != null) { ReadCustomAttributes(assembly); ReadSecurityDeclarations(assembly); } } private void ReadTypes(Collection<TypeDefinition> types) { for (int i = 0; i < types.Count; i++) { ReadType(types[i]); } } private void ReadType(TypeDefinition type) { ReadGenericParameters(type); if (type.HasInterfaces) { ReadInterfaces(type); } if (type.HasNestedTypes) { ReadTypes(type.NestedTypes); } if (type.HasLayoutInfo) { Mixin.Read(type.ClassSize); } if (type.HasFields) { ReadFields(type); } if (type.HasMethods) { ReadMethods(type); } if (type.HasProperties) { ReadProperties(type); } if (type.HasEvents) { ReadEvents(type); } ReadSecurityDeclarations(type); ReadCustomAttributes(type); } private void ReadInterfaces(TypeDefinition type) { Collection<InterfaceImplementation> interfaces = type.Interfaces; for (int i = 0; i < interfaces.Count; i++) { ReadCustomAttributes(interfaces[i]); } } private void ReadGenericParameters(IGenericParameterProvider provider) { if (!provider.HasGenericParameters) { return; } Collection<GenericParameter> genericParameters = provider.GenericParameters; for (int i = 0; i < genericParameters.Count; i++) { GenericParameter genericParameter = genericParameters[i]; if (genericParameter.HasConstraints) { Mixin.Read(genericParameter.Constraints); } ReadCustomAttributes(genericParameter); } } private void ReadSecurityDeclarations(ISecurityDeclarationProvider provider) { if (!provider.HasSecurityDeclarations) { return; } Collection<SecurityDeclaration> securityDeclarations = provider.SecurityDeclarations; if (resolve_attributes) { for (int i = 0; i < securityDeclarations.Count; i++) { Mixin.Read(securityDeclarations[i].SecurityAttributes); } } } private void ReadCustomAttributes(ICustomAttributeProvider provider) { if (!provider.HasCustomAttributes) { return; } Collection<CustomAttribute> customAttributes = provider.CustomAttributes; if (resolve_attributes) { for (int i = 0; i < customAttributes.Count; i++) { Mixin.Read(customAttributes[i].ConstructorArguments); } } } private void ReadFields(TypeDefinition type) { Collection<FieldDefinition> fields = type.Fields; for (int i = 0; i < fields.Count; i++) { FieldDefinition fieldDefinition = fields[i]; if (fieldDefinition.HasConstant) { Mixin.Read(fieldDefinition.Constant); } if (fieldDefinition.HasLayoutInfo) { Mixin.Read(fieldDefinition.Offset); } if (fieldDefinition.RVA > 0) { Mixin.Read(fieldDefinition.InitialValue); } if (fieldDefinition.HasMarshalInfo) { Mixin.Read(fieldDefinition.MarshalInfo); } ReadCustomAttributes(fieldDefinition); } } private void ReadMethods(TypeDefinition type) { Collection<MethodDefinition> methods = type.Methods; for (int i = 0; i < methods.Count; i++) { MethodDefinition methodDefinition = methods[i]; ReadGenericParameters(methodDefinition); if (methodDefinition.HasParameters) { ReadParameters(methodDefinition); } if (methodDefinition.HasOverrides) { Mixin.Read(methodDefinition.Overrides); } if (methodDefinition.IsPInvokeImpl) { Mixin.Read(methodDefinition.PInvokeInfo); } ReadSecurityDeclarations(methodDefinition); ReadCustomAttributes(methodDefinition); MethodReturnType methodReturnType = methodDefinition.MethodReturnType; if (methodReturnType.HasConstant) { Mixin.Read(methodReturnType.Constant); } if (methodReturnType.HasMarshalInfo) { Mixin.Read(methodReturnType.MarshalInfo); } ReadCustomAttributes(methodReturnType); } } private void ReadParameters(MethodDefinition method) { Collection<ParameterDefinition> parameters = method.Parameters; for (int i = 0; i < parameters.Count; i++) { ParameterDefinition parameterDefinition = parameters[i]; if (parameterDefinition.HasConstant) { Mixin.Read(parameterDefinition.Constant); } if (parameterDefinition.HasMarshalInfo) { Mixin.Read(parameterDefinition.MarshalInfo); } ReadCustomAttributes(parameterDefinition); } } private void ReadProperties(TypeDefinition type) { Collection<PropertyDefinition> properties = type.Properties; for (int i = 0; i < properties.Count; i++) { PropertyDefinition propertyDefinition = properties[i]; Mixin.Read(propertyDefinition.GetMethod); if (propertyDefinition.HasConstant) { Mixin.Read(propertyDefinition.Constant); } ReadCustomAttributes(propertyDefinition); } } private void ReadEvents(TypeDefinition type) { Collection<EventDefinition> events = type.Events; for (int i = 0; i < events.Count; i++) { EventDefinition eventDefinition = events[i]; Mixin.Read(eventDefinition.AddMethod); ReadCustomAttributes(eventDefinition); } } public override void ReadSymbols(ModuleDefinition module) { if (module.symbol_reader != null) { ReadTypesSymbols(module.Types, module.symbol_reader); } } private void ReadTypesSymbols(Collection<TypeDefinition> types, ISymbolReader symbol_reader) { for (int i = 0; i < types.Count; i++) { TypeDefinition typeDefinition = types[i]; if (typeDefinition.HasNestedTypes) { ReadTypesSymbols(typeDefinition.NestedTypes, symbol_reader); } if (typeDefinition.HasMethods) { ReadMethodsSymbols(typeDefinition, symbol_reader); } } } private void ReadMethodsSymbols(TypeDefinition type, ISymbolReader symbol_reader) { Collection<MethodDefinition> methods = type.Methods; for (int i = 0; i < methods.Count; i++) { MethodDefinition methodDefinition = methods[i]; if (methodDefinition.HasBody && methodDefinition.token.RID != 0 && methodDefinition.debug_info == null) { methodDefinition.debug_info = symbol_reader.Read(methodDefinition); } } } } internal sealed class DeferredModuleReader : ModuleReader { public DeferredModuleReader(Image image) : base(image, ReadingMode.Deferred) { } protected override void ReadModule() { module.Read(module, delegate(ModuleDefinition _, MetadataReader reader) { ReadModuleManifest(reader); }); } public override void ReadSymbols(ModuleDefinition module) { } } internal sealed class MetadataReader : ByteBuffer { internal readonly Image image; internal readonly ModuleDefinition module; internal readonly MetadataSystem metadata; internal CodeReader code; internal IGenericContext context; private readonly MetadataReader metadata_reader; public MetadataReader(ModuleDefinition module) : base(module.Image.TableHeap.data) { image = module.Image; this.module = module; metadata = module.MetadataSystem; code = new CodeReader(this); } public MetadataReader(Image image, ModuleDefinition module, MetadataReader metadata_reader) : base(image.TableHeap.data) { this.image = image; this.module = module; metadata = module.MetadataSystem; this.metadata_reader = metadata_reader; } private int GetCodedIndexSize(CodedIndex index) { return image.GetCodedIndexSize(index); } private uint ReadByIndexSize(int size) { if (size == 4) { return ReadUInt32(); } return ReadUInt16(); } private byte[] ReadBlob() { BlobHeap blobHeap = image.BlobHeap; if (blobHeap == null) { position += 2; return Empty<byte>.Array; } return blobHeap.Read(ReadBlobIndex()); } private byte[] ReadBlob(uint signature) { BlobHeap blobHeap = image.BlobHeap; if (blobHeap == null) { return Empty<byte>.Array; } return blobHeap.Read(signature); } private uint ReadBlobIndex() { return ReadByIndexSize(image.BlobHeap?.IndexSize ?? 2); } private void GetBlobView(uint signature, out byte[] blob, out int index, out int count) { BlobHeap blobHeap = image.BlobHeap; if (blobHeap == null) { blob = null; index = (count = 0); } else { blobHeap.GetView(signature, out blob, out index, out count); } } private string ReadString() { return image.StringHeap.Read(ReadByIndexSize(image.StringHeap.IndexSize)); } private uint ReadStringIndex() { return ReadByIndexSize(image.StringHeap.IndexSize); } private Guid ReadGuid() { return image.GuidHeap.Read(ReadByIndexSize(image.GuidHeap.IndexSize)); } private uint ReadTableIndex(Table table) { return ReadByIndexSize(image.GetTableIndexSize(table)); } private MetadataToken ReadMetadataToken(CodedIndex index) { return index.GetMetadataToken(ReadByIndexSize(GetCodedIndexSize(index))); } private int MoveTo(Table table) { TableInformation tableInformation = image.TableHeap[table]; if (tableInformation.Length != 0) { position = (int)tableInformation.Offset; } return (int)tableInformation.Length; } private bool MoveTo(Table table, uint row) { TableInformation tableInformation = image.TableHeap[table]; uint num = tableInformation.Length; if (num == 0 || row > num) { return false; } position = (int)(tableInformation.Offset + tableInformation.RowSize * (row - 1)); return true; } public AssemblyNameDefinition ReadAssemblyNameDefinition() { if (MoveTo(Table.Assembly) == 0) { return null; } AssemblyNameDefinition assemblyNameDefinition = new AssemblyNameDefinition(); assemblyNameDefinition.HashAlgorithm = (AssemblyHashAlgorithm)ReadUInt32(); PopulateVersionAndFlags(assemblyNameDefinition); assemblyNameDefinition.PublicKey = ReadBlob(); PopulateNameAndCulture(assemblyNameDefinition); return assemblyNameDefinition; } public ModuleDefinition Populate(ModuleDefinition module) { if (MoveTo(Table.Module) == 0) { return module; } Advance(2); module.Name = ReadString(); module.Mvid = ReadGuid(); return module; } private void InitializeAssemblyReferences() { if (metadata.AssemblyReferences != null) { return; } int num = MoveTo(Table.AssemblyRef); AssemblyNameReference[] array = (metadata.AssemblyReferences = new AssemblyNameReference[num]); for (uint num2 = 0u; num2 < num; num2++) { AssemblyNameReference assemblyNameReference = new AssemblyNameReference(); assemblyNameReference.token = new MetadataToken(TokenType.AssemblyRef, num2 + 1); PopulateVersionAndFlags(assemblyNameReference); byte[] array2 = ReadBlob(); if (assemblyNameReference.HasPublicKey) { assemblyNameReference.PublicKey = array2; } else { assemblyNameReference.PublicKeyToken = array2; } PopulateNameAndCulture(assemblyNameReference); assemblyNameReference.Hash = ReadBlob(); array[num2] = assemblyNameReference; } } public Collection<AssemblyNameReference> ReadAssemblyReferences() { InitializeAssemblyReferences(); Collection<AssemblyNameReference> collection = new Collection<AssemblyNameReference>(metadata.AssemblyReferences); if (module.IsWindowsMetadata()) { module.Projections.AddVirtualReferences(collection); } return collection; } public MethodDefinition ReadEntryPoint() { if (module.Image.EntryPointToken == 0) { return null; } return GetMethodDefinition(new MetadataToken(module.Image.EntryPointToken).RID); } public Collection<ModuleDefinition> ReadModules() { Collection<ModuleDefinition> collection = new Collection<ModuleDefinition>(1); collection.Add(module); int num = MoveTo(Table.File); for (uint num2 = 1u; num2 <= num; num2++) { uint num3 = ReadUInt32(); string name = ReadString(); ReadBlobIndex(); if (num3 == 0) { ReaderParameters parameters = new ReaderParameters { ReadingMode = module.ReadingMode, SymbolReaderProvider = module.SymbolReaderProvider, AssemblyResolver = module.AssemblyResolver }; collection.Add(ModuleDefinition.ReadModule(GetModuleFileName(name), parameters)); } } return collection; } private string GetModuleFileName(string name) { if (module.FileName == null) { throw new NotSupportedException(); } return Path.Combine(Path.GetDirectoryName(module.FileName), name); } private void InitializeModuleReferences() { if (metadata.ModuleReferences == null) { int num = MoveTo(Table.ModuleRef); ModuleReference[] array = (metadata.ModuleReferences = new ModuleReference[num]); for (uint num2 = 0u; num2 < num; num2++) { ModuleReference moduleReference = new ModuleReference(ReadString()); moduleReference.token = new MetadataToken(TokenType.ModuleRef, num2 + 1); array[num2] = moduleReference; } } } public Collection<ModuleReference> ReadModuleReferences() { InitializeModuleReferences(); return new Collection<ModuleReference>(metadata.ModuleReferences); } public bool HasFileResource() { int num = MoveTo(Table.File); if (num == 0) { return false; } for (uint num2 = 1u; num2 <= num; num2++) { if (ReadFileRecord(num2).Col1 == FileAttributes.ContainsNoMetaData) { return true; } } return false; } public Collection<Resource> ReadResources() { int num = MoveTo(Table.ManifestResource); Collection<Resource> collection = new Collection<Resource>(num); for (int i = 1; i <= num; i++) { uint offset = ReadUInt32(); ManifestResourceAttributes manifestResourceAttributes = (ManifestResourceAttributes)ReadUInt32(); string name = ReadString(); MetadataToken scope = ReadMetadataToken(CodedIndex.Implementation); Resource item; if (scope.RID == 0) { item = new EmbeddedResource(name, manifestResourceAttributes, offset, this); } else if (scope.TokenType == TokenType.AssemblyRef) { item = new AssemblyLinkedResource(name, manifestResourceAttributes) { Assembly = (AssemblyNameReference)GetTypeReferenceScope(scope) }; } else { if (scope.TokenType != TokenType.File) { continue; } Row<FileAttributes, string, uint> row = ReadFileRecord(scope.RID); item = new LinkedResource(name, manifestResourceAttributes) { File = row.Col2, hash = ReadBlob(row.Col3) }; } collection.Add(item); } return collection; } private Row<FileAttributes, string, uint> ReadFileRecord(uint rid) { int num = position; if (!MoveTo(Table.File, rid)) { throw new ArgumentException(); } Row<FileAttributes, string, uint> result = new Row<FileAttributes, string, uint>((FileAttributes)ReadUInt32(), ReadString(), ReadBlobIndex()); position = num; return result; } public byte[] GetManagedResource(uint offset) { return image.GetReaderAt(image.Resources.VirtualAddress, offset, delegate(uint o, BinaryStreamReader reader) { reader.Advance((int)o); return reader.ReadBytes(reader.ReadInt32()); }) ?? Empty<byte>.Array; } private void PopulateVersionAndFlags(AssemblyNameReference name) { name.Version = new Version(ReadUInt16(), ReadUInt16(), ReadUInt16(), ReadUInt16()); name.Attributes = (AssemblyAttributes)ReadUInt32(); } private void PopulateNameAndCulture(AssemblyNameReference name) { name.Name = ReadString(); name.Culture = ReadString(); } public TypeDefinitionCollection ReadTypes() { InitializeTypeDefinitions(); TypeDefinition[] types = metadata.Types; int capacity = types.Length - metadata.NestedTypes.Count; TypeDefinitionCollection typeDefinitionCollection = new TypeDefinitionCollection(module, capacity); foreach (TypeDefinition typeDefinition in types) { if (!IsNested(typeDefinition.Attributes)) { typeDefinitionCollection.Add(typeDefinition); } } if (image.HasTable(Table.MethodPtr) || image.HasTable(Table.FieldPtr)) { CompleteTypes(); } return typeDefinitionCollection; } private void CompleteTypes() { TypeDefinition[] types = metadata.Types; foreach (TypeDefinition obj in types) { Mixin.Read(obj.Fields); Mixin.Read(obj.Methods); } } private void InitializeTypeDefinitions() { if (metadata.Types != null) { return; } InitializeNestedTypes(); InitializeFields(); InitializeMethods(); int num = MoveTo(Table.TypeDef); TypeDefinition[] array = (metadata.Types = new TypeDefinition[num]); for (uint num2 = 0u; num2 < num; num2++) { if (array[num2] == null) { array[num2] = ReadType(num2 + 1); } } if (module.IsWindowsMetadata()) { for (uint num3 = 0u; num3 < num; num3++) { WindowsRuntimeProjections.Project(array[num3]); } } } private static bool IsNested(TypeAttributes attributes) { switch (attributes & TypeAttributes.VisibilityMask) { case TypeAttributes.NestedPublic: case TypeAttributes.NestedPrivate: case TypeAttributes.NestedFamily: case TypeAttributes.NestedAssembly: case TypeAttributes.NestedFamANDAssem: case TypeAttributes.VisibilityMask: return true; default: return false; } } public bool HasNestedTypes(TypeDefinition type) { InitializeNestedTypes(); if (!metadata.TryGetNestedTypeMapping(type, out var mapping)) { return false; } return mapping.Count > 0; } public Collection<TypeDefinition> ReadNestedTypes(TypeDefinition type) { InitializeNestedTypes(); if (!metadata.TryGetNestedTypeMapping(type, out var mapping)) { return new MemberDefinitionCollection<TypeDefinition>(type); } MemberDefinitionCollection<TypeDefinition> memberDefinitionCollection = new MemberDefinitionCollection<TypeDefinition>(type, mapping.Count); for (int i = 0; i < mapping.Count; i++) { TypeDefinition typeDefinition = GetTypeDefinition(mapping[i]); if (typeDefinition != null) { memberDefinitionCollection.Add(typeDefinition); } } metadata.RemoveNestedTypeMapping(type); return memberDefinitionCollection; } private void InitializeNestedTypes() { if (metadata.NestedTypes != null) { return; } int num = MoveTo(Table.NestedClass); metadata.NestedTypes = new Dictionary<uint, Collection<uint>>(num); metadata.ReverseNestedTypes = new Dictionary<uint, uint>(num); if (num != 0) { for (int i = 1; i <= num; i++) { uint nested = ReadTableIndex(Table.TypeDef); uint declaring = ReadTableIndex(Table.TypeDef); AddNestedMapping(declaring, nested); } } } private void AddNestedMapping(uint declaring, uint nested) { metadata.SetNestedTypeMapping(declaring, AddMapping(metadata.NestedTypes, declaring, nested)); metadata.SetReverseNestedTypeMapping(nested, declaring); } private static Collection<TValue> AddMapping<TKey, TValue>(Dictionary<TKey, Collection<TValue>> cache, TKey key, TValue value) { if (!cache.TryGetValue(key, out var value2)) { value2 = new Collection<TValue>(); } value2.Add(value); return value2; } private TypeDefinition ReadType(uint rid) { if (!MoveTo(Table.TypeDef, rid)) { return null; } TypeAttributes attributes = (TypeAttributes)ReadUInt32(); string name = ReadString(); TypeDefinition typeDefinition = new TypeDefinition(ReadString(), name, attributes); typeDefinition.token = new MetadataToken(TokenType.TypeDef, rid); typeDefinition.scope = module; typeDefinition.module = module; metadata.AddTypeDefinition(typeDefinition); context = typeDefinition; typeDefinition.BaseType = GetTypeDefOrRef(ReadMetadataToken(CodedIndex.TypeDefOrRef)); typeDefinition.fields_range = ReadListRange(rid, Table.TypeDef, Table.Field); typeDefinition.methods_range = ReadListRange(rid, Table.TypeDef, Table.Method); if (IsNested(attributes)) { typeDefinition.DeclaringType = GetNestedTypeDeclaringType(typeDefinition); } return typeDefinition; } private TypeDefinition GetNestedTypeDeclaringType(TypeDefinition type) { if (!metadata.TryGetReverseNestedTypeMapping(type, out var declaring)) { return null; } metadata.RemoveReverseNestedTypeMapping(type); return GetTypeDefinition(declaring); } private Range ReadListRange(uint current_index, Table current, Table target) { Range result = default(Range); uint num = ReadTableIndex(target); if (num == 0) { return result; } TableInformation tableInformation = image.TableHeap[current]; uint num2; if (current_index == tableInformation.Length) { num2 = image.TableHeap[target].Length + 1; } else { int num3 = position; position += (int)(tableInformation.RowSize - image.GetTableIndexSize(target)); num2 = ReadTableIndex(target); position = num3; } result.Start = num; result.Length = num2 - num; return result; } public Row<short, int> ReadTypeLayout(TypeDefinition type) { InitializeTypeLayouts(); uint rID = type.token.RID; if (!metadata.ClassLayouts.TryGetValue(rID, out var value)) { return new Row<short, int>(-1, -1); } type.PackingSize = (short)value.Col1; type.ClassSize = (int)value.Col2; metadata.ClassLayouts.Remove(rID); return new Row<short, int>((short)value.Col1, (int)value.Col2); } private void InitializeTypeLayouts() { if (metadata.ClassLayouts == null) { int num = MoveTo(Table.ClassLayout); Dictionary<uint, Row<ushort, uint>> dictionary = (metadata.ClassLayouts = new Dictionary<uint, Row<ushort, uint>>(num)); for (uint num2 = 0u;
BepInExPack\BepInEx\core\Mono.Cecil.Mdb.dll
Decompiled 2 months agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.SymbolStore; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; using Mono.Cecil.Cil; using Mono.Collections.Generic; using Mono.CompilerServices.SymbolWriter; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyProduct("Mono.Cecil")] [assembly: AssemblyCopyright("Copyright © 2008 - 2018 Jb Evain")] [assembly: ComVisible(false)] [assembly: AssemblyFileVersion("0.10.4.0")] [assembly: AssemblyInformationalVersion("0.10.4.0")] [assembly: AssemblyTitle("Mono.Cecil.Mdb")] [assembly: CLSCompliant(false)] [assembly: AssemblyVersion("0.10.4.0")] namespace Mono.CompilerServices.SymbolWriter { public class MonoSymbolFileException : Exception { public MonoSymbolFileException() { } public MonoSymbolFileException(string message, params object[] args) : base(string.Format(message, args)) { } public MonoSymbolFileException(string message, Exception innerException) : base(message, innerException) { } } internal sealed class MyBinaryWriter : BinaryWriter { public MyBinaryWriter(Stream stream) : base(stream) { } public void WriteLeb128(int value) { Write7BitEncodedInt(value); } } internal class MyBinaryReader : BinaryReader { public MyBinaryReader(Stream stream) : base(stream) { } public int ReadLeb128() { return Read7BitEncodedInt(); } public string ReadString(int offset) { long position = BaseStream.Position; BaseStream.Position = offset; string result = ReadString(); BaseStream.Position = position; return result; } } public interface ISourceFile { SourceFileEntry Entry { get; } } public interface ICompileUnit { CompileUnitEntry Entry { get; } } public interface IMethodDef { string Name { get; } int Token { get; } } public class MonoSymbolFile : IDisposable { private List<MethodEntry> methods = new List<MethodEntry>(); private List<SourceFileEntry> sources = new List<SourceFileEntry>(); private List<CompileUnitEntry> comp_units = new List<CompileUnitEntry>(); private Dictionary<int, AnonymousScopeEntry> anonymous_scopes; private OffsetTable ot; private int last_type_index; private int last_method_index; private int last_namespace_index; public readonly int MajorVersion = 50; public readonly int MinorVersion; public int NumLineNumbers; private MyBinaryReader reader; private Dictionary<int, SourceFileEntry> source_file_hash; private Dictionary<int, CompileUnitEntry> compile_unit_hash; private List<MethodEntry> method_list; private Dictionary<int, MethodEntry> method_token_hash; private Dictionary<string, int> source_name_hash; private Guid guid; internal int LineNumberCount; internal int LocalCount; internal int StringSize; internal int LineNumberSize; internal int ExtendedLineNumberSize; public int CompileUnitCount => ot.CompileUnitCount; public int SourceCount => ot.SourceCount; public int MethodCount => ot.MethodCount; public int TypeCount => ot.TypeCount; public int AnonymousScopeCount => ot.AnonymousScopeCount; public int NamespaceCount => last_namespace_index; public Guid Guid => guid; public OffsetTable OffsetTable => ot; public SourceFileEntry[] Sources { get { if (reader == null) { throw new InvalidOperationException(); } SourceFileEntry[] array = new SourceFileEntry[SourceCount]; for (int i = 0; i < SourceCount; i++) { array[i] = GetSourceFile(i + 1); } return array; } } public CompileUnitEntry[] CompileUnits { get { if (reader == null) { throw new InvalidOperationException(); } CompileUnitEntry[] array = new CompileUnitEntry[CompileUnitCount]; for (int i = 0; i < CompileUnitCount; i++) { array[i] = GetCompileUnit(i + 1); } return array; } } public MethodEntry[] Methods { get { if (reader == null) { throw new InvalidOperationException(); } lock (this) { read_methods(); MethodEntry[] array = new MethodEntry[MethodCount]; method_list.CopyTo(array, 0); return array; } } } internal MyBinaryReader BinaryReader { get { if (reader == null) { throw new InvalidOperationException(); } return reader; } } public MonoSymbolFile() { ot = new OffsetTable(); } public int AddSource(SourceFileEntry source) { sources.Add(source); return sources.Count; } public int AddCompileUnit(CompileUnitEntry entry) { comp_units.Add(entry); return comp_units.Count; } public void AddMethod(MethodEntry entry) { methods.Add(entry); } public MethodEntry DefineMethod(CompileUnitEntry comp_unit, int token, ScopeVariable[] scope_vars, LocalVariableEntry[] locals, LineNumberEntry[] lines, CodeBlockEntry[] code_blocks, string real_name, MethodEntry.Flags flags, int namespace_id) { if (reader != null) { throw new InvalidOperationException(); } MethodEntry methodEntry = new MethodEntry(this, comp_unit, token, scope_vars, locals, lines, code_blocks, real_name, flags, namespace_id); AddMethod(methodEntry); return methodEntry; } internal void DefineAnonymousScope(int id) { if (reader != null) { throw new InvalidOperationException(); } if (anonymous_scopes == null) { anonymous_scopes = new Dictionary<int, AnonymousScopeEntry>(); } anonymous_scopes.Add(id, new AnonymousScopeEntry(id)); } internal void DefineCapturedVariable(int scope_id, string name, string captured_name, CapturedVariable.CapturedKind kind) { if (reader != null) { throw new InvalidOperationException(); } anonymous_scopes[scope_id].AddCapturedVariable(name, captured_name, kind); } internal void DefineCapturedScope(int scope_id, int id, string captured_name) { if (reader != null) { throw new InvalidOperationException(); } anonymous_scopes[scope_id].AddCapturedScope(id, captured_name); } internal int GetNextTypeIndex() { return ++last_type_index; } internal int GetNextMethodIndex() { return ++last_method_index; } internal int GetNextNamespaceIndex() { return ++last_namespace_index; } private void Write(MyBinaryWriter bw, Guid guid) { bw.Write(5037318119232611860L); bw.Write(MajorVersion); bw.Write(MinorVersion); bw.Write(guid.ToByteArray()); long position = bw.BaseStream.Position; ot.Write(bw, MajorVersion, MinorVersion); methods.Sort(); for (int i = 0; i < methods.Count; i++) { methods[i].Index = i + 1; } ot.DataSectionOffset = (int)bw.BaseStream.Position; foreach (SourceFileEntry source in sources) { source.WriteData(bw); } foreach (CompileUnitEntry comp_unit in comp_units) { comp_unit.WriteData(bw); } foreach (MethodEntry method in methods) { method.WriteData(this, bw); } ot.DataSectionSize = (int)bw.BaseStream.Position - ot.DataSectionOffset; ot.MethodTableOffset = (int)bw.BaseStream.Position; for (int j = 0; j < methods.Count; j++) { methods[j].Write(bw); } ot.MethodTableSize = (int)bw.BaseStream.Position - ot.MethodTableOffset; ot.SourceTableOffset = (int)bw.BaseStream.Position; for (int k = 0; k < sources.Count; k++) { sources[k].Write(bw); } ot.SourceTableSize = (int)bw.BaseStream.Position - ot.SourceTableOffset; ot.CompileUnitTableOffset = (int)bw.BaseStream.Position; for (int l = 0; l < comp_units.Count; l++) { comp_units[l].Write(bw); } ot.CompileUnitTableSize = (int)bw.BaseStream.Position - ot.CompileUnitTableOffset; ot.AnonymousScopeCount = ((anonymous_scopes != null) ? anonymous_scopes.Count : 0); ot.AnonymousScopeTableOffset = (int)bw.BaseStream.Position; if (anonymous_scopes != null) { foreach (AnonymousScopeEntry value in anonymous_scopes.Values) { value.Write(bw); } } ot.AnonymousScopeTableSize = (int)bw.BaseStream.Position - ot.AnonymousScopeTableOffset; ot.TypeCount = last_type_index; ot.MethodCount = methods.Count; ot.SourceCount = sources.Count; ot.CompileUnitCount = comp_units.Count; ot.TotalFileSize = (int)bw.BaseStream.Position; bw.Seek((int)position, SeekOrigin.Begin); ot.Write(bw, MajorVersion, MinorVersion); bw.Seek(0, SeekOrigin.End); } public void CreateSymbolFile(Guid guid, FileStream fs) { if (reader != null) { throw new InvalidOperationException(); } Write(new MyBinaryWriter(fs), guid); } private MonoSymbolFile(Stream stream) { reader = new MyBinaryReader(stream); try { long num = reader.ReadInt64(); int num2 = reader.ReadInt32(); int num3 = reader.ReadInt32(); if (num != 5037318119232611860L) { throw new MonoSymbolFileException("Symbol file is not a valid"); } if (num2 != 50) { throw new MonoSymbolFileException("Symbol file has version {0} but expected {1}", num2, 50); } if (num3 != 0) { throw new MonoSymbolFileException("Symbol file has version {0}.{1} but expected {2}.{3}", num2, num3, 50, 0); } MajorVersion = num2; MinorVersion = num3; guid = new Guid(reader.ReadBytes(16)); ot = new OffsetTable(reader, num2, num3); } catch (Exception innerException) { throw new MonoSymbolFileException("Cannot read symbol file", innerException); } source_file_hash = new Dictionary<int, SourceFileEntry>(); compile_unit_hash = new Dictionary<int, CompileUnitEntry>(); } public static MonoSymbolFile ReadSymbolFile(Assembly assembly) { string mdbFilename = assembly.Location + ".mdb"; Guid moduleVersionId = assembly.GetModules()[0].ModuleVersionId; return ReadSymbolFile(mdbFilename, moduleVersionId); } public static MonoSymbolFile ReadSymbolFile(string mdbFilename) { return ReadSymbolFile(new FileStream(mdbFilename, FileMode.Open, FileAccess.Read)); } public static MonoSymbolFile ReadSymbolFile(string mdbFilename, Guid assemblyGuid) { MonoSymbolFile monoSymbolFile = ReadSymbolFile(mdbFilename); if (assemblyGuid != monoSymbolFile.guid) { throw new MonoSymbolFileException("Symbol file `{0}' does not match assembly", mdbFilename); } return monoSymbolFile; } public static MonoSymbolFile ReadSymbolFile(Stream stream) { return new MonoSymbolFile(stream); } public SourceFileEntry GetSourceFile(int index) { if (index < 1 || index > ot.SourceCount) { throw new ArgumentException(); } if (reader == null) { throw new InvalidOperationException(); } lock (this) { if (source_file_hash.TryGetValue(index, out var value)) { return value; } long position = reader.BaseStream.Position; reader.BaseStream.Position = ot.SourceTableOffset + SourceFileEntry.Size * (index - 1); value = new SourceFileEntry(this, reader); source_file_hash.Add(index, value); reader.BaseStream.Position = position; return value; } } public CompileUnitEntry GetCompileUnit(int index) { if (index < 1 || index > ot.CompileUnitCount) { throw new ArgumentException(); } if (reader == null) { throw new InvalidOperationException(); } lock (this) { if (compile_unit_hash.TryGetValue(index, out var value)) { return value; } long position = reader.BaseStream.Position; reader.BaseStream.Position = ot.CompileUnitTableOffset + CompileUnitEntry.Size * (index - 1); value = new CompileUnitEntry(this, reader); compile_unit_hash.Add(index, value); reader.BaseStream.Position = position; return value; } } private void read_methods() { lock (this) { if (method_token_hash == null) { method_token_hash = new Dictionary<int, MethodEntry>(); method_list = new List<MethodEntry>(); long position = reader.BaseStream.Position; reader.BaseStream.Position = ot.MethodTableOffset; for (int i = 0; i < MethodCount; i++) { MethodEntry methodEntry = new MethodEntry(this, reader, i + 1); method_token_hash.Add(methodEntry.Token, methodEntry); method_list.Add(methodEntry); } reader.BaseStream.Position = position; } } } public MethodEntry GetMethodByToken(int token) { if (reader == null) { throw new InvalidOperationException(); } lock (this) { read_methods(); method_token_hash.TryGetValue(token, out var value); return value; } } public MethodEntry GetMethod(int index) { if (index < 1 || index > ot.MethodCount) { throw new ArgumentException(); } if (reader == null) { throw new InvalidOperationException(); } lock (this) { read_methods(); return method_list[index - 1]; } } public int FindSource(string file_name) { if (reader == null) { throw new InvalidOperationException(); } lock (this) { if (source_name_hash == null) { source_name_hash = new Dictionary<string, int>(); for (int i = 0; i < ot.SourceCount; i++) { SourceFileEntry sourceFile = GetSourceFile(i + 1); source_name_hash.Add(sourceFile.FileName, i); } } if (!source_name_hash.TryGetValue(file_name, out var value)) { return -1; } return value; } } public AnonymousScopeEntry GetAnonymousScope(int id) { if (reader == null) { throw new InvalidOperationException(); } lock (this) { if (anonymous_scopes != null) { anonymous_scopes.TryGetValue(id, out var value); return value; } anonymous_scopes = new Dictionary<int, AnonymousScopeEntry>(); reader.BaseStream.Position = ot.AnonymousScopeTableOffset; for (int i = 0; i < ot.AnonymousScopeCount; i++) { AnonymousScopeEntry value = new AnonymousScopeEntry(reader); anonymous_scopes.Add(value.ID, value); } return anonymous_scopes[id]; } } public void Dispose() { Dispose(disposing: true); } protected virtual void Dispose(bool disposing) { if (disposing && reader != null) { reader.Close(); reader = null; } } } public class OffsetTable { [Flags] public enum Flags { IsAspxSource = 1, WindowsFileNames = 2 } public const int MajorVersion = 50; public const int MinorVersion = 0; public const long Magic = 5037318119232611860L; public int TotalFileSize; public int DataSectionOffset; public int DataSectionSize; public int CompileUnitCount; public int CompileUnitTableOffset; public int CompileUnitTableSize; public int SourceCount; public int SourceTableOffset; public int SourceTableSize; public int MethodCount; public int MethodTableOffset; public int MethodTableSize; public int TypeCount; public int AnonymousScopeCount; public int AnonymousScopeTableOffset; public int AnonymousScopeTableSize; public Flags FileFlags; public int LineNumberTable_LineBase = -1; public int LineNumberTable_LineRange = 8; public int LineNumberTable_OpcodeBase = 9; internal OffsetTable() { int platform = (int)Environment.OSVersion.Platform; if (platform != 4 && platform != 128) { FileFlags |= Flags.WindowsFileNames; } } internal OffsetTable(BinaryReader reader, int major_version, int minor_version) { TotalFileSize = reader.ReadInt32(); DataSectionOffset = reader.ReadInt32(); DataSectionSize = reader.ReadInt32(); CompileUnitCount = reader.ReadInt32(); CompileUnitTableOffset = reader.ReadInt32(); CompileUnitTableSize = reader.ReadInt32(); SourceCount = reader.ReadInt32(); SourceTableOffset = reader.ReadInt32(); SourceTableSize = reader.ReadInt32(); MethodCount = reader.ReadInt32(); MethodTableOffset = reader.ReadInt32(); MethodTableSize = reader.ReadInt32(); TypeCount = reader.ReadInt32(); AnonymousScopeCount = reader.ReadInt32(); AnonymousScopeTableOffset = reader.ReadInt32(); AnonymousScopeTableSize = reader.ReadInt32(); LineNumberTable_LineBase = reader.ReadInt32(); LineNumberTable_LineRange = reader.ReadInt32(); LineNumberTable_OpcodeBase = reader.ReadInt32(); FileFlags = (Flags)reader.ReadInt32(); } internal void Write(BinaryWriter bw, int major_version, int minor_version) { bw.Write(TotalFileSize); bw.Write(DataSectionOffset); bw.Write(DataSectionSize); bw.Write(CompileUnitCount); bw.Write(CompileUnitTableOffset); bw.Write(CompileUnitTableSize); bw.Write(SourceCount); bw.Write(SourceTableOffset); bw.Write(SourceTableSize); bw.Write(MethodCount); bw.Write(MethodTableOffset); bw.Write(MethodTableSize); bw.Write(TypeCount); bw.Write(AnonymousScopeCount); bw.Write(AnonymousScopeTableOffset); bw.Write(AnonymousScopeTableSize); bw.Write(LineNumberTable_LineBase); bw.Write(LineNumberTable_LineRange); bw.Write(LineNumberTable_OpcodeBase); bw.Write((int)FileFlags); } public override string ToString() { return $"OffsetTable [{TotalFileSize} - {DataSectionOffset}:{DataSectionSize} - {SourceCount}:{SourceTableOffset}:{SourceTableSize} - {MethodCount}:{MethodTableOffset}:{MethodTableSize} - {TypeCount}]"; } } public class LineNumberEntry { public sealed class LocationComparer : IComparer<LineNumberEntry> { public static readonly LocationComparer Default = new LocationComparer(); public int Compare(LineNumberEntry l1, LineNumberEntry l2) { if (l1.Row != l2.Row) { int row = l1.Row; return row.CompareTo(l2.Row); } return l1.Column.CompareTo(l2.Column); } } public readonly int Row; public int Column; public int EndRow; public int EndColumn; public readonly int File; public readonly int Offset; public readonly bool IsHidden; public static readonly LineNumberEntry Null = new LineNumberEntry(0, 0, 0, 0); public LineNumberEntry(int file, int row, int column, int offset) : this(file, row, column, offset, is_hidden: false) { } public LineNumberEntry(int file, int row, int offset) : this(file, row, -1, offset, is_hidden: false) { } public LineNumberEntry(int file, int row, int column, int offset, bool is_hidden) : this(file, row, column, -1, -1, offset, is_hidden) { } public LineNumberEntry(int file, int row, int column, int end_row, int end_column, int offset, bool is_hidden) { File = file; Row = row; Column = column; EndRow = end_row; EndColumn = end_column; Offset = offset; IsHidden = is_hidden; } public override string ToString() { return $"[Line {File}:{Row},{Column}-{EndRow},{EndColumn}:{Offset}]"; } } public class CodeBlockEntry { public enum Type { Lexical = 1, CompilerGenerated, IteratorBody, IteratorDispatcher } public int Index; public int Parent; public Type BlockType; public int StartOffset; public int EndOffset; public CodeBlockEntry(int index, int parent, Type type, int start_offset) { Index = index; Parent = parent; BlockType = type; StartOffset = start_offset; } internal CodeBlockEntry(int index, MyBinaryReader reader) { Index = index; int num = reader.ReadLeb128(); BlockType = (Type)(num & 0x3F); Parent = reader.ReadLeb128(); StartOffset = reader.ReadLeb128(); EndOffset = reader.ReadLeb128(); if (((uint)num & 0x40u) != 0) { int num2 = reader.ReadInt16(); reader.BaseStream.Position += num2; } } public void Close(int end_offset) { EndOffset = end_offset; } internal void Write(MyBinaryWriter bw) { bw.WriteLeb128((int)BlockType); bw.WriteLeb128(Parent); bw.WriteLeb128(StartOffset); bw.WriteLeb128(EndOffset); } public override string ToString() { return $"[CodeBlock {Index}:{Parent}:{BlockType}:{StartOffset}:{EndOffset}]"; } } public struct LocalVariableEntry { public readonly int Index; public readonly string Name; public readonly int BlockIndex; public LocalVariableEntry(int index, string name, int block) { Index = index; Name = name; BlockIndex = block; } internal LocalVariableEntry(MonoSymbolFile file, MyBinaryReader reader) { Index = reader.ReadLeb128(); Name = reader.ReadString(); BlockIndex = reader.ReadLeb128(); } internal void Write(MonoSymbolFile file, MyBinaryWriter bw) { bw.WriteLeb128(Index); bw.Write(Name); bw.WriteLeb128(BlockIndex); } public override string ToString() { return $"[LocalVariable {Name}:{Index}:{BlockIndex - 1}]"; } } public struct CapturedVariable { public enum CapturedKind : byte { Local, Parameter, This } public readonly string Name; public readonly string CapturedName; public readonly CapturedKind Kind; public CapturedVariable(string name, string captured_name, CapturedKind kind) { Name = name; CapturedName = captured_name; Kind = kind; } internal CapturedVariable(MyBinaryReader reader) { Name = reader.ReadString(); CapturedName = reader.ReadString(); Kind = (CapturedKind)reader.ReadByte(); } internal void Write(MyBinaryWriter bw) { bw.Write(Name); bw.Write(CapturedName); bw.Write((byte)Kind); } public override string ToString() { return $"[CapturedVariable {Name}:{CapturedName}:{Kind}]"; } } public struct CapturedScope { public readonly int Scope; public readonly string CapturedName; public CapturedScope(int scope, string captured_name) { Scope = scope; CapturedName = captured_name; } internal CapturedScope(MyBinaryReader reader) { Scope = reader.ReadLeb128(); CapturedName = reader.ReadString(); } internal void Write(MyBinaryWriter bw) { bw.WriteLeb128(Scope); bw.Write(CapturedName); } public override string ToString() { return $"[CapturedScope {Scope}:{CapturedName}]"; } } public struct ScopeVariable { public readonly int Scope; public readonly int Index; public ScopeVariable(int scope, int index) { Scope = scope; Index = index; } internal ScopeVariable(MyBinaryReader reader) { Scope = reader.ReadLeb128(); Index = reader.ReadLeb128(); } internal void Write(MyBinaryWriter bw) { bw.WriteLeb128(Scope); bw.WriteLeb128(Index); } public override string ToString() { return $"[ScopeVariable {Scope}:{Index}]"; } } public class AnonymousScopeEntry { public readonly int ID; private List<CapturedVariable> captured_vars = new List<CapturedVariable>(); private List<CapturedScope> captured_scopes = new List<CapturedScope>(); public CapturedVariable[] CapturedVariables { get { CapturedVariable[] array = new CapturedVariable[captured_vars.Count]; captured_vars.CopyTo(array, 0); return array; } } public CapturedScope[] CapturedScopes { get { CapturedScope[] array = new CapturedScope[captured_scopes.Count]; captured_scopes.CopyTo(array, 0); return array; } } public AnonymousScopeEntry(int id) { ID = id; } internal AnonymousScopeEntry(MyBinaryReader reader) { ID = reader.ReadLeb128(); int num = reader.ReadLeb128(); for (int i = 0; i < num; i++) { captured_vars.Add(new CapturedVariable(reader)); } int num2 = reader.ReadLeb128(); for (int j = 0; j < num2; j++) { captured_scopes.Add(new CapturedScope(reader)); } } internal void AddCapturedVariable(string name, string captured_name, CapturedVariable.CapturedKind kind) { captured_vars.Add(new CapturedVariable(name, captured_name, kind)); } internal void AddCapturedScope(int scope, string captured_name) { captured_scopes.Add(new CapturedScope(scope, captured_name)); } internal void Write(MyBinaryWriter bw) { bw.WriteLeb128(ID); bw.WriteLeb128(captured_vars.Count); foreach (CapturedVariable captured_var in captured_vars) { captured_var.Write(bw); } bw.WriteLeb128(captured_scopes.Count); foreach (CapturedScope captured_scope in captured_scopes) { captured_scope.Write(bw); } } public override string ToString() { return $"[AnonymousScope {ID}]"; } } public class CompileUnitEntry : ICompileUnit { public readonly int Index; private int DataOffset; private MonoSymbolFile file; private SourceFileEntry source; private List<SourceFileEntry> include_files; private List<NamespaceEntry> namespaces; private bool creating; public static int Size => 8; CompileUnitEntry ICompileUnit.Entry => this; public SourceFileEntry SourceFile { get { if (creating) { return source; } ReadData(); return source; } } public NamespaceEntry[] Namespaces { get { ReadData(); NamespaceEntry[] array = new NamespaceEntry[namespaces.Count]; namespaces.CopyTo(array, 0); return array; } } public SourceFileEntry[] IncludeFiles { get { ReadData(); if (include_files == null) { return new SourceFileEntry[0]; } SourceFileEntry[] array = new SourceFileEntry[include_files.Count]; include_files.CopyTo(array, 0); return array; } } public CompileUnitEntry(MonoSymbolFile file, SourceFileEntry source) { this.file = file; this.source = source; Index = file.AddCompileUnit(this); creating = true; namespaces = new List<NamespaceEntry>(); } public void AddFile(SourceFileEntry file) { if (!creating) { throw new InvalidOperationException(); } if (include_files == null) { include_files = new List<SourceFileEntry>(); } include_files.Add(file); } public int DefineNamespace(string name, string[] using_clauses, int parent) { if (!creating) { throw new InvalidOperationException(); } int nextNamespaceIndex = file.GetNextNamespaceIndex(); NamespaceEntry item = new NamespaceEntry(name, nextNamespaceIndex, using_clauses, parent); namespaces.Add(item); return nextNamespaceIndex; } internal void WriteData(MyBinaryWriter bw) { DataOffset = (int)bw.BaseStream.Position; bw.WriteLeb128(source.Index); int value = ((include_files != null) ? include_files.Count : 0); bw.WriteLeb128(value); if (include_files != null) { foreach (SourceFileEntry include_file in include_files) { bw.WriteLeb128(include_file.Index); } } bw.WriteLeb128(namespaces.Count); foreach (NamespaceEntry @namespace in namespaces) { @namespace.Write(file, bw); } } internal void Write(BinaryWriter bw) { bw.Write(Index); bw.Write(DataOffset); } internal CompileUnitEntry(MonoSymbolFile file, MyBinaryReader reader) { this.file = file; Index = reader.ReadInt32(); DataOffset = reader.ReadInt32(); } public void ReadAll() { ReadData(); } private void ReadData() { if (creating) { throw new InvalidOperationException(); } lock (file) { if (namespaces != null) { return; } MyBinaryReader binaryReader = file.BinaryReader; int num = (int)binaryReader.BaseStream.Position; binaryReader.BaseStream.Position = DataOffset; int index = binaryReader.ReadLeb128(); source = file.GetSourceFile(index); int num2 = binaryReader.ReadLeb128(); if (num2 > 0) { include_files = new List<SourceFileEntry>(); for (int i = 0; i < num2; i++) { include_files.Add(file.GetSourceFile(binaryReader.ReadLeb128())); } } int num3 = binaryReader.ReadLeb128(); namespaces = new List<NamespaceEntry>(); for (int j = 0; j < num3; j++) { namespaces.Add(new NamespaceEntry(file, binaryReader)); } binaryReader.BaseStream.Position = num; } } } public class SourceFileEntry { public readonly int Index; private int DataOffset; private MonoSymbolFile file; private string file_name; private byte[] guid; private byte[] hash; private bool creating; private bool auto_generated; private readonly string sourceFile; public static int Size => 8; public byte[] Checksum => hash; public string FileName { get { return file_name; } set { file_name = value; } } public bool AutoGenerated => auto_generated; public SourceFileEntry(MonoSymbolFile file, string file_name) { this.file = file; this.file_name = file_name; Index = file.AddSource(this); creating = true; } public SourceFileEntry(MonoSymbolFile file, string sourceFile, byte[] guid, byte[] checksum) : this(file, sourceFile, sourceFile, guid, checksum) { } public SourceFileEntry(MonoSymbolFile file, string fileName, string sourceFile, byte[] guid, byte[] checksum) : this(file, fileName) { this.guid = guid; hash = checksum; this.sourceFile = sourceFile; } internal void WriteData(MyBinaryWriter bw) { DataOffset = (int)bw.BaseStream.Position; bw.Write(file_name); if (guid == null) { guid = new byte[16]; } if (hash == null) { try { using FileStream inputStream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read); MD5 mD = MD5.Create(); hash = mD.ComputeHash(inputStream); } catch { hash = new byte[16]; } } bw.Write(guid); bw.Write(hash); bw.Write((byte)(auto_generated ? 1u : 0u)); } internal void Write(BinaryWriter bw) { bw.Write(Index); bw.Write(DataOffset); } internal SourceFileEntry(MonoSymbolFile file, MyBinaryReader reader) { this.file = file; Index = reader.ReadInt32(); DataOffset = reader.ReadInt32(); int num = (int)reader.BaseStream.Position; reader.BaseStream.Position = DataOffset; sourceFile = (file_name = reader.ReadString()); guid = reader.ReadBytes(16); hash = reader.ReadBytes(16); auto_generated = reader.ReadByte() == 1; reader.BaseStream.Position = num; } public void SetAutoGenerated() { if (!creating) { throw new InvalidOperationException(); } auto_generated = true; file.OffsetTable.FileFlags |= OffsetTable.Flags.IsAspxSource; } public bool CheckChecksum() { try { using FileStream inputStream = new FileStream(sourceFile, FileMode.Open); byte[] array = MD5.Create().ComputeHash(inputStream); for (int i = 0; i < 16; i++) { if (array[i] != hash[i]) { return false; } } return true; } catch { return false; } } public override string ToString() { return $"SourceFileEntry ({Index}:{DataOffset})"; } } public class LineNumberTable { protected LineNumberEntry[] _line_numbers; public readonly int LineBase; public readonly int LineRange; public readonly byte OpcodeBase; public readonly int MaxAddressIncrement; public const int Default_LineBase = -1; public const int Default_LineRange = 8; public const byte Default_OpcodeBase = 9; public const byte DW_LNS_copy = 1; public const byte DW_LNS_advance_pc = 2; public const byte DW_LNS_advance_line = 3; public const byte DW_LNS_set_file = 4; public const byte DW_LNS_const_add_pc = 8; public const byte DW_LNE_end_sequence = 1; public const byte DW_LNE_MONO_negate_is_hidden = 64; internal const byte DW_LNE_MONO__extensions_start = 64; internal const byte DW_LNE_MONO__extensions_end = 127; public LineNumberEntry[] LineNumbers => _line_numbers; protected LineNumberTable(MonoSymbolFile file) { LineBase = file.OffsetTable.LineNumberTable_LineBase; LineRange = file.OffsetTable.LineNumberTable_LineRange; OpcodeBase = (byte)file.OffsetTable.LineNumberTable_OpcodeBase; MaxAddressIncrement = (255 - OpcodeBase) / LineRange; } internal LineNumberTable(MonoSymbolFile file, LineNumberEntry[] lines) : this(file) { _line_numbers = lines; } internal void Write(MonoSymbolFile file, MyBinaryWriter bw, bool hasColumnsInfo, bool hasEndInfo) { int num = (int)bw.BaseStream.Position; bool flag = false; int num2 = 1; int num3 = 0; int num4 = 1; for (int i = 0; i < LineNumbers.Length; i++) { int num5 = LineNumbers[i].Row - num2; int num6 = LineNumbers[i].Offset - num3; if (LineNumbers[i].File != num4) { bw.Write((byte)4); bw.WriteLeb128(LineNumbers[i].File); num4 = LineNumbers[i].File; } if (LineNumbers[i].IsHidden != flag) { bw.Write((byte)0); bw.Write((byte)1); bw.Write((byte)64); flag = LineNumbers[i].IsHidden; } if (num6 >= MaxAddressIncrement) { if (num6 < 2 * MaxAddressIncrement) { bw.Write((byte)8); num6 -= MaxAddressIncrement; } else { bw.Write((byte)2); bw.WriteLeb128(num6); num6 = 0; } } if (num5 < LineBase || num5 >= LineBase + LineRange) { bw.Write((byte)3); bw.WriteLeb128(num5); if (num6 != 0) { bw.Write((byte)2); bw.WriteLeb128(num6); } bw.Write((byte)1); } else { byte value = (byte)(num5 - LineBase + LineRange * num6 + OpcodeBase); bw.Write(value); } num2 = LineNumbers[i].Row; num3 = LineNumbers[i].Offset; } bw.Write((byte)0); bw.Write((byte)1); bw.Write((byte)1); if (hasColumnsInfo) { for (int j = 0; j < LineNumbers.Length; j++) { LineNumberEntry lineNumberEntry = LineNumbers[j]; if (lineNumberEntry.Row >= 0) { bw.WriteLeb128(lineNumberEntry.Column); } } } if (hasEndInfo) { for (int k = 0; k < LineNumbers.Length; k++) { LineNumberEntry lineNumberEntry2 = LineNumbers[k]; if (lineNumberEntry2.EndRow == -1 || lineNumberEntry2.EndColumn == -1 || lineNumberEntry2.Row > lineNumberEntry2.EndRow) { bw.WriteLeb128(16777215); continue; } bw.WriteLeb128(lineNumberEntry2.EndRow - lineNumberEntry2.Row); bw.WriteLeb128(lineNumberEntry2.EndColumn); } } file.ExtendedLineNumberSize += (int)bw.BaseStream.Position - num; } internal static LineNumberTable Read(MonoSymbolFile file, MyBinaryReader br, bool readColumnsInfo, bool readEndInfo) { LineNumberTable lineNumberTable = new LineNumberTable(file); lineNumberTable.DoRead(file, br, readColumnsInfo, readEndInfo); return lineNumberTable; } private void DoRead(MonoSymbolFile file, MyBinaryReader br, bool includesColumns, bool includesEnds) { List<LineNumberEntry> list = new List<LineNumberEntry>(); bool flag = false; bool flag2 = false; int num = 1; int num2 = 0; int file2 = 1; while (true) { byte b = br.ReadByte(); if (b == 0) { byte b2 = br.ReadByte(); long position = br.BaseStream.Position + b2; b = br.ReadByte(); switch (b) { case 1: { if (flag2) { list.Add(new LineNumberEntry(file2, num, -1, num2, flag)); } _line_numbers = list.ToArray(); if (includesColumns) { for (int i = 0; i < _line_numbers.Length; i++) { LineNumberEntry lineNumberEntry = _line_numbers[i]; if (lineNumberEntry.Row >= 0) { lineNumberEntry.Column = br.ReadLeb128(); } } } if (!includesEnds) { return; } for (int j = 0; j < _line_numbers.Length; j++) { LineNumberEntry lineNumberEntry2 = _line_numbers[j]; int num3 = br.ReadLeb128(); if (num3 == 16777215) { lineNumberEntry2.EndRow = -1; lineNumberEntry2.EndColumn = -1; } else { lineNumberEntry2.EndRow = lineNumberEntry2.Row + num3; lineNumberEntry2.EndColumn = br.ReadLeb128(); } } return; } case 64: flag = !flag; flag2 = true; break; default: throw new MonoSymbolFileException("Unknown extended opcode {0:x}", b); case 65: case 66: case 67: case 68: case 69: case 70: case 71: case 72: case 73: case 74: case 75: case 76: case 77: case 78: case 79: case 80: case 81: case 82: case 83: case 84: case 85: case 86: case 87: case 88: case 89: case 90: case 91: case 92: case 93: case 94: case 95: case 96: case 97: case 98: case 99: case 100: case 101: case 102: case 103: case 104: case 105: case 106: case 107: case 108: case 109: case 110: case 111: case 112: case 113: case 114: case 115: case 116: case 117: case 118: case 119: case 120: case 121: case 122: case 123: case 124: case 125: case 126: case 127: break; } br.BaseStream.Position = position; } else if (b < OpcodeBase) { switch (b) { case 1: list.Add(new LineNumberEntry(file2, num, -1, num2, flag)); flag2 = false; break; case 2: num2 += br.ReadLeb128(); flag2 = true; break; case 3: num += br.ReadLeb128(); flag2 = true; break; case 4: file2 = br.ReadLeb128(); flag2 = true; break; case 8: num2 += MaxAddressIncrement; flag2 = true; break; default: throw new MonoSymbolFileException("Unknown standard opcode {0:x} in LNT", b); } } else { b -= OpcodeBase; num2 += b / LineRange; num += LineBase + b % LineRange; list.Add(new LineNumberEntry(file2, num, -1, num2, flag)); flag2 = false; } } } public bool GetMethodBounds(out LineNumberEntry start, out LineNumberEntry end) { if (_line_numbers.Length > 1) { start = _line_numbers[0]; end = _line_numbers[_line_numbers.Length - 1]; return true; } start = LineNumberEntry.Null; end = LineNumberEntry.Null; return false; } } public class MethodEntry : IComparable { [Flags] public enum Flags { LocalNamesAmbiguous = 1, ColumnsInfoIncluded = 2, EndInfoIncluded = 4 } public readonly int CompileUnitIndex; public readonly int Token; public readonly int NamespaceID; private int DataOffset; private int LocalVariableTableOffset; private int LineNumberTableOffset; private int CodeBlockTableOffset; private int ScopeVariableTableOffset; private int RealNameOffset; private Flags flags; private int index; public readonly CompileUnitEntry CompileUnit; private LocalVariableEntry[] locals; private CodeBlockEntry[] code_blocks; private ScopeVariable[] scope_vars; private LineNumberTable lnt; private string real_name; public readonly MonoSymbolFile SymbolFile; public const int Size = 12; public Flags MethodFlags => flags; public int Index { get { return index; } set { index = value; } } internal MethodEntry(MonoSymbolFile file, MyBinaryReader reader, int index) { SymbolFile = file; this.index = index; Token = reader.ReadInt32(); DataOffset = reader.ReadInt32(); LineNumberTableOffset = reader.ReadInt32(); long position = reader.BaseStream.Position; reader.BaseStream.Position = DataOffset; CompileUnitIndex = reader.ReadLeb128(); LocalVariableTableOffset = reader.ReadLeb128(); NamespaceID = reader.ReadLeb128(); CodeBlockTableOffset = reader.ReadLeb128(); ScopeVariableTableOffset = reader.ReadLeb128(); RealNameOffset = reader.ReadLeb128(); flags = (Flags)reader.ReadLeb128(); reader.BaseStream.Position = position; CompileUnit = file.GetCompileUnit(CompileUnitIndex); } internal MethodEntry(MonoSymbolFile file, CompileUnitEntry comp_unit, int token, ScopeVariable[] scope_vars, LocalVariableEntry[] locals, LineNumberEntry[] lines, CodeBlockEntry[] code_blocks, string real_name, Flags flags, int namespace_id) { SymbolFile = file; this.real_name = real_name; this.locals = locals; this.code_blocks = code_blocks; this.scope_vars = scope_vars; this.flags = flags; index = -1; Token = token; CompileUnitIndex = comp_unit.Index; CompileUnit = comp_unit; NamespaceID = namespace_id; CheckLineNumberTable(lines); lnt = new LineNumberTable(file, lines); file.NumLineNumbers += lines.Length; int num = ((locals != null) ? locals.Length : 0); if (num <= 32) { for (int i = 0; i < num; i++) { string name = locals[i].Name; for (int j = i + 1; j < num; j++) { if (locals[j].Name == name) { flags |= Flags.LocalNamesAmbiguous; return; } } } return; } Dictionary<string, LocalVariableEntry> dictionary = new Dictionary<string, LocalVariableEntry>(); for (int k = 0; k < locals.Length; k++) { LocalVariableEntry value = locals[k]; if (dictionary.ContainsKey(value.Name)) { flags |= Flags.LocalNamesAmbiguous; break; } dictionary.Add(value.Name, value); } } private static void CheckLineNumberTable(LineNumberEntry[] line_numbers) { int num = -1; int num2 = -1; if (line_numbers == null) { return; } foreach (LineNumberEntry lineNumberEntry in line_numbers) { if (lineNumberEntry.Equals(LineNumberEntry.Null)) { throw new MonoSymbolFileException(); } if (lineNumberEntry.Offset < num) { throw new MonoSymbolFileException(); } if (lineNumberEntry.Offset > num) { num2 = lineNumberEntry.Row; num = lineNumberEntry.Offset; } else if (lineNumberEntry.Row > num2) { num2 = lineNumberEntry.Row; } } } internal void Write(MyBinaryWriter bw) { if (index <= 0 || DataOffset == 0) { throw new InvalidOperationException(); } bw.Write(Token); bw.Write(DataOffset); bw.Write(LineNumberTableOffset); } internal void WriteData(MonoSymbolFile file, MyBinaryWriter bw) { if (index <= 0) { throw new InvalidOperationException(); } LocalVariableTableOffset = (int)bw.BaseStream.Position; int num = ((locals != null) ? locals.Length : 0); bw.WriteLeb128(num); for (int i = 0; i < num; i++) { locals[i].Write(file, bw); } file.LocalCount += num; CodeBlockTableOffset = (int)bw.BaseStream.Position; int num2 = ((code_blocks != null) ? code_blocks.Length : 0); bw.WriteLeb128(num2); for (int j = 0; j < num2; j++) { code_blocks[j].Write(bw); } ScopeVariableTableOffset = (int)bw.BaseStream.Position; int num3 = ((scope_vars != null) ? scope_vars.Length : 0); bw.WriteLeb128(num3); for (int k = 0; k < num3; k++) { scope_vars[k].Write(bw); } if (real_name != null) { RealNameOffset = (int)bw.BaseStream.Position; bw.Write(real_name); } LineNumberEntry[] lineNumbers = lnt.LineNumbers; foreach (LineNumberEntry lineNumberEntry in lineNumbers) { if (lineNumberEntry.EndRow != -1 || lineNumberEntry.EndColumn != -1) { flags |= Flags.EndInfoIncluded; } } LineNumberTableOffset = (int)bw.BaseStream.Position; lnt.Write(file, bw, (flags & Flags.ColumnsInfoIncluded) != 0, (flags & Flags.EndInfoIncluded) != 0); DataOffset = (int)bw.BaseStream.Position; bw.WriteLeb128(CompileUnitIndex); bw.WriteLeb128(LocalVariableTableOffset); bw.WriteLeb128(NamespaceID); bw.WriteLeb128(CodeBlockTableOffset); bw.WriteLeb128(ScopeVariableTableOffset); bw.WriteLeb128(RealNameOffset); bw.WriteLeb128((int)flags); } public void ReadAll() { GetLineNumberTable(); GetLocals(); GetCodeBlocks(); GetScopeVariables(); GetRealName(); } public LineNumberTable GetLineNumberTable() { lock (SymbolFile) { if (lnt != null) { return lnt; } if (LineNumberTableOffset == 0) { return null; } MyBinaryReader binaryReader = SymbolFile.BinaryReader; long position = binaryReader.BaseStream.Position; binaryReader.BaseStream.Position = LineNumberTableOffset; lnt = LineNumberTable.Read(SymbolFile, binaryReader, (flags & Flags.ColumnsInfoIncluded) != 0, (flags & Flags.EndInfoIncluded) != 0); binaryReader.BaseStream.Position = position; return lnt; } } public LocalVariableEntry[] GetLocals() { lock (SymbolFile) { if (locals != null) { return locals; } if (LocalVariableTableOffset == 0) { return null; } MyBinaryReader binaryReader = SymbolFile.BinaryReader; long position = binaryReader.BaseStream.Position; binaryReader.BaseStream.Position = LocalVariableTableOffset; int num = binaryReader.ReadLeb128(); locals = new LocalVariableEntry[num]; for (int i = 0; i < num; i++) { locals[i] = new LocalVariableEntry(SymbolFile, binaryReader); } binaryReader.BaseStream.Position = position; return locals; } } public CodeBlockEntry[] GetCodeBlocks() { lock (SymbolFile) { if (code_blocks != null) { return code_blocks; } if (CodeBlockTableOffset == 0) { return null; } MyBinaryReader binaryReader = SymbolFile.BinaryReader; long position = binaryReader.BaseStream.Position; binaryReader.BaseStream.Position = CodeBlockTableOffset; int num = binaryReader.ReadLeb128(); code_blocks = new CodeBlockEntry[num]; for (int i = 0; i < num; i++) { code_blocks[i] = new CodeBlockEntry(i, binaryReader); } binaryReader.BaseStream.Position = position; return code_blocks; } } public ScopeVariable[] GetScopeVariables() { lock (SymbolFile) { if (scope_vars != null) { return scope_vars; } if (ScopeVariableTableOffset == 0) { return null; } MyBinaryReader binaryReader = SymbolFile.BinaryReader; long position = binaryReader.BaseStream.Position; binaryReader.BaseStream.Position = ScopeVariableTableOffset; int num = binaryReader.ReadLeb128(); scope_vars = new ScopeVariable[num]; for (int i = 0; i < num; i++) { scope_vars[i] = new ScopeVariable(binaryReader); } binaryReader.BaseStream.Position = position; return scope_vars; } } public string GetRealName() { lock (SymbolFile) { if (real_name != null) { return real_name; } if (RealNameOffset == 0) { return null; } real_name = SymbolFile.BinaryReader.ReadString(RealNameOffset); return real_name; } } public int CompareTo(object obj) { MethodEntry methodEntry = (MethodEntry)obj; if (methodEntry.Token < Token) { return 1; } if (methodEntry.Token > Token) { return -1; } return 0; } public override string ToString() { return $"[Method {index}:{Token:x}:{CompileUnitIndex}:{CompileUnit}]"; } } public struct NamespaceEntry { public readonly string Name; public readonly int Index; public readonly int Parent; public readonly string[] UsingClauses; public NamespaceEntry(string name, int index, string[] using_clauses, int parent) { Name = name; Index = index; Parent = parent; UsingClauses = ((using_clauses != null) ? using_clauses : new string[0]); } internal NamespaceEntry(MonoSymbolFile file, MyBinaryReader reader) { Name = reader.ReadString(); Index = reader.ReadLeb128(); Parent = reader.ReadLeb128(); int num = reader.ReadLeb128(); UsingClauses = new string[num]; for (int i = 0; i < num; i++) { UsingClauses[i] = reader.ReadString(); } } internal void Write(MonoSymbolFile file, MyBinaryWriter bw) { bw.Write(Name); bw.WriteLeb128(Index); bw.WriteLeb128(Parent); bw.WriteLeb128(UsingClauses.Length); string[] usingClauses = UsingClauses; foreach (string value in usingClauses) { bw.Write(value); } } public override string ToString() { return $"[Namespace {Name}:{Index}:{Parent}]"; } } public class MonoSymbolWriter { private List<SourceMethodBuilder> methods; private List<SourceFileEntry> sources; private List<CompileUnitEntry> comp_units; protected readonly MonoSymbolFile file; private string filename; private SourceMethodBuilder current_method; private Stack<SourceMethodBuilder> current_method_stack = new Stack<SourceMethodBuilder>(); public MonoSymbolFile SymbolFile => file; public MonoSymbolWriter(string filename) { methods = new List<SourceMethodBuilder>(); sources = new List<SourceFileEntry>(); comp_units = new List<CompileUnitEntry>(); file = new MonoSymbolFile(); this.filename = filename + ".mdb"; } public void CloseNamespace() { } public void DefineLocalVariable(int index, string name) { if (current_method != null) { current_method.AddLocal(index, name); } } public void DefineCapturedLocal(int scope_id, string name, string captured_name) { file.DefineCapturedVariable(scope_id, name, captured_name, CapturedVariable.CapturedKind.Local); } public void DefineCapturedParameter(int scope_id, string name, string captured_name) { file.DefineCapturedVariable(scope_id, name, captured_name, CapturedVariable.CapturedKind.Parameter); } public void DefineCapturedThis(int scope_id, string captured_name) { file.DefineCapturedVariable(scope_id, "this", captured_name, CapturedVariable.CapturedKind.This); } public void DefineCapturedScope(int scope_id, int id, string captured_name) { file.DefineCapturedScope(scope_id, id, captured_name); } public void DefineScopeVariable(int scope, int index) { if (current_method != null) { current_method.AddScopeVariable(scope, index); } } public void MarkSequencePoint(int offset, SourceFileEntry file, int line, int column, bool is_hidden) { if (current_method != null) { current_method.MarkSequencePoint(offset, file, line, column, is_hidden); } } public SourceMethodBuilder OpenMethod(ICompileUnit file, int ns_id, IMethodDef method) { SourceMethodBuilder result = new SourceMethodBuilder(file, ns_id, method); current_method_stack.Push(current_method); current_method = result; methods.Add(current_method); return result; } public void CloseMethod() { current_method = current_method_stack.Pop(); } public SourceFileEntry DefineDocument(string url) { SourceFileEntry sourceFileEntry = new SourceFileEntry(file, url); sources.Add(sourceFileEntry); return sourceFileEntry; } public SourceFileEntry DefineDocument(string url, byte[] guid, byte[] checksum) { SourceFileEntry sourceFileEntry = new SourceFileEntry(file, url, guid, checksum); sources.Add(sourceFileEntry); return sourceFileEntry; } public CompileUnitEntry DefineCompilationUnit(SourceFileEntry source) { CompileUnitEntry compileUnitEntry = new CompileUnitEntry(file, source); comp_units.Add(compileUnitEntry); return compileUnitEntry; } public int DefineNamespace(string name, CompileUnitEntry unit, string[] using_clauses, int parent) { if (unit == null || using_clauses == null) { throw new NullReferenceException(); } return unit.DefineNamespace(name, using_clauses, parent); } public int OpenScope(int start_offset) { if (current_method == null) { return 0; } current_method.StartBlock(CodeBlockEntry.Type.Lexical, start_offset); return 0; } public void CloseScope(int end_offset) { if (current_method != null) { current_method.EndBlock(end_offset); } } public void OpenCompilerGeneratedBlock(int start_offset) { if (current_method != null) { current_method.StartBlock(CodeBlockEntry.Type.CompilerGenerated, start_offset); } } public void CloseCompilerGeneratedBlock(int end_offset) { if (current_method != null) { current_method.EndBlock(end_offset); } } public void StartIteratorBody(int start_offset) { current_method.StartBlock(CodeBlockEntry.Type.IteratorBody, start_offset); } public void EndIteratorBody(int end_offset) { current_method.EndBlock(end_offset); } public void StartIteratorDispatcher(int start_offset) { current_method.StartBlock(CodeBlockEntry.Type.IteratorDispatcher, start_offset); } public void EndIteratorDispatcher(int end_offset) { current_method.EndBlock(end_offset); } public void DefineAnonymousScope(int id) { file.DefineAnonymousScope(id); } public void WriteSymbolFile(Guid guid) { foreach (SourceMethodBuilder method in methods) { method.DefineMethod(file); } try { File.Delete(filename); } catch { } using FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write); file.CreateSymbolFile(guid, fs); } } public class SourceMethodBuilder { private List<LocalVariableEntry> _locals; private List<CodeBlockEntry> _blocks; private List<ScopeVariable> _scope_vars; private Stack<CodeBlockEntry> _block_stack; private readonly List<LineNumberEntry> method_lines; private readonly ICompileUnit _comp_unit; private readonly int ns_id; private readonly IMethodDef method; public CodeBlockEntry[] Blocks { get { if (_blocks == null) { return new CodeBlockEntry[0]; } CodeBlockEntry[] array = new CodeBlockEntry[_blocks.Count]; _blocks.CopyTo(array, 0); return array; } } public CodeBlockEntry CurrentBlock { get { if (_block_stack != null && _block_stack.Count > 0) { return _block_stack.Peek(); } return null; } } public LocalVariableEntry[] Locals { get { if (_locals == null) { return new LocalVariableEntry[0]; } return _locals.ToArray(); } } public ICompileUnit SourceFile => _comp_unit; public ScopeVariable[] ScopeVariables { get { if (_scope_vars == null) { return new ScopeVariable[0]; } return _scope_vars.ToArray(); } } public SourceMethodBuilder(ICompileUnit comp_unit) { _comp_unit = comp_unit; method_lines = new List<LineNumberEntry>(); } public SourceMethodBuilder(ICompileUnit comp_unit, int ns_id, IMethodDef method) : this(comp_unit) { this.ns_id = ns_id; this.method = method; } public void MarkSequencePoint(int offset, SourceFileEntry file, int line, int column, bool is_hidden) { MarkSequencePoint(offset, file, line, column, -1, -1, is_hidden); } public void MarkSequencePoint(int offset, SourceFileEntry file, int line, int column, int end_line, int end_column, bool is_hidden) { LineNumberEntry lineNumberEntry = new LineNumberEntry(file?.Index ?? 0, line, column, end_line, end_column, offset, is_hidden); if (method_lines.Count > 0) { LineNumberEntry lineNumberEntry2 = method_lines[method_lines.Count - 1]; if (lineNumberEntry2.Offset == offset) { if (LineNumberEntry.LocationComparer.Default.Compare(lineNumberEntry, lineNumberEntry2) > 0) { method_lines[method_lines.Count - 1] = lineNumberEntry; } return; } } method_lines.Add(lineNumberEntry); } public void StartBlock(CodeBlockEntry.Type type, int start_offset) { StartBlock(type, start_offset, (_blocks == null) ? 1 : (_blocks.Count + 1)); } public void StartBlock(CodeBlockEntry.Type type, int start_offset, int scopeIndex) { if (_block_stack == null) { _block_stack = new Stack<CodeBlockEntry>(); } if (_blocks == null) { _blocks = new List<CodeBlockEntry>(); } int parent = ((CurrentBlock != null) ? CurrentBlock.Index : (-1)); CodeBlockEntry item = new CodeBlockEntry(scopeIndex, parent, type, start_offset); _block_stack.Push(item); _blocks.Add(item); } public void EndBlock(int end_offset) { _block_stack.Pop().Close(end_offset); } public void AddLocal(int index, string name) { if (_locals == null) { _locals = new List<LocalVariableEntry>(); } int block = ((CurrentBlock != null) ? CurrentBlock.Index : 0); _locals.Add(new LocalVariableEntry(index, name, block)); } public void AddScopeVariable(int scope, int index) { if (_scope_vars == null) { _scope_vars = new List<ScopeVariable>(); } _scope_vars.Add(new ScopeVariable(scope, index)); } public void DefineMethod(MonoSymbolFile file) { DefineMethod(file, method.Token); } public void DefineMethod(MonoSymbolFile file, int token) { CodeBlockEntry[] array = Blocks; if (array.Length != 0) { List<CodeBlockEntry> list = new List<CodeBlockEntry>(array.Length); int num = 0; for (int i = 0; i < array.Length; i++) { num = Math.Max(num, array[i].Index); } for (int j = 0; j < num; j++) { int num2 = j + 1; if (j < array.Length && array[j].Index == num2) { list.Add(array[j]); continue; } bool flag = false; for (int k = 0; k < array.Length; k++) { if (array[k].Index == num2) { list.Add(array[k]); flag = true; break; } } if (!flag) { list.Add(new CodeBlockEntry(num2, -1, CodeBlockEntry.Type.CompilerGenerated, 0)); } } array = list.ToArray(); } MethodEntry entry = new MethodEntry(file, _comp_unit.Entry, token, ScopeVariables, Locals, method_lines.ToArray(), array, null, MethodEntry.Flags.ColumnsInfoIncluded, ns_id); file.AddMethod(entry); } } public class SymbolWriterImpl : ISymbolWriter { private MonoSymbolWriter msw; private int nextLocalIndex; private int currentToken; private string methodName; private Stack namespaceStack = new Stack(); private bool methodOpened; private Hashtable documents = new Hashtable(); private Guid guid; public SymbolWriterImpl(Guid guid) { this.guid = guid; } public void Close() { msw.WriteSymbolFile(guid); } public void CloseMethod() { if (methodOpened) { methodOpened = false; nextLocalIndex = 0; msw.CloseMethod(); } } public void CloseNamespace() { namespaceStack.Pop(); msw.CloseNamespace(); } public void CloseScope(int endOffset) { msw.CloseScope(endOffset); } public ISymbolDocumentWriter DefineDocument(string url, Guid language, Guid languageVendor, Guid documentType) { SymbolDocumentWriterImpl symbolDocumentWriterImpl = (SymbolDocumentWriterImpl)documents[url]; if (symbolDocumentWriterImpl == null) { SourceFileEntry source = msw.DefineDocument(url); symbolDocumentWriterImpl = new SymbolDocumentWriterImpl(msw.DefineCompilationUnit(source)); documents[url] = symbolDocumentWriterImpl; } return symbolDocumentWriterImpl; } public void DefineField(SymbolToken parent, string name, FieldAttributes attributes, byte[] signature, SymAddressKind addrKind, int addr1, int addr2, int addr3) { } public void DefineGlobalVariable(string name, FieldAttributes attributes, byte[] signature, SymAddressKind addrKind, int addr1, int addr2, int addr3) { } public void DefineLocalVariable(string name, FieldAttributes attributes, byte[] signature, SymAddressKind addrKind, int addr1, int addr2, int addr3, int startOffset, int endOffset) { msw.DefineLocalVariable(nextLocalIndex++, name); } public void DefineParameter(string name, ParameterAttributes attributes, int sequence, SymAddressKind addrKind, int addr1, int addr2, int addr3) { } public void DefineSequencePoints(ISymbolDocumentWriter document, int[] offsets, int[] lines, int[] columns, int[] endLines, int[] endColumns) { SourceFileEntry file = ((SymbolDocumentWriterImpl)document)?.Entry.SourceFile; for (int i = 0; i < offsets.Length; i++) { if (i <= 0 || offsets[i] != offsets[i - 1] || lines[i] != lines[i - 1] || columns[i] != columns[i - 1]) { msw.MarkSequencePoint(offsets[i], file, lines[i], columns[i], is_hidden: false); } } } public void Initialize(IntPtr emitter, string filename, bool fFullBuild) { msw = new MonoSymbolWriter(filename); } public void OpenMethod(SymbolToken method) { currentToken = method.GetToken(); } public void OpenNamespace(string name) { NamespaceInfo namespaceInfo = new NamespaceInfo(); namespaceInfo.NamespaceID = -1; namespaceInfo.Name = name; namespaceStack.Push(namespaceInfo); } public int OpenScope(int startOffset) { return msw.OpenScope(startOffset); } public void SetMethodSourceRange(ISymbolDocumentWriter startDoc, int startLine, int startColumn, ISymbolDocumentWriter endDoc, int endLine, int endColumn) { int currentNamespace = GetCurrentNamespace(startDoc); SourceMethodImpl method = new SourceMethodImpl(methodName, currentToken, currentNamespace); msw.OpenMethod(((ICompileUnit)startDoc).Entry, currentNamespace, method); methodOpened = true; } public void SetScopeRange(int scopeID, int startOffset, int endOffset) { } public void SetSymAttribute(SymbolToken parent, string name, byte[] data) { if (name == "__name") { methodName = Encoding.UTF8.GetString(data); } } public void SetUnderlyingWriter(IntPtr underlyingWriter) { } public void SetUserEntryPoint(SymbolToken entryMethod) { } public void UsingNamespace(string fullName) { if (namespaceStack.Count == 0) { OpenNamespace(""); } NamespaceInfo namespaceInfo = (NamespaceInfo)namespaceStack.Peek(); if (namespaceInfo.NamespaceID != -1) { NamespaceInfo namespaceInfo2 = namespaceInfo; CloseNamespace(); OpenNamespace(namespaceInfo2.Name); namespaceInfo = (NamespaceInfo)namespaceStack.Peek(); namespaceInfo.UsingClauses = namespaceInfo2.UsingClauses; } namespaceInfo.UsingClauses.Add(fullName); } private int GetCurrentNamespace(ISymbolDocumentWriter doc) { if (namespaceStack.Count == 0) { OpenNamespace(""); } NamespaceInfo namespaceInfo = (NamespaceInfo)namespaceStack.Peek(); if (namespaceInfo.NamespaceID == -1) { string[] using_clauses = (string[])namespaceInfo.UsingClauses.ToArray(typeof(string)); int parent = 0; if (namespaceStack.Count > 1) { namespaceStack.Pop(); parent = ((NamespaceInfo)namespaceStack.Peek()).NamespaceID; namespaceStack.Push(namespaceInfo); } namespaceInfo.NamespaceID = msw.DefineNamespace(namespaceInfo.Name, ((ICompileUnit)doc).Entry, using_clauses, parent); } return namespaceInfo.NamespaceID; } } internal class SymbolDocumentWriterImpl : ISymbolDocumentWriter, ISourceFile, ICompileUnit { private CompileUnitEntry comp_unit; SourceFileEntry ISourceFile.Entry => comp_unit.SourceFile; public CompileUnitEntry Entry => comp_unit; public SymbolDocumentWriterImpl(CompileUnitEntry comp_unit) { this.comp_unit = comp_unit; } public void SetCheckSum(Guid algorithmId, byte[] checkSum) { } public void SetSource(byte[] source) { } } internal class SourceMethodImpl : IMethodDef { private string name; private int token; private int namespaceID; public string Name => name; public int NamespaceID => namespaceID; public int Token => token; public SourceMethodImpl(string name, int token, int namespaceID) { this.name = name; this.token = token; this.namespaceID = namespaceID; } } internal class NamespaceInfo { public string Name; public int NamespaceID; public ArrayList UsingClauses = new ArrayList(); } } namespace Mono.Cecil.Mdb { public sealed class MdbReaderProvider : ISymbolReaderProvider { public ISymbolReader GetSymbolReader(ModuleDefinition module, string fileName) { Mixin.CheckModule(module); Mixin.CheckFileName(fileName); return (ISymbolReader)(object)new MdbReader(module, MonoSymbolFile.ReadSymbolFile(Mixin.GetMdbFileName(fileName))); } public ISymbolReader GetSymbolReader(ModuleDefinition module, Stream symbolStream) { Mixin.CheckModule(module); Mixin.CheckStream((object)symbolStream); return (ISymbolReader)(object)new MdbReader(module, MonoSymbolFile.ReadSymbolFile(symbolStream)); } } public sealed class MdbReader : ISymbolReader, IDisposable { private readonly ModuleDefinition module; private readonly MonoSymbolFile symbol_file; private readonly Dictionary<string, Document> documents; public MdbReader(ModuleDefinition module, MonoSymbolFile symFile) { this.module = module; symbol_file = symFile; documents = new Dictionary<string, Document>(); } public ISymbolWriterProvider GetWriterProvider() { return (ISymbolWriterProvider)(object)new MdbWriterProvider(); } public bool ProcessDebugHeader(ImageDebugHeader header) { return symbol_file.Guid == module.Mvid; } public MethodDebugInformation Read(MethodDefinition method) { //IL_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_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Expected O, but got Unknown MetadataToken metadataToken = ((MemberReference)method).MetadataToken; MethodEntry methodByToken = symbol_file.GetMethodByToken(((MetadataToken)(ref metadataToken)).ToInt32()); if (methodByToken == null) { return null; } MethodDebugInformation val = new MethodDebugInformation(method); val.code_size = ReadCodeSize(method); ScopeDebugInformation[] scopes = ReadScopes(methodByToken, val); ReadLineNumbers(methodByToken, val); ReadLocalVariables(methodByToken, scopes); return val; } private static int ReadCodeSize(MethodDefinition method) { return ((MemberReference)method).Module.Read<MethodDefinition, int>(method, (Func<MethodDefinition, MetadataReader, int>)((MethodDefinition m, MetadataReader reader) => reader.ReadCodeSize(m))); } private static void ReadLocalVariables(MethodEntry entry, ScopeDebugInformation[] scopes) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Expected O, but got Unknown LocalVariableEntry[] locals = entry.GetLocals(); for (int i = 0; i < locals.Length; i++) { LocalVariableEntry localVariableEntry = locals[i]; VariableDebugInformation val = new VariableDebugInformation(localVariableEntry.Index, localVariableEntry.Name); int blockIndex = localVariableEntry.BlockIndex; if (blockIndex >= 0 && blockIndex < scopes.Length) { ScopeDebugInformation val2 = scopes[blockIndex]; if (val2 != null) { val2.Variables.Add(val); } } } } private void ReadLineNumbers(MethodEntry entry, MethodDebugInformation info) { LineNumberTable lineNumberTable = entry.GetLineNumberTable(); info.sequence_points = new Collection<SequencePoint>(lineNumberTable.LineNumbers.Length); for (int i = 0; i < lineNumberTable.LineNumbers.Length; i++) { LineNumberEntry lineNumberEntry = lineNumberTable.LineNumbers[i]; if (i <= 0 || lineNumberTable.LineNumbers[i - 1].Offset != lineNumberEntry.Offset) { info.sequence_points.Add(LineToSequencePoint(lineNumberEntry)); } } } private Document GetDocument(SourceFileEntry file) { //IL_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_002c: Expected O, but got Unknown string fileName = file.FileName; if (documents.TryGetValue(fileName, out var value)) { return value; } value = new Document(fileName) { Hash = file.Checksum }; documents.Add(fileName, value); return value; } private static ScopeDebugInformation[] ReadScopes(MethodEntry entry, MethodDebugInformation info) { //IL_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_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002c: 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_0038: Expected O, but got Unknown //IL_0039: Expected O, but got Unknown //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Expected O, but got Unknown //IL_006d: 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) CodeBlockEntry[] codeBlocks = entry.GetCodeBlocks(); ScopeDebugInformation[] array = (ScopeDebugInformation[])(object)new ScopeDebugInformation[codeBlocks.Length + 1]; ScopeDebugInformation val = new ScopeDebugInformation { Start = new InstructionOffset(0), End = new InstructionOffset(info.code_size) }; ScopeDebugInformation scope = val; array[0] = val; info.scope = scope; CodeBlockEntry[] array2 = codeBlocks; foreach (CodeBlockEntry codeBlockEntry in array2) { if (codeBlockEntry.BlockType == CodeBlockEntry.Type.Lexical || codeBlockEntry.BlockType == CodeBlockEntry.Type.CompilerGenerated) { ScopeDebugInformation val2 = new ScopeDebugInformation(); val2.Start = new InstructionOffset(codeBlockEntry.StartOffset); val2.End = new InstructionOffset(codeBlockEntry.EndOffset); array[codeBlockEntry.Index + 1] = val2; if (!AddScope(info.scope.Scopes, val2)) { info.scope.Scopes.Add(val2); } } } return array; } private static bool AddScope(Collection<ScopeDebugInformation> scopes, ScopeDebugInformation scope) { //IL_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_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_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_004a: 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_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) Enumerator<ScopeDebugInformation> enumerator = scopes.GetEnumerator(); try { while (enumerator.MoveNext()) { ScopeDebugInformation current = enumerator.Current; if (current.HasScopes && AddScope(current.Scopes, scope)) { return true; } InstructionOffset val = scope.Start; int offset = ((InstructionOffset)(ref val)).Offset; val = current.Start; if (offset >= ((InstructionOffset)(ref val)).Offset) { val = scope.End; int offset2 = ((InstructionOffset)(ref val)).Offset; val = current.End; if (offset2 <= ((InstructionOffset)(ref val)).Offset) { current.Scopes.Add(scope); return true; } } } } finally { ((IDisposable)enumerator).Dispose(); } return false; } private SequencePoint LineToSequencePoint(LineNumberEntry line) { //IL_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_0030: 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_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Expected O, but got Unknown SourceFileEntry sourceFile = symbol_file.GetSourceFile(line.File); return new SequencePoint(line.Offset, GetDocument(sourceFile)) { StartLine = line.Row, EndLine = line.EndRow, StartColumn = line.Column, EndColumn = line.EndColumn }; } public void Dispose() { symbol_file.Dispose(); } } internal static class MethodEntryExtensions { public static bool HasColumnInfo(this MethodEntry entry) { return (entry.MethodFlags & MethodEntry.Flags.ColumnsInfoIncluded) != 0; } public static bool HasEndInfo(this MethodEntry entry) { return (entry.MethodFlags & MethodEntry.Flags.EndInfoIncluded) != 0; } } public sealed class MdbWriterProvider : ISymbolWriterProvider { public ISymbolWriter GetSymbolWriter(ModuleDefinition module, string fileName) { Mixin.CheckModule(module); Mixin.CheckFileName(fileName); return (ISymbolWriter)(object)new MdbWriter(module.Mvid, fileName); } public ISymbolWriter GetSymbolWriter(ModuleDefinition module, Stream symbolStream) { throw new NotImplementedException(); } } public sealed class MdbWriter : ISymbolWriter, IDisposable { private class SourceFile : ISourceFile { private readonly CompileUnitEntry compilation_unit; private readonly SourceFileEntry entry; public SourceFileEntry Entry => entry; public CompileUnitEntry CompilationUnit => compilation_unit; public SourceFile(CompileUnitEntry comp_unit, SourceFileEntry entry) { compilation_unit = comp_unit; this.entry = entry; } } private class SourceMethod : IMethodDef { private readonly MethodDefinition method; public string Name => ((MemberReference)method).Name; public int Token { get { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) MetadataToken metadataToken = ((MemberReference)method).MetadataToken; return ((MetadataToken)(ref metadataToken)).ToInt32(); } } public SourceMethod(MethodDefinition method) { this.method = method; } } private readonly Guid mvid; private readonly MonoSymbolWriter writer; private readonly Dictionary<string, SourceFile> source_files; public MdbWriter(Guid mvid, string assembly) { this.mvid = mvid; writer = new MonoSymbolWriter(assembly); source_files = new Dictionary<string, SourceFile>(); } public ISymbolReaderProvider GetReaderProvider() { return (ISymbolReaderProvider)(object)new MdbReaderProvider(); } private SourceFile GetSourceFile(Document document) { string url = document.Url; if (source_files.TryGetValue(url, out var value)) { return value; } SourceFileEntry sourceFileEntry = writer.DefineDocument(url, null, (document.Hash != null && document.Hash.Length == 16) ? document.Hash : null); value = new SourceFile(writer.DefineCompilationUnit(sourceFileEntry), sourceFileEntry); source_files.Add(url, value); return value; } private void Populate(Collection<SequencePoint> sequencePoints, int[] offsets, int[] startRows, int[] endRows, int[] startCols, int[] endCols, out SourceFile file) { SourceFile sourceFile = null; for (int i = 0; i < sequencePoints.Count; i++) { SequencePoint val = sequencePoints[i]; offsets[i] = val.Offset; if (sourceFile == null) { sourceFile = GetSourceFile(val.Document); } startRows[i] = val.StartLine; endRows[i] = val.EndLine; startCols[i] = val.StartColumn; endCols[i] = val.EndColumn; } file = sourceFile; } public void Write(MethodDebugInformation info) { SourceMethod method = new SourceMethod(info.method); Collection<SequencePoint> sequencePoints = info.SequencePoints; int count = sequencePoints.Count; if (count != 0) { int[] array = new int[count]; int[] array2 = new int[count]; int[] array3 = new int[count]; int[] array4 = new int[count]; int[] array5 = new int[count]; Populate(sequencePoints, array, array2, array3, array4, array5, out var file); SourceMethodBuilder sourceMethodBuilder = writer.OpenMethod(file.CompilationUnit, 0, method); for (int i = 0; i < count; i++) { sourceMethodBuilder.MarkSequencePoint(array[i], file.CompilationUnit.SourceFile, array2[i], array4[i], array3[i], array5[i], is_hidden: false); } if (info.scope != null) { WriteRootScope(info.scope, info); } writer.CloseMethod(); } } private void WriteRootScope(ScopeDebugInformation scope, MethodDebugInformation info) { WriteScopeVariables(scope); if (scope.HasScopes) { WriteScopes(scope.Scopes, info); } } private void WriteScope(ScopeDebugInformation scope, MethodDebugInformation info) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_004d: 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) MonoSymbolWriter monoSymbolWriter = writer; InstructionOffset val = scope.Start; monoSymbolWriter.OpenScope(((InstructionOffset)(ref val)).Offset); WriteScopeVariables(scope); if (scope.HasScopes) { WriteScopes(scope.Scopes, info); } MonoSymbolWriter monoSymbolWriter2 = writer; val = scope.End; int end_offset; if (!((InstructionOffset)(ref val)).IsEndOfMethod) { val = scope.End; end_offset = ((InstructionOffset)(ref val)).Offset; } else { end_offset = info.code_size; } monoSymbolWriter2.CloseScope(end_offset); } private void WriteScopes(Collection<ScopeDebugInformation> scopes, MethodDebugInformation info) { for (int i = 0; i < scopes.Count; i++) { WriteScope(scopes[i], info); } } private void WriteScopeVariables(ScopeDebugInformation scope) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) if (!scope.HasVariables) { return; } Enumerator<VariableDebugInformation> enumerator = scope.variables.GetEnumerator(); try { while (enumerator.MoveNext()) { VariableDebugInformation current = enumerator.Current; if (!string.IsNullOrEmpty(current.Name)) { writer.DefineLocalVariable(current.Index, current.Name); } } } finally { ((IDisposable)enumerator).Dispose(); } } public ImageDebugHeader GetDebugHeader() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown return new ImageDebugHeader(); } public void Dispose() { writer.WriteSymbolFile(mvid); } } }
BepInExPack\BepInEx\core\Mono.Cecil.Pdb.dll
Decompiled 2 months ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Text; using Microsoft.Cci; using Microsoft.Cci.Pdb; using Mono.Cecil.Cil; using Mono.Cecil.PE; using Mono.Collections.Generic; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyProduct("Mono.Cecil")] [assembly: AssemblyCopyright("Copyright © 2008 - 2018 Jb Evain")] [assembly: ComVisible(false)] [assembly: AssemblyFileVersion("0.10.4.0")] [assembly: AssemblyInformationalVersion("0.10.4.0")] [assembly: AssemblyTitle("Mono.Cecil.Pdb")] [assembly: CLSCompliant(false)] [assembly: AssemblyVersion("0.10.4.0")] namespace Mono.Cecil.Pdb { [ComImport] [Guid("B01FAFEB-C450-3A4D-BEEC-B4CEEC01E006")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface ISymUnmanagedDocumentWriter { } [ComImport] [Guid("0B97726E-9E6D-4f05-9A26-424022093CAA")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface ISymUnmanagedWriter2 { void DefineDocument([In][MarshalAs(UnmanagedType.LPWStr)] string url, [In] ref Guid langauge, [In] ref Guid languageVendor, [In] ref Guid documentType, [MarshalAs(UnmanagedType.Interface)] out ISymUnmanagedDocumentWriter pRetVal); void SetUserEntryPoint([In] int methodToken); void OpenMethod([In] int methodToken); void CloseMethod(); void OpenScope([In] int startOffset, out int pRetVal); void CloseScope([In] int endOffset); void SetScopeRange_Placeholder(); void DefineLocalVariable_Placeholder(); void DefineParameter_Placeholder(); void DefineField_Placeholder(); void DefineGlobalVariable_Placeholder(); void Close(); void SetSymAttribute(uint parent, string name, uint data, IntPtr signature); void OpenNamespace([In][MarshalAs(UnmanagedType.LPWStr)] string name); void CloseNamespace(); void UsingNamespace([In][MarshalAs(UnmanagedType.LPWStr)] string fullName); void SetMethodSourceRange_Placeholder(); void Initialize([In][MarshalAs(UnmanagedType.IUnknown)] object emitter, [In][MarshalAs(UnmanagedType.LPWStr)] string filename, [In] IStream pIStream, [In] bool fFullBuild); void GetDebugInfo(out ImageDebugDirectory pIDD, [In] int cData, out int pcData, [In][Out][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] data); void DefineSequencePoints([In][MarshalAs(UnmanagedType.Interface)] ISymUnmanagedDocumentWriter document, [In] int spCount, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] offsets, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] lines, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] columns, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] endLines, [In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] endColumns); void RemapToken_Placeholder(); void Initialize2_Placeholder(); void DefineConstant_Placeholder(); void Abort_Placeholder(); void DefineLocalVariable2([In][MarshalAs(UnmanagedType.LPWStr)] string name, [In] int attributes, [In] int sigToken, [In] int addrKind, [In] int addr1, [In] int addr2, [In] int addr3, [In] int startOffset, [In] int endOffset); void DefineGlobalVariable2_Placeholder(); void DefineConstant2([In][MarshalAs(UnmanagedType.LPWStr)] string name, [In][MarshalAs(UnmanagedType.Struct)] object variant, [In] int sigToken); } [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("BA3FEE4C-ECB9-4e41-83B7-183FA41CD859")] internal interface IMetaDataEmit { void SetModuleProps(string szName); void Save(string szFile, uint dwSaveFlags); void SaveToStream(IntPtr pIStream, uint dwSaveFlags); uint GetSaveSize(uint fSave); uint DefineTypeDef(IntPtr szTypeDef, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements); uint DefineNestedType(IntPtr szTypeDef, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements, uint tdEncloser); void SetHandler([In][MarshalAs(UnmanagedType.IUnknown)] object pUnk); uint DefineMethod(uint td, IntPtr zName, uint dwMethodFlags, IntPtr pvSigBlob, uint cbSigBlob, uint ulCodeRVA, uint dwImplFlags); void DefineMethodImpl(uint td, uint tkBody, uint tkDecl); uint DefineTypeRefByName(uint tkResolutionScope, IntPtr szName); uint DefineImportType(IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport pImport, uint tdImport, IntPtr pAssemEmit); uint DefineMemberRef(uint tkImport, string szName, IntPtr pvSigBlob, uint cbSigBlob); uint DefineImportMember(IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport pImport, uint mbMember, IntPtr pAssemEmit, uint tkParent); uint DefineEvent(uint td, string szEvent, uint dwEventFlags, uint tkEventType, uint mdAddOn, uint mdRemoveOn, uint mdFire, IntPtr rmdOtherMethods); void SetClassLayout(uint td, uint dwPackSize, IntPtr rFieldOffsets, uint ulClassSize); void DeleteClassLayout(uint td); void SetFieldMarshal(uint tk, IntPtr pvNativeType, uint cbNativeType); void DeleteFieldMarshal(uint tk); uint DefinePermissionSet(uint tk, uint dwAction, IntPtr pvPermission, uint cbPermission); void SetRVA(uint md, uint ulRVA); uint GetTokenFromSig(IntPtr pvSig, uint cbSig); uint DefineModuleRef(string szName); void SetParent(uint mr, uint tk); uint GetTokenFromTypeSpec(IntPtr pvSig, uint cbSig); void SaveToMemory(IntPtr pbData, uint cbData); uint DefineUserString(string szString, uint cchString); void DeleteToken(uint tkObj); void SetMethodProps(uint md, uint dwMethodFlags, uint ulCodeRVA, uint dwImplFlags); void SetTypeDefProps(uint td, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements); void SetEventProps(uint ev, uint dwEventFlags, uint tkEventType, uint mdAddOn, uint mdRemoveOn, uint mdFire, IntPtr rmdOtherMethods); uint SetPermissionSetProps(uint tk, uint dwAction, IntPtr pvPermission, uint cbPermission); void DefinePinvokeMap(uint tk, uint dwMappingFlags, string szImportName, uint mrImportDLL); void SetPinvokeMap(uint tk, uint dwMappingFlags, string szImportName, uint mrImportDLL); void DeletePinvokeMap(uint tk); uint DefineCustomAttribute(uint tkObj, uint tkType, IntPtr pCustomAttribute, uint cbCustomAttribute); void SetCustomAttributeValue(uint pcv, IntPtr pCustomAttribute, uint cbCustomAttribute); uint DefineField(uint td, string szName, uint dwFieldFlags, IntPtr pvSigBlob, uint cbSigBlob, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue); uint DefineProperty(uint td, string szProperty, uint dwPropFlags, IntPtr pvSig, uint cbSig, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue, uint mdSetter, uint mdGetter, IntPtr rmdOtherMethods); uint DefineParam(uint md, uint ulParamSeq, string szName, uint dwParamFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue); void SetFieldProps(uint fd, uint dwFieldFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue); void SetPropertyProps(uint pr, uint dwPropFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue, uint mdSetter, uint mdGetter, IntPtr rmdOtherMethods); void SetParamProps(uint pd, string szName, uint dwParamFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue); uint DefineSecurityAttributeSet(uint tkObj, IntPtr rSecAttrs, uint cSecAttrs); void ApplyEditAndContinue([MarshalAs(UnmanagedType.IUnknown)] object pImport); uint TranslateSigWithScope(IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport import, IntPtr pbSigBlob, uint cbSigBlob, IntPtr pAssemEmit, IMetaDataEmit emit, IntPtr pvTranslatedSig, uint cbTranslatedSigMax); void SetMethodImplFlags(uint md, uint dwImplFlags); void SetFieldRVA(uint fd, uint ulRVA); void Merge(IMetaDataImport pImport, IntPtr pHostMapToken, [MarshalAs(UnmanagedType.IUnknown)] object pHandler); void MergeEnd(); } [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("7DAC8207-D3AE-4c75-9B67-92801A497D44")] internal interface IMetaDataImport { [PreserveSig] void CloseEnum(uint hEnum); uint CountEnum(uint hEnum); void ResetEnum(uint hEnum, uint ulPos); uint EnumTypeDefs(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rTypeDefs, uint cMax); uint EnumInterfaceImpls(ref uint phEnum, uint td, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] rImpls, uint cMax); uint EnumTypeRefs(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rTypeRefs, uint cMax); uint FindTypeDefByName(string szTypeDef, uint tkEnclosingClass); Guid GetScopeProps(StringBuilder szName, uint cchName, out uint pchName); uint GetModuleFromScope(); uint GetTypeDefProps(uint td, IntPtr szTypeDef, uint cchTypeDef, out uint pchTypeDef, IntPtr pdwTypeDefFlags); uint GetInterfaceImplProps(uint iiImpl, out uint pClass); uint GetTypeRefProps(uint tr, out uint ptkResolutionScope, StringBuilder szName, uint cchName); uint ResolveTypeRef(uint tr, [In] ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out object ppIScope); uint EnumMembers(ref uint phEnum, uint cl, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] rMembers, uint cMax); uint EnumMembersWithName(ref uint phEnum, uint cl, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rMembers, uint cMax); uint EnumMethods(ref uint phEnum, uint cl, IntPtr rMethods, uint cMax); uint EnumMethodsWithName(ref uint phEnum, uint cl, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rMethods, uint cMax); uint EnumFields(ref uint phEnum, uint cl, IntPtr rFields, uint cMax); uint EnumFieldsWithName(ref uint phEnum, uint cl, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rFields, uint cMax); uint EnumParams(ref uint phEnum, uint mb, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] rParams, uint cMax); uint EnumMemberRefs(ref uint phEnum, uint tkParent, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] rMemberRefs, uint cMax); uint EnumMethodImpls(ref uint phEnum, uint td, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rMethodBody, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rMethodDecl, uint cMax); uint EnumPermissionSets(ref uint phEnum, uint tk, uint dwActions, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rPermission, uint cMax); uint FindMember(uint td, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] pvSigBlob, uint cbSigBlob); uint FindMethod(uint td, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] pvSigBlob, uint cbSigBlob); uint FindField(uint td, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] pvSigBlob, uint cbSigBlob); uint FindMemberRef(uint td, string szName, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] byte[] pvSigBlob, uint cbSigBlob); uint GetMethodProps(uint mb, out uint pClass, IntPtr szMethod, uint cchMethod, out uint pchMethod, IntPtr pdwAttr, IntPtr ppvSigBlob, IntPtr pcbSigBlob, IntPtr pulCodeRVA); uint GetMemberRefProps(uint mr, ref uint ptk, StringBuilder szMember, uint cchMember, out uint pchMember, out IntPtr ppvSigBlob); uint EnumProperties(ref uint phEnum, uint td, IntPtr rProperties, uint cMax); uint EnumEvents(ref uint phEnum, uint td, IntPtr rEvents, uint cMax); uint GetEventProps(uint ev, out uint pClass, StringBuilder szEvent, uint cchEvent, out uint pchEvent, out uint pdwEventFlags, out uint ptkEventType, out uint pmdAddOn, out uint pmdRemoveOn, out uint pmdFire, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 11)] uint[] rmdOtherMethod, uint cMax); uint EnumMethodSemantics(ref uint phEnum, uint mb, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] uint[] rEventProp, uint cMax); uint GetMethodSemantics(uint mb, uint tkEventProp); uint GetClassLayout(uint td, out uint pdwPackSize, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 3)] IntPtr rFieldOffset, uint cMax, out uint pcFieldOffset); uint GetFieldMarshal(uint tk, out IntPtr ppvNativeType); uint GetRVA(uint tk, out uint pulCodeRVA); uint GetPermissionSetProps(uint pm, out uint pdwAction, out IntPtr ppvPermission); uint GetSigFromToken(uint mdSig, out IntPtr ppvSig); uint GetModuleRefProps(uint mur, StringBuilder szName, uint cchName); uint EnumModuleRefs(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rModuleRefs, uint cmax); uint GetTypeSpecFromToken(uint typespec, out IntPtr ppvSig); uint GetNameFromToken(uint tk); uint EnumUnresolvedMethods(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rMethods, uint cMax); uint GetUserString(uint stk, StringBuilder szString, uint cchString); uint GetPinvokeMap(uint tk, out uint pdwMappingFlags, StringBuilder szImportName, uint cchImportName, out uint pchImportName); uint EnumSignatures(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rSignatures, uint cmax); uint EnumTypeSpecs(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rTypeSpecs, uint cmax); uint EnumUserStrings(ref uint phEnum, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] uint[] rStrings, uint cmax); [PreserveSig] int GetParamForMethodIndex(uint md, uint ulParamSeq, out uint pParam); uint EnumCustomAttributes(ref uint phEnum, uint tk, uint tkType, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)] uint[] rCustomAttributes, uint cMax); uint GetCustomAttributeProps(uint cv, out uint ptkObj, out uint ptkType, out IntPtr ppBlob); uint FindTypeRef(uint tkResolutionScope, string szName); uint GetMemberProps(uint mb, out uint pClass, StringBuilder szMember, uint cchMember, out uint pchMember, out uint pdwAttr, out IntPtr ppvSigBlob, out uint pcbSigBlob, out uint pulCodeRVA, out uint pdwImplFlags, out uint pdwCPlusTypeFlag, out IntPtr ppValue); uint GetFieldProps(uint mb, out uint pClass, StringBuilder szField, uint cchField, out uint pchField, out uint pdwAttr, out IntPtr ppvSigBlob, out uint pcbSigBlob, out uint pdwCPlusTypeFlag, out IntPtr ppValue); uint GetPropertyProps(uint prop, out uint pClass, StringBuilder szProperty, uint cchProperty, out uint pchProperty, out uint pdwPropFlags, out IntPtr ppvSig, out uint pbSig, out uint pdwCPlusTypeFlag, out IntPtr ppDefaultValue, out uint pcchDefaultValue, out uint pmdSetter, out uint pmdGetter, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 14)] uint[] rmdOtherMethod, uint cMax); uint GetParamProps(uint tk, out uint pmd, out uint pulSequence, StringBuilder szName, uint cchName, out uint pchName, out uint pdwAttr, out uint pdwCPlusTypeFlag, out IntPtr ppValue); uint GetCustomAttributeByName(uint tkObj, string szName, out IntPtr ppData); [PreserveSig] [return: MarshalAs(UnmanagedType.Bool)] bool IsValidToken(uint tk); uint GetNestedClassProps(uint tdNestedClass); uint GetNativeCallConvFromSig(IntPtr pvSig, uint cbSig); int IsGlobal(uint pd); } internal class ModuleMetadata : IMetaDataEmit, IMetaDataImport { private readonly ModuleDefinition module; private Dictionary<uint, TypeDefinition> types; private Dictionary<uint, MethodDefinition> methods; public ModuleMetadata(ModuleDefinition module) { this.module = module; } private bool TryGetType(uint token, out TypeDefinition type) { if (types == null) { InitializeMetadata(module); } return types.TryGetValue(token, out type); } private bool TryGetMethod(uint token, out MethodDefinition method) { if (methods == null) { InitializeMetadata(module); } return methods.TryGetValue(token, out method); } private void InitializeMetadata(ModuleDefinition module) { //IL_0032: 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) types = new Dictionary<uint, TypeDefinition>(); methods = new Dictionary<uint, MethodDefinition>(); foreach (TypeDefinition type in module.GetTypes()) { Dictionary<uint, TypeDefinition> dictionary = types; MetadataToken metadataToken = ((MemberReference)type).MetadataToken; dictionary.Add(((MetadataToken)(ref metadataToken)).ToUInt32(), type); InitializeMethods(type); } } private void InitializeMethods(TypeDefinition type) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) Enumerator<MethodDefinition> enumerator = type.Methods.GetEnumerator(); try { while (enumerator.MoveNext()) { MethodDefinition current = enumerator.Current; Dictionary<uint, MethodDefinition> dictionary = methods; MetadataToken metadataToken = ((MemberReference)current).MetadataToken; dictionary.Add(((MetadataToken)(ref metadataToken)).ToUInt32(), current); } } finally { ((IDisposable)enumerator).Dispose(); } } public void SetModuleProps(string szName) { throw new NotImplementedException(); } public void Save(string szFile, uint dwSaveFlags) { throw new NotImplementedException(); } public void SaveToStream(IntPtr pIStream, uint dwSaveFlags) { throw new NotImplementedException(); } public uint GetSaveSize(uint fSave) { throw new NotImplementedException(); } public uint DefineTypeDef(IntPtr szTypeDef, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements) { throw new NotImplementedException(); } public uint DefineNestedType(IntPtr szTypeDef, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements, uint tdEncloser) { throw new NotImplementedException(); } public void SetHandler(object pUnk) { throw new NotImplementedException(); } public uint DefineMethod(uint td, IntPtr zName, uint dwMethodFlags, IntPtr pvSigBlob, uint cbSigBlob, uint ulCodeRVA, uint dwImplFlags) { throw new NotImplementedException(); } public void DefineMethodImpl(uint td, uint tkBody, uint tkDecl) { throw new NotImplementedException(); } public uint DefineTypeRefByName(uint tkResolutionScope, IntPtr szName) { throw new NotImplementedException(); } public uint DefineImportType(IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport pImport, uint tdImport, IntPtr pAssemEmit) { throw new NotImplementedException(); } public uint DefineMemberRef(uint tkImport, string szName, IntPtr pvSigBlob, uint cbSigBlob) { throw new NotImplementedException(); } public uint DefineImportMember(IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport pImport, uint mbMember, IntPtr pAssemEmit, uint tkParent) { throw new NotImplementedException(); } public uint DefineEvent(uint td, string szEvent, uint dwEventFlags, uint tkEventType, uint mdAddOn, uint mdRemoveOn, uint mdFire, IntPtr rmdOtherMethods) { throw new NotImplementedException(); } public void SetClassLayout(uint td, uint dwPackSize, IntPtr rFieldOffsets, uint ulClassSize) { throw new NotImplementedException(); } public void DeleteClassLayout(uint td) { throw new NotImplementedException(); } public void SetFieldMarshal(uint tk, IntPtr pvNativeType, uint cbNativeType) { throw new NotImplementedException(); } public void DeleteFieldMarshal(uint tk) { throw new NotImplementedException(); } public uint DefinePermissionSet(uint tk, uint dwAction, IntPtr pvPermission, uint cbPermission) { throw new NotImplementedException(); } public void SetRVA(uint md, uint ulRVA) { throw new NotImplementedException(); } public uint GetTokenFromSig(IntPtr pvSig, uint cbSig) { throw new NotImplementedException(); } public uint DefineModuleRef(string szName) { throw new NotImplementedException(); } public void SetParent(uint mr, uint tk) { throw new NotImplementedException(); } public uint GetTokenFromTypeSpec(IntPtr pvSig, uint cbSig) { throw new NotImplementedException(); } public void SaveToMemory(IntPtr pbData, uint cbData) { throw new NotImplementedException(); } public uint DefineUserString(string szString, uint cchString) { throw new NotImplementedException(); } public void DeleteToken(uint tkObj) { throw new NotImplementedException(); } public void SetMethodProps(uint md, uint dwMethodFlags, uint ulCodeRVA, uint dwImplFlags) { throw new NotImplementedException(); } public void SetTypeDefProps(uint td, uint dwTypeDefFlags, uint tkExtends, IntPtr rtkImplements) { throw new NotImplementedException(); } public void SetEventProps(uint ev, uint dwEventFlags, uint tkEventType, uint mdAddOn, uint mdRemoveOn, uint mdFire, IntPtr rmdOtherMethods) { throw new NotImplementedException(); } public uint SetPermissionSetProps(uint tk, uint dwAction, IntPtr pvPermission, uint cbPermission) { throw new NotImplementedException(); } public void DefinePinvokeMap(uint tk, uint dwMappingFlags, string szImportName, uint mrImportDLL) { throw new NotImplementedException(); } public void SetPinvokeMap(uint tk, uint dwMappingFlags, string szImportName, uint mrImportDLL) { throw new NotImplementedException(); } public void DeletePinvokeMap(uint tk) { throw new NotImplementedException(); } public uint DefineCustomAttribute(uint tkObj, uint tkType, IntPtr pCustomAttribute, uint cbCustomAttribute) { throw new NotImplementedException(); } public void SetCustomAttributeValue(uint pcv, IntPtr pCustomAttribute, uint cbCustomAttribute) { throw new NotImplementedException(); } public uint DefineField(uint td, string szName, uint dwFieldFlags, IntPtr pvSigBlob, uint cbSigBlob, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue) { throw new NotImplementedException(); } public uint DefineProperty(uint td, string szProperty, uint dwPropFlags, IntPtr pvSig, uint cbSig, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue, uint mdSetter, uint mdGetter, IntPtr rmdOtherMethods) { throw new NotImplementedException(); } public uint DefineParam(uint md, uint ulParamSeq, string szName, uint dwParamFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue) { throw new NotImplementedException(); } public void SetFieldProps(uint fd, uint dwFieldFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue) { throw new NotImplementedException(); } public void SetPropertyProps(uint pr, uint dwPropFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue, uint mdSetter, uint mdGetter, IntPtr rmdOtherMethods) { throw new NotImplementedException(); } public void SetParamProps(uint pd, string szName, uint dwParamFlags, uint dwCPlusTypeFlag, IntPtr pValue, uint cchValue) { throw new NotImplementedException(); } public uint DefineSecurityAttributeSet(uint tkObj, IntPtr rSecAttrs, uint cSecAttrs) { throw new NotImplementedException(); } public void ApplyEditAndContinue(object pImport) { throw new NotImplementedException(); } public uint TranslateSigWithScope(IntPtr pAssemImport, IntPtr pbHashValue, uint cbHashValue, IMetaDataImport import, IntPtr pbSigBlob, uint cbSigBlob, IntPtr pAssemEmit, IMetaDataEmit emit, IntPtr pvTranslatedSig, uint cbTranslatedSigMax) { throw new NotImplementedException(); } public void SetMethodImplFlags(uint md, uint dwImplFlags) { throw new NotImplementedException(); } public void SetFieldRVA(uint fd, uint ulRVA) { throw new NotImplementedException(); } public void Merge(IMetaDataImport pImport, IntPtr pHostMapToken, object pHandler) { throw new NotImplementedException(); } public void MergeEnd() { throw new NotImplementedException(); } public void CloseEnum(uint hEnum) { throw new NotImplementedException(); } public uint CountEnum(uint hEnum) { throw new NotImplementedException(); } public void ResetEnum(uint hEnum, uint ulPos) { throw new NotImplementedException(); } public uint EnumTypeDefs(ref uint phEnum, uint[] rTypeDefs, uint cMax) { throw new NotImplementedException(); } public uint EnumInterfaceImpls(ref uint phEnum, uint td, uint[] rImpls, uint cMax) { throw new NotImplementedException(); } public uint EnumTypeRefs(ref uint phEnum, uint[] rTypeRefs, uint cMax) { throw new NotImplementedException(); } public uint FindTypeDefByName(string szTypeDef, uint tkEnclosingClass) { throw new NotImplementedException(); } public Guid GetScopeProps(StringBuilder szName, uint cchName, out uint pchName) { throw new NotImplementedException(); } public uint GetModuleFromScope() { throw new NotImplementedException(); } public uint GetTypeDefProps(uint td, IntPtr szTypeDef, uint cchTypeDef, out uint pchTypeDef, IntPtr pdwTypeDefFlags) { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Expected I4, but got Unknown //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) if (!TryGetType(td, out var type)) { Marshal.WriteInt16(szTypeDef, 0); pchTypeDef = 1u; return 0u; } WriteString(((TypeReference)type).IsNested ? ((MemberReference)type).Name : ((MemberReference)type).FullName, szTypeDef, cchTypeDef, out pchTypeDef); WriteIntPtr(pdwTypeDefFlags, (uint)(int)type.Attributes); if (type.BaseType == null) { return 0u; } MetadataToken metadataToken = ((MemberReference)type.BaseType).MetadataToken; return ((MetadataToken)(ref metadataToken)).ToUInt32(); } private static void WriteIntPtr(IntPtr ptr, uint value) { if (!(ptr == IntPtr.Zero)) { Marshal.WriteInt32(ptr, (int)value); } } private static void WriteString(string str, IntPtr buffer, uint bufferSize, out uint chars) { uint num = ((str.Length + 1 >= bufferSize) ? (bufferSize - 1) : ((uint)str.Length)); chars = num + 1; int num2 = 0; for (int i = 0; i < num; i++) { Marshal.WriteInt16(buffer, num2, str[i]); num2 += 2; } Marshal.WriteInt16(buffer, num2, 0); } public uint GetInterfaceImplProps(uint iiImpl, out uint pClass) { throw new NotImplementedException(); } public uint GetTypeRefProps(uint tr, out uint ptkResolutionScope, StringBuilder szName, uint cchName) { throw new NotImplementedException(); } public uint ResolveTypeRef(uint tr, ref Guid riid, out object ppIScope) { throw new NotImplementedException(); } public uint EnumMembers(ref uint phEnum, uint cl, uint[] rMembers, uint cMax) { throw new NotImplementedException(); } public uint EnumMembersWithName(ref uint phEnum, uint cl, string szName, uint[] rMembers, uint cMax) { throw new NotImplementedException(); } public uint EnumMethods(ref uint phEnum, uint cl, IntPtr rMethods, uint cMax) { throw new NotImplementedException(); } public uint EnumMethodsWithName(ref uint phEnum, uint cl, string szName, uint[] rMethods, uint cMax) { throw new NotImplementedException(); } public uint EnumFields(ref uint phEnum, uint cl, IntPtr rFields, uint cMax) { throw new NotImplementedException(); } public uint EnumFieldsWithName(ref uint phEnum, uint cl, string szName, uint[] rFields, uint cMax) { throw new NotImplementedException(); } public uint EnumParams(ref uint phEnum, uint mb, uint[] rParams, uint cMax) { throw new NotImplementedException(); } public uint EnumMemberRefs(ref uint phEnum, uint tkParent, uint[] rMemberRefs, uint cMax) { throw new NotImplementedException(); } public uint EnumMethodImpls(ref uint phEnum, uint td, uint[] rMethodBody, uint[] rMethodDecl, uint cMax) { throw new NotImplementedException(); } public uint EnumPermissionSets(ref uint phEnum, uint tk, uint dwActions, uint[] rPermission, uint cMax) { throw new NotImplementedException(); } public uint FindMember(uint td, string szName, byte[] pvSigBlob, uint cbSigBlob) { throw new NotImplementedException(); } public uint FindMethod(uint td, string szName, byte[] pvSigBlob, uint cbSigBlob) { throw new NotImplementedException(); } public uint FindField(uint td, string szName, byte[] pvSigBlob, uint cbSigBlob) { throw new NotImplementedException(); } public uint FindMemberRef(uint td, string szName, byte[] pvSigBlob, uint cbSigBlob) { throw new NotImplementedException(); } public uint GetMethodProps(uint mb, out uint pClass, IntPtr szMethod, uint cchMethod, out uint pchMethod, IntPtr pdwAttr, IntPtr ppvSigBlob, IntPtr pcbSigBlob, IntPtr pulCodeRVA) { //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_0043: 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_0061: Expected I4, but got Unknown if (!TryGetMethod(mb, out var method)) { Marshal.WriteInt16(szMethod, 0); pchMethod = 1u; pClass = 0u; return 0u; } MetadataToken metadataToken = ((MemberReference)method.DeclaringType).MetadataToken; pClass = ((MetadataToken)(ref metadataToken)).ToUInt32(); WriteString(((MemberReference)method).Name, szMethod, cchMethod, out pchMethod); WriteIntPtr(pdwAttr, (uint)(int)method.Attributes); WriteIntPtr(pulCodeRVA, (uint)method.RVA); return (uint)(int)method.ImplAttributes; } public uint GetMemberRefProps(uint mr, ref uint ptk, StringBuilder szMember, uint cchMember, out uint pchMember, out IntPtr ppvSigBlob) { throw new NotImplementedException(); } public uint EnumProperties(ref uint phEnum, uint td, IntPtr rProperties, uint cMax) { throw new NotImplementedException(); } public uint EnumEvents(ref uint phEnum, uint td, IntPtr rEvents, uint cMax) { throw new NotImplementedException(); } public uint GetEventProps(uint ev, out uint pClass, StringBuilder szEvent, uint cchEvent, out uint pchEvent, out uint pdwEventFlags, out uint ptkEventType, out uint pmdAddOn, out uint pmdRemoveOn, out uint pmdFire, uint[] rmdOtherMethod, uint cMax) { throw new NotImplementedException(); } public uint EnumMethodSemantics(ref uint phEnum, uint mb, uint[] rEventProp, uint cMax) { throw new NotImplementedException(); } public uint GetMethodSemantics(uint mb, uint tkEventProp) { throw new NotImplementedException(); } public uint GetClassLayout(uint td, out uint pdwPackSize, IntPtr rFieldOffset, uint cMax, out uint pcFieldOffset) { throw new NotImplementedException(); } public uint GetFieldMarshal(uint tk, out IntPtr ppvNativeType) { throw new NotImplementedException(); } public uint GetRVA(uint tk, out uint pulCodeRVA) { throw new NotImplementedException(); } public uint GetPermissionSetProps(uint pm, out uint pdwAction, out IntPtr ppvPermission) { throw new NotImplementedException(); } public uint GetSigFromToken(uint mdSig, out IntPtr ppvSig) { throw new NotImplementedException(); } public uint GetModuleRefProps(uint mur, StringBuilder szName, uint cchName) { throw new NotImplementedException(); } public uint EnumModuleRefs(ref uint phEnum, uint[] rModuleRefs, uint cmax) { throw new NotImplementedException(); } public uint GetTypeSpecFromToken(uint typespec, out IntPtr ppvSig) { throw new NotImplementedException(); } public uint GetNameFromToken(uint tk) { throw new NotImplementedException(); } public uint EnumUnresolvedMethods(ref uint phEnum, uint[] rMethods, uint cMax) { throw new NotImplementedException(); } public uint GetUserString(uint stk, StringBuilder szString, uint cchString) { throw new NotImplementedException(); } public uint GetPinvokeMap(uint tk, out uint pdwMappingFlags, StringBuilder szImportName, uint cchImportName, out uint pchImportName) { throw new NotImplementedException(); } public uint EnumSignatures(ref uint phEnum, uint[] rSignatures, uint cmax) { throw new NotImplementedException(); } public uint EnumTypeSpecs(ref uint phEnum, uint[] rTypeSpecs, uint cmax) { throw new NotImplementedException(); } public uint EnumUserStrings(ref uint phEnum, uint[] rStrings, uint cmax) { throw new NotImplementedException(); } public int GetParamForMethodIndex(uint md, uint ulParamSeq, out uint pParam) { throw new NotImplementedException(); } public uint EnumCustomAttributes(ref uint phEnum, uint tk, uint tkType, uint[] rCustomAttributes, uint cMax) { throw new NotImplementedException(); } public uint GetCustomAttributeProps(uint cv, out uint ptkObj, out uint ptkType, out IntPtr ppBlob) { throw new NotImplementedException(); } public uint FindTypeRef(uint tkResolutionScope, string szName) { throw new NotImplementedException(); } public uint GetMemberProps(uint mb, out uint pClass, StringBuilder szMember, uint cchMember, out uint pchMember, out uint pdwAttr, out IntPtr ppvSigBlob, out uint pcbSigBlob, out uint pulCodeRVA, out uint pdwImplFlags, out uint pdwCPlusTypeFlag, out IntPtr ppValue) { throw new NotImplementedException(); } public uint GetFieldProps(uint mb, out uint pClass, StringBuilder szField, uint cchField, out uint pchField, out uint pdwAttr, out IntPtr ppvSigBlob, out uint pcbSigBlob, out uint pdwCPlusTypeFlag, out IntPtr ppValue) { throw new NotImplementedException(); } public uint GetPropertyProps(uint prop, out uint pClass, StringBuilder szProperty, uint cchProperty, out uint pchProperty, out uint pdwPropFlags, out IntPtr ppvSig, out uint pbSig, out uint pdwCPlusTypeFlag, out IntPtr ppDefaultValue, out uint pcchDefaultValue, out uint pmdSetter, out uint pmdGetter, uint[] rmdOtherMethod, uint cMax) { throw new NotImplementedException(); } public uint GetParamProps(uint tk, out uint pmd, out uint pulSequence, StringBuilder szName, uint cchName, out uint pchName, out uint pdwAttr, out uint pdwCPlusTypeFlag, out IntPtr ppValue) { throw new NotImplementedException(); } public uint GetCustomAttributeByName(uint tkObj, string szName, out IntPtr ppData) { throw new NotImplementedException(); } public bool IsValidToken(uint tk) { throw new NotImplementedException(); } public uint GetNestedClassProps(uint tdNestedClass) { //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 (!TryGetType(tdNestedClass, out var type)) { return 0u; } if (!((TypeReference)type).IsNested) { return 0u; } MetadataToken metadataToken = ((MemberReference)type.DeclaringType).MetadataToken; return ((MetadataToken)(ref metadataToken)).ToUInt32(); } public uint GetNativeCallConvFromSig(IntPtr pvSig, uint cbSig) { throw new NotImplementedException(); } public int IsGlobal(uint pd) { throw new NotImplementedException(); } } public class NativePdbReader : ISymbolReader, IDisposable { private int age; private Guid guid; private readonly Disposable<Stream> pdb_file; private readonly Dictionary<string, Document> documents = new Dictionary<string, Document>(); private readonly Dictionary<uint, PdbFunction> functions = new Dictionary<uint, PdbFunction>(); private readonly Dictionary<PdbScope, ImportDebugInformation> imports = new Dictionary<PdbScope, ImportDebugInformation>(); internal NativePdbReader(Disposable<Stream> file) { //IL_0028: 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) pdb_file = file; } public ISymbolWriterProvider GetWriterProvider() { return (ISymbolWriterProvider)(object)new NativePdbWriterProvider(); } public bool ProcessDebugHeader(ImageDebugHeader header) { //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_0022: Invalid comparison between Unknown and I4 if (!header.HasEntries) { return false; } ImageDebugHeaderEntry codeViewEntry = Mixin.GetCodeViewEntry(header); if (codeViewEntry == null) { return false; } if ((int)codeViewEntry.Directory.Type != 2) { return false; } byte[] data = codeViewEntry.Data; if (data.Length < 24) { return false; } if (ReadInt32(data, 0) != 1396986706) { return false; } byte[] array = new byte[16]; Buffer.BlockCopy(data, 4, array, 0, 16); guid = new Guid(array); age = ReadInt32(data, 20); return PopulateFunctions(); } private static int ReadInt32(byte[] bytes, int start) { return bytes[start] | (bytes[start + 1] << 8) | (bytes[start + 2] << 16) | (bytes[start + 3] << 24); } private bool PopulateFunctions() { //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_0008: Unknown result type (might be due to invalid IL or missing references) Disposable<Stream> val = pdb_file; try { Dictionary<uint, PdbTokenLine> tokenToSourceMapping; string sourceServerData; int num; Guid guid; PdbFunction[] array = PdbFile.LoadFunctions(pdb_file.value, out tokenToSourceMapping, out sourceServerData, out num, out guid); if (this.guid != guid) { return false; } PdbFunction[] array2 = array; foreach (PdbFunction pdbFunction in array2) { functions.Add(pdbFunction.token, pdbFunction); } } finally { ((IDisposable)val).Dispose(); } return true; } public MethodDebugInformation Read(MethodDefinition method) { //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_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Expected O, but got Unknown //IL_003c: 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_0043: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0054: 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_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_0118: Expected O, but got Unknown //IL_0195: Unknown result type (might be due to invalid IL or missing references) //IL_019c: Expected O, but got Unknown //IL_01c3: Unknown result type (might be due to invalid IL or missing references) //IL_01db: 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_022e: Expected O, but got Unknown //IL_014f: Unknown result type (might be due to invalid IL or missing references) //IL_0159: Expected O, but got Unknown MetadataToken metadataToken = ((MemberReference)method).MetadataToken; if (!functions.TryGetValue(((MetadataToken)(ref metadataToken)).ToUInt32(), out var value)) { return null; } MethodDebugInformation val = new MethodDebugInformation(method); ReadSequencePoints(value, val); val.scope = (ScopeDebugInformation)((!Mixin.IsNullOrEmpty<PdbScope>(value.scopes)) ? ((object)ReadScopeAndLocals(value.scopes[0], val)) : ((object)new ScopeDebugInformation { Start = new InstructionOffset(0), End = new InstructionOffset((int)value.length) })); uint tokenOfMethodWhoseUsingInfoAppliesToThisMethod = value.tokenOfMethodWhoseUsingInfoAppliesToThisMethod; MetadataToken metadataToken2 = ((MemberReference)method).MetadataToken; if (tokenOfMethodWhoseUsingInfoAppliesToThisMethod != ((MetadataToken)(ref metadataToken2)).ToUInt32() && value.tokenOfMethodWhoseUsingInfoAppliesToThisMethod != 0) { val.scope.import = GetImport(value.tokenOfMethodWhoseUsingInfoAppliesToThisMethod, ((MemberReference)method).Module); } if (value.scopes.Length > 1) { for (int i = 1; i < value.scopes.Length; i++) { ScopeDebugInformation val2 = ReadScopeAndLocals(value.scopes[i], val); if (!AddScope(val.scope.Scopes, val2)) { val.scope.Scopes.Add(val2); } } } if (value.iteratorScopes != null) { StateMachineScopeDebugInformation val3 = new StateMachineScopeDebugInformation(); foreach (ILocalScope iteratorScope in value.iteratorScopes) { val3.Scopes.Add(new StateMachineScope((int)iteratorScope.Offset, (int)(iteratorScope.Offset + iteratorScope.Length + 1))); } ((DebugInformation)val).CustomDebugInformations.Add((CustomDebugInformation)(object)val3); } if (value.synchronizationInformation != null) { AsyncMethodBodyDebugInformation val4 = new AsyncMethodBodyDebugInformation((int)value.synchronizationInformation.GeneratedCatchHandlerOffset); PdbSynchronizationPoint[] synchronizationPoints = value.synchronizationInformation.synchronizationPoints; foreach (PdbSynchronizationPoint pdbSynchronizationPoint in synchronizationPoints) { val4.Yields.Add(new InstructionOffset((int)pdbSynchronizationPoint.SynchronizeOffset)); val4.Resumes.Add(new InstructionOffset((int)pdbSynchronizationPoint.ContinuationOffset)); val4.ResumeMethods.Add(method); } ((DebugInformation)val).CustomDebugInformations.Add((CustomDebugInformation)(object)val4); val.StateMachineKickOffMethod = (MethodDefinition)((MemberReference)method).Module.LookupToken((int)value.synchronizationInformation.kickoffMethodToken); } return val; } private Collection<ScopeDebugInformation> ReadScopeAndLocals(PdbScope[] scopes, MethodDebugInformation info) { Collection<ScopeDebugInformation> val = new Collection<ScopeDebugInformation>(scopes.Length); foreach (PdbScope pdbScope in scopes) { if (pdbScope != null) { val.Add(ReadScopeAndLocals(pdbScope, info)); } } return val; } private ScopeDebugInformation ReadScopeAndLocals(PdbScope scope, MethodDebugInformation info) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Expected O, but got Unknown //IL_014b: Unknown result type (might be due to invalid IL or missing references) //IL_0155: Expected O, but got Unknown ScopeDebugInformation val = new ScopeDebugInformation(); val.Start = new InstructionOffset((int)scope.offset); val.End = new InstructionOffset((int)(scope.offset + scope.length)); if (!Mixin.IsNullOrEmpty<PdbSlot>(scope.slots)) { val.variables = new Collection<VariableDebugInformation>(scope.slots.Length); PdbSlot[] slots = scope.slots; foreach (PdbSlot pdbSlot in slots) { if ((pdbSlot.flags & 1) == 0) { VariableDebugInformation val2 = new VariableDebugInformation((int)pdbSlot.slot, pdbSlot.name); if ((pdbSlot.flags & 4u) != 0) { val2.IsDebuggerHidden = true; } val.variables.Add(val2); } } } if (!Mixin.IsNullOrEmpty<PdbConstant>(scope.constants)) { val.constants = new Collection<ConstantDebugInformation>(scope.constants.Length); PdbConstant[] constants = scope.constants; foreach (PdbConstant pdbConstant in constants) { TypeReference val3 = ((MemberReference)info.Method).Module.Read<PdbConstant, TypeReference>(pdbConstant, (Func<PdbConstant, MetadataReader, TypeReference>)((PdbConstant c, MetadataReader r) => r.ReadConstantSignature(new MetadataToken(c.token)))); object obj = pdbConstant.value; if (val3 != null && !val3.IsValueType && obj is int && (int)obj == 0) { obj = null; } val.constants.Add(new ConstantDebugInformation(pdbConstant.name, val3, obj)); } } if (!Mixin.IsNullOrEmpty<string>(scope.usedNamespaces)) { if (imports.TryGetValue(scope, out var value)) { val.import = value; } else { value = GetImport(scope, ((MemberReference)info.Method).Module); imports.Add(scope, value); val.import = value; } } val.scopes = ReadScopeAndLocals(scope.scopes, info); return val; } private static bool AddScope(Collection<ScopeDebugInformation> scopes, ScopeDebugInformation scope) { //IL_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_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_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_004a: 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_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) Enumerator<ScopeDebugInformation> enumerator = scopes.GetEnumerator(); try { while (enumerator.MoveNext()) { ScopeDebugInformation current = enumerator.Current; if (current.HasScopes && AddScope(current.Scopes, scope)) { return true; } InstructionOffset val = scope.Start; int offset = ((InstructionOffset)(ref val)).Offset; val = current.Start; if (offset >= ((InstructionOffset)(ref val)).Offset) { val = scope.End; int offset2 = ((InstructionOffset)(ref val)).Offset; val = current.End; if (offset2 <= ((InstructionOffset)(ref val)).Offset) { current.Scopes.Add(scope); return true; } } } } finally { ((IDisposable)enumerator).Dispose(); } return false; } private ImportDebugInformation GetImport(uint token, ModuleDefinition module) { if (!functions.TryGetValue(token, out var value)) { return null; } if (value.scopes.Length != 1) { return null; } PdbScope pdbScope = value.scopes[0]; if (imports.TryGetValue(pdbScope, out var value2)) { return value2; } value2 = GetImport(pdbScope, module); imports.Add(pdbScope, value2); return value2; } private static ImportDebugInformation GetImport(PdbScope scope, ModuleDefinition module) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Expected O, but got Unknown //IL_014e: 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_015d: Expected O, but got Unknown //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Expected O, but got Unknown //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Expected O, but got Unknown //IL_007a: 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_0089: Expected O, but got Unknown //IL_016e: Unknown result type (might be due to invalid IL or missing references) //IL_0173: Unknown result type (might be due to invalid IL or missing references) //IL_0183: Expected O, but got Unknown //IL_0134: Unknown result type (might be due to invalid IL or missing references) //IL_0139: Unknown result type (might be due to invalid IL or missing references) //IL_0141: Unknown result type (might be due to invalid IL or missing references) //IL_014b: Expected O, but got Unknown //IL_010a: 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_0117: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Expected O, but got Unknown if (Mixin.IsNullOrEmpty<string>(scope.usedNamespaces)) { return null; } ImportDebugInformation val = new ImportDebugInformation(); string[] usedNamespaces = scope.usedNamespaces; foreach (string text in usedNamespaces) { if (string.IsNullOrEmpty(text)) { continue; } ImportTarget val2 = null; string text2 = text.Substring(1); switch (text[0]) { case 'U': val2 = new ImportTarget((ImportTargetKind)1) { @namespace = text2 }; break; case 'T': { TypeReference val4 = TypeParser.ParseType(module, text2, false); if (val4 != null) { val2 = new ImportTarget((ImportTargetKind)3) { type = val4 }; } break; } case 'A': { int num = text.IndexOf(' '); if (num < 0) { val2 = new ImportTarget((ImportTargetKind)1) { @namespace = text }; break; } string alias = text.Substring(1, num - 1); string text3 = text.Substring(num + 2); switch (text[num + 1]) { case 'U': val2 = new ImportTarget((ImportTargetKind)7) { alias = alias, @namespace = text3 }; break; case 'T': { TypeReference val3 = TypeParser.ParseType(module, text3, false); if (val3 != null) { val2 = new ImportTarget((ImportTargetKind)9) { alias = alias, type = val3 }; } break; } } break; } case '*': val2 = new ImportTarget((ImportTargetKind)1) { @namespace = text2 }; break; case '@': if (!text2.StartsWith("P:")) { continue; } val2 = new ImportTarget((ImportTargetKind)1) { @namespace = text2.Substring(2) }; break; } if (val2 != null) { val.Targets.Add(val2); } } return val; } private void ReadSequencePoints(PdbFunction function, MethodDebugInformation info) { if (function.lines != null) { info.sequence_points = new Collection<SequencePoint>(); PdbLines[] lines = function.lines; foreach (PdbLines lines2 in lines) { ReadLines(lines2, info); } } } private void ReadLines(PdbLines lines, MethodDebugInformation info) { Document document = GetDocument(lines.file); PdbLine[] lines2 = lines.lines; for (int i = 0; i < lines2.Length; i++) { ReadLine(lines2[i], document, info); } } private static void ReadLine(PdbLine line, Document document, MethodDebugInformation info) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Expected O, but got Unknown SequencePoint val = new SequencePoint((int)line.offset, document); val.StartLine = (int)line.lineBegin; val.StartColumn = line.colBegin; val.EndLine = (int)line.lineEnd; val.EndColumn = line.colEnd; info.sequence_points.Add(val); } private Document GetDocument(PdbSource source) { //IL_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_0026: 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_0037: 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_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Expected O, but got Unknown string name = source.name; if (documents.TryGetValue(name, out var value)) { return value; } value = new Document(name) { Language = PdbGuidMapping.ToLanguage(source.language), LanguageVendor = PdbGuidMapping.ToVendor(source.vendor), Type = PdbGuidMapping.ToType(source.doctype) }; documents.Add(name, value); return value; } public void Dispose() { //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) pdb_file.Dispose(); } } public class NativePdbWriter : ISymbolWriter, IDisposable { private readonly ModuleDefinition module; private readonly MetadataBuilder metadata; private readonly SymWriter writer; private readonly Dictionary<string, SymDocumentWriter> documents; private readonly Dictionary<ImportDebugInformation, MetadataToken> import_info_to_parent; internal NativePdbWriter(ModuleDefinition module, SymWriter writer) { this.module = module; metadata = module.metadata_builder; this.writer = writer; documents = new Dictionary<string, SymDocumentWriter>(); import_info_to_parent = new Dictionary<ImportDebugInformation, MetadataToken>(); } public ISymbolReaderProvider GetReaderProvider() { return (ISymbolReaderProvider)(object)new NativePdbReaderProvider(); } public ImageDebugHeader GetDebugHeader() { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Expected O, but got Unknown //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Expected O, but got Unknown ImageDebugDirectory idd; byte[] debugInfo = writer.GetDebugInfo(out idd); idd.TimeDateStamp = (int)module.timestamp; return new ImageDebugHeader(new ImageDebugHeaderEntry(idd, debugInfo)); } public void Write(MethodDebugInformation info) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_005c: 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) MetadataToken metadataToken = ((MemberReference)info.method).MetadataToken; int methodToken = ((MetadataToken)(ref metadataToken)).ToInt32(); if (info.HasSequencePoints || info.scope != null || ((DebugInformation)info).HasCustomDebugInformations || info.StateMachineKickOffMethod != null) { writer.OpenMethod(methodToken); if (!Mixin.IsNullOrEmpty<SequencePoint>(info.sequence_points)) { DefineSequencePoints(info.sequence_points); } MetadataToken import_parent = default(MetadataToken); if (info.scope != null) { DefineScope(info.scope, info, out import_parent); } DefineCustomMetadata(info, import_parent); writer.CloseMethod(); } } private void DefineCustomMetadata(MethodDebugInformation info, MetadataToken import_parent) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0071: 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_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) CustomMetadataWriter customMetadataWriter = new CustomMetadataWriter(writer); if (((MetadataToken)(ref import_parent)).RID != 0) { customMetadataWriter.WriteForwardInfo(import_parent); } else if (info.scope != null && info.scope.Import != null && info.scope.Import.HasTargets) { customMetadataWriter.WriteUsingInfo(info.scope.Import); } if (info.Method.HasCustomAttributes) { Enumerator<CustomAttribute> enumerator = info.Method.CustomAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttribute current = enumerator.Current; TypeReference attributeType = current.AttributeType; if (Mixin.IsTypeOf(attributeType, "System.Runtime.CompilerServices", "IteratorStateMachineAttribute") || Mixin.IsTypeOf(attributeType, "System.Runtime.CompilerServices", "AsyncStateMachineAttribute")) { CustomAttributeArgument val = current.ConstructorArguments[0]; object value = ((CustomAttributeArgument)(ref val)).Value; TypeReference val2 = (TypeReference)((value is TypeReference) ? value : null); if (val2 != null) { customMetadataWriter.WriteForwardIterator(val2); } } } } finally { ((IDisposable)enumerator).Dispose(); } } if (((DebugInformation)info).HasCustomDebugInformations) { CustomDebugInformation? obj = ((IEnumerable<CustomDebugInformation>)((DebugInformation)info).CustomDebugInformations).FirstOrDefault((Func<CustomDebugInformation, bool>)((CustomDebugInformation cdi) => (int)cdi.Kind == 1)); StateMachineScopeDebugInformation val3 = (StateMachineScopeDebugInformation)(object)((obj is StateMachineScopeDebugInformation) ? obj : null); if (val3 != null) { customMetadataWriter.WriteIteratorScopes(val3, info); } } customMetadataWriter.WriteCustomMetadata(); DefineAsyncCustomMetadata(info); } private void DefineAsyncCustomMetadata(MethodDebugInformation info) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Expected O, but got Unknown //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0051: 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_0066: 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_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) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) if (!((DebugInformation)info).HasCustomDebugInformations) { return; } Enumerator<CustomDebugInformation> enumerator = ((DebugInformation)info).CustomDebugInformations.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomDebugInformation current = enumerator.Current; AsyncMethodBodyDebugInformation val = (AsyncMethodBodyDebugInformation)(object)((current is AsyncMethodBodyDebugInformation) ? current : null); if (val == null) { continue; } using MemoryStream memoryStream = new MemoryStream(); BinaryStreamWriter val2 = new BinaryStreamWriter((Stream)memoryStream); int num; MetadataToken metadataToken; if (info.StateMachineKickOffMethod == null) { num = 0; } else { metadataToken = ((MemberReference)info.StateMachineKickOffMethod).MetadataToken; num = (int)((MetadataToken)(ref metadataToken)).ToUInt32(); } val2.WriteUInt32((uint)num); InstructionOffset val3 = val.CatchHandler; val2.WriteUInt32((uint)((InstructionOffset)(ref val3)).Offset); val2.WriteUInt32((uint)val.Resumes.Count); for (int i = 0; i < val.Resumes.Count; i++) { val3 = val.Yields[i]; val2.WriteUInt32((uint)((InstructionOffset)(ref val3)).Offset); metadataToken = ((MemberReference)val.resume_methods[i]).MetadataToken; val2.WriteUInt32(((MetadataToken)(ref metadataToken)).ToUInt32()); val3 = val.Resumes[i]; val2.WriteUInt32((uint)((InstructionOffset)(ref val3)).Offset); } writer.DefineCustomMetadata("asyncMethodInfo", memoryStream.ToArray()); } } finally { ((IDisposable)enumerator).Dispose(); } } private void DefineScope(ScopeDebugInformation scope, MethodDebugInformation info, out MetadataToken import_parent) { //IL_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_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_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_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Invalid comparison between Unknown and I4 //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Invalid comparison between Unknown and I4 //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Invalid comparison between Unknown and I4 //IL_01a0: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Invalid comparison between Unknown and I4 //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Invalid comparison between Unknown and I4 InstructionOffset val = scope.Start; int offset = ((InstructionOffset)(ref val)).Offset; val = scope.End; int num; if (!((InstructionOffset)(ref val)).IsEndOfMethod) { val = scope.End; num = ((InstructionOffset)(ref val)).Offset; } else { num = info.code_size; } int num2 = num; import_parent = new MetadataToken(0u); writer.OpenScope(offset); if (scope.Import != null && scope.Import.HasTargets && !import_info_to_parent.TryGetValue(info.scope.Import, out import_parent)) { Enumerator<ImportTarget> enumerator = scope.Import.Targets.GetEnumerator(); try { while (enumerator.MoveNext()) { ImportTarget current = enumerator.Current; ImportTargetKind kind = current.Kind; if ((int)kind <= 3) { if ((int)kind != 1) { if ((int)kind == 3) { writer.UsingNamespace("T" + TypeParser.ToParseable(current.type, true)); } } else { writer.UsingNamespace("U" + current.@namespace); } } else if ((int)kind != 7) { if ((int)kind == 9) { writer.UsingNamespace("A" + current.Alias + " T" + TypeParser.ToParseable(current.type, true)); } } else { writer.UsingNamespace("A" + current.Alias + " U" + current.@namespace); } } } finally { ((IDisposable)enumerator).Dispose(); } import_info_to_parent.Add(info.scope.Import, ((MemberReference)info.method).MetadataToken); } int local_var_token = ((MetadataToken)(ref info.local_var_token)).ToInt32(); if (!Mixin.IsNullOrEmpty<VariableDebugInformation>(scope.variables)) { for (int i = 0; i < scope.variables.Count; i++) { VariableDebugInformation variable = scope.variables[i]; DefineLocalVariable(variable, local_var_token, offset, num2); } } if (!Mixin.IsNullOrEmpty<ConstantDebugInformation>(scope.constants)) { for (int j = 0; j < scope.constants.Count; j++) { ConstantDebugInformation constant = scope.constants[j]; DefineConstant(constant); } } if (!Mixin.IsNullOrEmpty<ScopeDebugInformation>(scope.scopes)) { for (int k = 0; k < scope.scopes.Count; k++) { DefineScope(scope.scopes[k], info, out var _); } } writer.CloseScope(num2); } private void DefineSequencePoints(Collection<SequencePoint> sequence_points) { for (int i = 0; i < sequence_points.Count; i++) { SequencePoint val = sequence_points[i]; writer.DefineSequencePoints(GetDocument(val.Document), new int[1] { val.Offset }, new int[1] { val.StartLine }, new int[1] { val.StartColumn }, new int[1] { val.EndLine }, new int[1] { val.EndColumn }); } } private void DefineLocalVariable(VariableDebugInformation variable, int local_var_token, int start_offset, int end_offset) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) writer.DefineLocalVariable2(variable.Name, variable.Attributes, local_var_token, variable.Index, 0, 0, start_offset, end_offset); } private void DefineConstant(ConstantDebugInformation constant) { uint num = metadata.AddStandAloneSignature(metadata.GetConstantTypeBlobIndex(constant.ConstantType)); MetadataToken val = default(MetadataToken); ((MetadataToken)(ref val))..ctor((TokenType)285212672, num); writer.DefineConstant2(constant.Name, constant.Value, ((MetadataToken)(ref val)).ToInt32()); } private SymDocumentWriter GetDocument(Document document) { if (document == null) { return null; } if (documents.TryGetValue(document.Url, out var value)) { return value; } value = writer.DefineDocument(document.Url, document.LanguageGuid, document.LanguageVendorGuid, document.TypeGuid); documents[document.Url] = value; return value; } public void Dispose() { //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) MethodDefinition entryPoint = module.EntryPoint; if (entryPoint != null) { SymWriter symWriter = writer; MetadataToken metadataToken = ((MemberReference)entryPoint).MetadataToken; symWriter.SetUserEntryPoint(((MetadataToken)(ref metadataToken)).ToInt32()); } writer.Close(); } } internal enum CustomMetadataType : byte { UsingInfo = 0, ForwardInfo = 1, IteratorScopes = 3, ForwardIterator = 4 } internal class CustomMetadataWriter : IDisposable { private readonly SymWriter sym_writer; private readonly MemoryStream stream; private readonly BinaryStreamWriter writer; private int count; private const byte version = 4; public CustomMetadataWriter(SymWriter sym_writer) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Expected O, but got Unknown this.sym_writer = sym_writer; stream = new MemoryStream(); writer = new BinaryStreamWriter((Stream)stream); writer.WriteByte((byte)4); writer.WriteByte((byte)0); writer.Align(4); } public void WriteUsingInfo(ImportDebugInformation import_info) { Write(CustomMetadataType.UsingInfo, delegate { writer.WriteUInt16((ushort)1); writer.WriteUInt16((ushort)import_info.Targets.Count); }); } public void WriteForwardInfo(MetadataToken import_parent) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) Write(CustomMetadataType.ForwardInfo, delegate { writer.WriteUInt32(((MetadataToken)(ref import_parent)).ToUInt32()); }); } public void WriteIteratorScopes(StateMachineScopeDebugInformation state_machine, MethodDebugInformation debug_info) { Write(CustomMetadataType.IteratorScopes, delegate { //IL_0023: 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_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_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_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) Collection<StateMachineScope> scopes = state_machine.Scopes; writer.WriteInt32(scopes.Count); Enumerator<StateMachineScope> enumerator = scopes.GetEnumerator(); try { while (enumerator.MoveNext()) { StateMachineScope current = enumerator.Current; InstructionOffset val = current.Start; int offset = ((InstructionOffset)(ref val)).Offset; val = current.End; int num; if (!((InstructionOffset)(ref val)).IsEndOfMethod) { val = current.End; num = ((InstructionOffset)(ref val)).Offset; } else { num = debug_info.code_size; } int num2 = num; writer.WriteInt32(offset); writer.WriteInt32(num2 - 1); } } finally { ((IDisposable)enumerator).Dispose(); } }); } public void WriteForwardIterator(TypeReference type) { Write(CustomMetadataType.ForwardIterator, delegate { writer.WriteBytes(Encoding.Unicode.GetBytes(((MemberReference)type).Name)); }); } private void Write(CustomMetadataType type, Action write) { count++; writer.WriteByte((byte)4); writer.WriteByte((byte)type); writer.Align(4); int position = writer.Position; writer.WriteUInt32(0u); write(); writer.Align(4); int position2 = writer.Position; int num = position2 - position + 4; writer.Position = position; writer.WriteInt32(num); writer.Position = position2; } public void WriteCustomMetadata() { if (count != 0) { ((BinaryWriter)(object)writer).BaseStream.Position = 1L; writer.WriteByte((byte)count); ((BinaryWriter)(object)writer).Flush(); sym_writer.DefineCustomMetadata("MD2", stream.ToArray()); } } public void Dispose() { stream.Dispose(); } } public sealed class NativePdbReaderProvider : ISymbolReaderProvider { public ISymbolReader GetSymbolReader(ModuleDefinition module, string fileName) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) Mixin.CheckModule(module); Mixin.CheckFileName(fileName); return (ISymbolReader)(object)new NativePdbReader(Disposable.Owned<Stream>((Stream)File.OpenRead(Mixin.GetPdbFileName(fileName)))); } public ISymbolReader GetSymbolReader(ModuleDefinition module, Stream symbolStream) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) Mixin.CheckModule(module); Mixin.CheckStream((object)symbolStream); return (ISymbolReader)(object)new NativePdbReader(Disposable.NotOwned<Stream>(symbolStream)); } } public sealed class PdbReaderProvider : ISymbolReaderProvider { public ISymbolReader GetSymbolReader(ModuleDefinition module, string fileName) { //IL_0048: 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) Mixin.CheckModule(module); Mixin.CheckFileName(fileName); if (module.HasDebugHeader && Mixin.GetEmbeddedPortablePdbEntry(module.GetDebugHeader()) != null) { return new EmbeddedPortablePdbReaderProvider().GetSymbolReader(module, fileName); } if (!Mixin.IsPortablePdb(Mixin.GetPdbFileName(fileName))) { return new NativePdbReaderProvider().GetSymbolReader(module, fileName); } return new PortablePdbReaderProvider().GetSymbolReader(module, fileName); } public ISymbolReader GetSymbolReader(ModuleDefinition module, Stream symbolStream) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) Mixin.CheckModule(module); Mixin.CheckStream((object)symbolStream); Mixin.CheckReadSeek(symbolStream); if (!Mixin.IsPortablePdb(symbolStream)) { return new NativePdbReaderProvider().GetSymbolReader(module, symbolStream); } return new PortablePdbReaderProvider().GetSymbolReader(module, symbolStream); } } public sealed class NativePdbWriterProvider : ISymbolWriterProvider { public ISymbolWriter GetSymbolWriter(ModuleDefinition module, string fileName) { Mixin.CheckModule(module); Mixin.CheckFileName(fileName); return (ISymbolWriter)(object)new NativePdbWriter(module, CreateWriter(module, Mixin.GetPdbFileName(fileName))); } private static SymWriter CreateWriter(ModuleDefinition module, string pdb) { SymWriter symWriter = new SymWriter(); if (File.Exists(pdb)) { File.Delete(pdb); } symWriter.Initialize(new ModuleMetadata(module), pdb, fFullBuild: true); return symWriter; } public ISymbolWriter GetSymbolWriter(ModuleDefinition module, Stream symbolStream) { throw new NotImplementedException(); } } public sealed class PdbWriterProvider : ISymbolWriterProvider { public ISymbolWriter GetSymbolWriter(ModuleDefinition module, string fileName) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) Mixin.CheckModule(module); Mixin.CheckFileName(fileName); if (HasPortablePdbSymbols(module)) { return new PortablePdbWriterProvider().GetSymbolWriter(module, fileName); } return new NativePdbWriterProvider().GetSymbolWriter(module, fileName); } private static bool HasPortablePdbSymbols(ModuleDefinition module) { if (module.symbol_reader != null) { return module.symbol_reader is PortablePdbReader; } return false; } public ISymbolWriter GetSymbolWriter(ModuleDefinition module, Stream symbolStream) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) Mixin.CheckModule(module); Mixin.CheckStream((object)symbolStream); Mixin.CheckReadSeek(symbolStream); if (HasPortablePdbSymbols(module)) { return new PortablePdbWriterProvider().GetSymbolWriter(module, symbolStream); } return new NativePdbWriterProvider().GetSymbolWriter(module, symbolStream); } } internal class SymDocumentWriter { private readonly ISymUnmanagedDocumentWriter m_unmanagedDocumentWriter; public SymDocumentWriter(ISymUnmanagedDocumentWriter unmanagedDocumentWriter) { m_unmanagedDocumentWriter = unmanagedDocumentWriter; } public ISymUnmanagedDocumentWriter GetUnmanaged() { return m_unmanagedDocumentWriter; } } internal class SymWriter { private static Guid s_symUnmangedWriterIID = new Guid("0b97726e-9e6d-4f05-9a26-424022093caa"); private static Guid s_CorSymWriter_SxS_ClassID = new Guid("108296c1-281e-11d3-bd22-0000f80849bd"); private readonly ISymUnmanagedWriter2 m_writer; private readonly Collection<ISymUnmanagedDocumentWriter> documents; [DllImport("ole32.dll")] private static extern int CoCreateInstance([In] ref Guid rclsid, [In][MarshalAs(UnmanagedType.IUnknown)] object pUnkOuter, [In] uint dwClsContext, [In] ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out object ppv); public SymWriter() { CoCreateInstance(ref s_CorSymWriter_SxS_ClassID, null, 1u, ref s_symUnmangedWriterIID, out var ppv); m_writer = (ISymUnmanagedWriter2)ppv; documents = new Collection<ISymUnmanagedDocumentWriter>(); } public byte[] GetDebugInfo(out ImageDebugDirectory idd) { m_writer.GetDebugInfo(out idd, 0, out var pcData, null); byte[] array = new byte[pcData]; m_writer.GetDebugInfo(out idd, pcData, out pcData, array); return array; } public void DefineLocalVariable2(string name, VariableAttributes attributes, int sigToken, int addr1, int addr2, int addr3, int startOffset, int endOffset) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Expected I4, but got Unknown m_writer.DefineLocalVariable2(name, (int)attributes, sigToken, 1, addr1, addr2, addr3, startOffset, endOffset); } public void DefineConstant2(string name, object value, int sigToken) { if (value == null) { m_writer.DefineConstant2(name, 0, sigToken); } else { m_writer.DefineConstant2(name, value, sigToken); } } public void Close() { //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) m_writer.Close(); Marshal.ReleaseComObject(m_writer); Enumerator<ISymUnmanagedDocumentWriter> enumerator = documents.GetEnumerator(); try { while (enumerator.MoveNext()) { Marshal.ReleaseComObject(enumerator.Current); } } finally { ((IDisposable)enumerator).Dispose(); } } public void CloseMethod() { m_writer.CloseMethod(); } public void CloseNamespace() { m_writer.CloseNamespace(); } public void CloseScope(int endOffset) { m_writer.CloseScope(endOffset); } public SymDocumentWriter DefineDocument(string url, Guid language, Guid languageVendor, Guid documentType) { m_writer.DefineDocument(url, ref language, ref languageVendor, ref documentType, out var pRetVal); documents.Add(pRetVal); return new SymDocumentWriter(pRetVal); } public void DefineSequencePoints(SymDocumentWriter document, int[] offsets, int[] lines, int[] columns, int[] endLines, int[] endColumns) { m_writer.DefineSequencePoints(document.GetUnmanaged(), offsets.Length, offsets, lines, columns, endLines, endColumns); } public void Initialize(object emitter, string filename, bool fFullBuild) { m_writer.Initialize(emitter, filename, null, fFullBuild); } public void SetUserEntryPoint(int methodToken) { m_writer.SetUserEntryPoint(methodToken); } public void OpenMethod(int methodToken) { m_writer.OpenMethod(methodToken); } public void OpenNamespace(string name) { m_writer.OpenNamespace(name); } public int OpenScope(int startOffset) { m_writer.OpenScope(startOffset, out var pRetVal); return pRetVal; } public void UsingNamespace(string fullName) { m_writer.UsingNamespace(fullName); } public void DefineCustomMetadata(string name, byte[] metadata) { GCHandle gCHandle = GCHandle.Alloc(metadata, GCHandleType.Pinned); m_writer.SetSymAttribute(0u, name, (uint)metadata.Length, gCHandle.AddrOfPinnedObject()); gCHandle.Free(); } } } namespace Microsoft.Cci { public interface ILocalScope { uint Offset { get; } uint Length { get; } } public interface INamespaceScope { IEnumerable<IUsedNamespace> UsedNamespaces { get; } } public interface IUsedNamespace { IName Alias { get; } IName NamespaceName { get; } } public interface IName { int UniqueKey { get; } int UniqueKeyIgnoringCase { get; } string Value { get; } } internal sealed class PdbIteratorScope : ILocalScope { private uint offset; private uint length; public uint Offset => offset; public uint Length => length; internal PdbIteratorScope(uint offset, uint length) { this.offset = offset; this.length = length; } } } namespace Microsoft.Cci.Pdb { internal class BitAccess { private byte[] buffer; private int offset; internal byte[] Buffer => buffer; internal int Position { get { return offset; } set { offset = value; } } internal BitAccess(int capacity) { buffer = new byte[capacity]; } internal void FillBuffer(Stream stream, int capacity) { MinCapacity(capacity); stream.Read(buffer, 0, capacity); offset = 0; } internal void Append(Stream stream, int count) { int num = offset + count; if (buffer.Length < num) { byte[] destinationArray = new byte[num]; Array.Copy(buffer, destinationArray, buffer.Length); buffer = destinationArray; } stream.Read(buffer, offset, count); offset += count; } internal void MinCapacity(int capacity) { if (buffer.Length < capacity) { buffer = new byte[capacity]; } offset = 0; } internal void Align(int alignment) { while (offset % alignment != 0) { offset++; } } internal void ReadInt16(out short value) { value = (short)((buffer[offset] & 0xFF) | (buffer[offset + 1] << 8)); offset += 2; } internal void ReadInt8(out sbyte value) { value = (sbyte)buffer[offset]; offset++; } internal void ReadInt32(out int value) { value = (buffer[offset] & 0xFF) | (buffer[offset + 1] << 8) | (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24); offset += 4; } internal void ReadInt64(out long value) { value = ((long)buffer[offset] & 0xFFL) | (long)((ulong)buffer[offset + 1] << 8) | (long)((ulong)buffer[offset + 2] << 16) | (long)((ulong)buffer[offset + 3] << 24) | (long)((ulong)buffer[offset + 4] << 32) | (long)((ulong)buffer[offset + 5] << 40) | (long)((ulong)buffer[offset + 6] << 48) | (long)((ulong)buffer[offset + 7] << 56); offset += 8; } internal void ReadUInt16(out ushort value) { value = (ushort)((buffer[offset] & 0xFFu) | (uint)(buffer[offset + 1] << 8)); offset += 2; } internal void ReadUInt8(out byte value) { value = (byte)(buffer[offset] & 0xFFu); offset++; } internal void ReadUInt32(out uint value) { value = (buffer[offset] & 0xFFu) | (uint)(buffer[offset + 1] << 8) | (uint)(buffer[offset + 2] << 16) | (uint)(buffer[offset + 3] << 24); offset += 4; } internal void ReadUInt64(out ulong value) { value = ((ulong)buffer[offset] & 0xFFuL) | ((ulong)buffer[offset + 1] << 8) | ((ulong)buffer[offset + 2] << 16) | ((ulong)buffer[offset + 3] << 24) | ((ulong)buffer[offset + 4] << 32) | ((ulong)buffer[offset + 5] << 40) | ((ulong)buffer[offset + 6] << 48) | ((ulong)buffer[offset + 7] << 56); offset += 8; } internal void ReadInt32(int[] values) { for (int i = 0; i < values.Length; i++) { ReadInt32(out values[i]); } } internal void ReadUInt32(uint[] values) { for (int i = 0; i < values.Length; i++) { ReadUInt32(out values[i]); } } internal void ReadBytes(byte[] bytes) { for (int i = 0; i < bytes.Length; i++) { bytes[i] = buffer[offset++]; } } internal float ReadFloat() { float result = BitConverter.ToSingle(buffer, offset); offset += 4; return result; } internal double ReadDouble() { double result = BitConverter.ToDouble(buffer, offset); offset += 8; return result; } internal decimal ReadDecimal() { int[] array = new int[4]; ReadInt32(array); return new decimal(array[2], array[3], array[1], array[0] < 0, (byte)((array[0] & 0xFF0000) >> 16)); } internal void ReadBString(out string value) { ReadUInt16(out var value2); value = Encoding.UTF8.GetString(buffer, offset, value2); offset += value2; } internal string ReadBString(int len) { string @string = Encoding.UTF8.GetString(buffer, offset, len); offset += len; return @string; } internal void ReadCString(out string value) { int i; for (i = 0; offset + i < buffer.Length && buffer[offset + i] != 0; i++) { } value = Encoding.UTF8.GetString(buffer, offset, i); offset += i + 1; } internal void SkipCString(out string value) { int i; for (i = 0; offset + i < buffer.Length && buffer[offset + i] != 0; i++) { } offset += i + 1; value = null; } internal void ReadGuid(out Guid guid) { ReadUInt32(out var value); ReadUInt16(out var value2); ReadUInt16(out var value3); ReadUInt8(out var value4); ReadUInt8(out var value5); ReadUInt8(out var value6); ReadUInt8(out var value7); ReadUInt8(out var value8); ReadUInt8(out var value9); ReadUInt8(out var value10); ReadUInt8(out var value11); guid = new Guid(value, value2, value3, value4, value5, value6, value7, value8, value9, value10, value11); } internal string ReadString() { int i; for (i = 0; offset + i < buffer.Length && buffer[offset + i] != 0; i += 2) { } string @string = Encoding.Unicode.GetString(buffer, offset, i); offset += i + 2; return @string; } } internal struct BitSet { private int size; private uint[] words; internal bool IsEmpty => size == 0; internal BitSet(BitAccess bits) { bits.ReadInt32(out size); words = new uint[size]; bits.ReadUInt32(words); } internal bool IsSet(int index) { int num = index / 32; if (num >= size) { return false; } return (words[num] & GetBit(index)) != 0; } private static uint GetBit(int index) { return (uint)(1 << index % 32); } } internal struct FLOAT10 { internal byte Data_0; internal byte Data_1; internal byte Data_2; internal byte Data_3; internal byte Data_4; internal byte Data_5; internal byte Data_6; internal byte Data_7; internal byte Data_8; internal byte Data_9; } internal enum CV_SIGNATURE { C6 = 0, C7 = 1, C11 = 2, C13 = 4, RESERVERD = 5 } internal enum CV_prmode { CV_TM_DIRECT = 0, CV_TM_NPTR32 = 4, CV_TM_NPTR64 = 6, CV_TM_NPTR128 = 7 } internal enum CV_type { CV_SPECIAL = 0, CV_SIGNED = 1, CV_UNSIGNED = 2, CV_BOOLEAN = 3, CV_REAL = 4, CV_COMPLEX = 5, CV_SPECIAL2 = 6, CV_INT = 7, CV_CVRESERVED = 15 } internal enum CV_special { CV_SP_NOTYPE, CV_SP_ABS, CV_SP_SEGMENT, CV_SP_VOID, CV_SP_CURRENCY, CV_SP_NBASICSTR, CV_SP_FBASICSTR, CV_SP_NOTTRANS, CV_SP_HRESULT } internal enum CV_special2 { CV_S2_BIT, CV_S2_PASCHAR } internal enum CV_integral { CV_IN_1BYTE, CV_IN_2BYTE, CV_IN_4BYTE, CV_IN_8BYTE, CV_IN_16BYTE } internal enum CV_real { CV_RC_REAL32, CV_RC_REAL64, CV_RC_REAL80, CV_RC_REAL128 } internal enum CV_int { CV_RI_CHAR = 0, CV_RI_INT1 = 0, CV_RI_WCHAR = 1, CV_RI_UINT1 = 1, CV_RI_INT2 = 2, CV_RI_UINT2 = 3, CV_RI_INT4 = 4, CV_RI_UINT4 = 5, CV_RI_INT8 = 6, CV_RI_UINT8 = 7, CV_RI_INT16 = 8, CV_RI_UINT16 = 9 } [StructLayout(LayoutKind.Sequential, Size = 1)] internal struct CV_PRIMITIVE_TYPE { private const uint CV_MMASK = 1792u; private const uint CV_TMASK = 240u; private const uint CV_SMASK = 15u; private const int CV_MSHIFT = 8; private const int CV_TSHIFT = 4; private const int CV_SSHIFT = 0; private const uint CV_FIRST_NONPRIM = 4096u; } internal enum TYPE_ENUM { T_NOTYPE = 0, T_ABS = 1, T_SEGMENT = 2, T_VOID = 3, T_HRESULT = 8, T_32PHRESULT = 1032, T_64PHRESULT = 1544, T_PVOID = 259, T_PFVOID = 515, T_PHVOID = 771, T_32PVOID = 1027, T_64PVOID = 1539, T_CURRENCY = 4, T_NOTTRANS = 7, T_BIT = 96, T_PASCHAR = 97, T_CHAR = 16, T_32PCHAR = 1040, T_64PCHAR = 1552, T_UCHAR = 32, T_32PUCHAR = 1056, T_64PUCHAR = 1568, T_RCHAR = 112, T_32PRCHAR = 1136, T_64PRCHAR = 1648, T_WCHAR = 113, T_32PWCHAR = 1137, T_64PWCHAR = 1649, T_INT1 = 104, T_32PINT1 = 1128, T_64PINT1 = 1640, T_UINT1 = 105, T_32PUINT1 = 1129, T_64PUINT1 = 1641, T_SHORT = 17, T_32PSHORT = 1041, T_64PSHORT = 1553, T_USHORT = 33, T_32PUSHORT = 1057, T_64PUSHORT = 1569, T_INT2 = 114, T_32PINT2 = 1138, T_64PINT2 = 1650, T_UINT2 = 115, T_32PUINT2 = 1139, T_64PUINT2 = 1651, T_LONG = 18, T_ULONG = 34, T_32PLONG = 1042, T_32PULONG = 1058, T_64PLONG = 1554, T_64PULONG = 1570, T_INT4 = 116, T_32PINT4 = 1140, T_64PINT4 = 1652, T_UINT4 = 117, T_32PUINT4 = 1141, T_64PUINT4 = 1653, T_QUAD = 19, T_32PQUAD = 1043, T_64PQUAD = 1555, T_UQUAD = 35, T_32PUQUAD = 1059, T_64PUQUAD = 1571, T_INT8 = 118, T_32PINT8 = 1142, T_64PINT8 = 1654, T_UINT8 = 119, T_32PUINT8 = 1143, T_64PUINT8 = 1655, T_OCT = 20, T_32POCT = 1044, T_64POCT = 1556, T_UOCT = 36, T_32PUOCT = 1060, T_64PUOCT = 1572, T_INT16 = 120, T_32PINT16 = 1144, T_64PINT16 = 1656, T_UINT16 = 121, T_32PUINT16 = 1145, T_64PUINT16 = 1657, T_REAL32 = 64, T_32PREAL32 = 1088, T_64PREAL32 = 1600, T_REAL64 = 65, T_32PREAL64 = 1089, T_64PREAL64 = 1601, T_REAL80 = 66, T_32PREAL80 = 1090, T_64PREAL80 = 1602, T_REAL128 = 67, T_32PREAL128 = 1091, T_64PREAL128 = 1603, T_CPLX32 = 80, T_32PCPLX32 = 1104, T_64PCPLX32 = 1616, T_CPLX64 = 81, T_32PCPLX64 = 1105, T_64PCPLX64 = 1617, T_CPLX80 = 82, T_32PCPLX80 = 1106, T_64PCPLX80 = 1618, T_CPLX128 = 83, T_32PCPLX128 = 1107, T_64PCPLX128 = 1619, T_BOOL08 = 48, T_32PBOOL08 = 1072, T_64PBOOL08 = 1584, T_BOOL16 = 49, T_32PBOOL16 = 1073, T_64PBOOL16 = 1585, T_BOOL32 = 50, T_32PBOOL32 = 1074, T_64PBOOL32 = 1586, T_BOOL64 = 51, T_32PBOOL64 = 1075, T_64PBOOL64 = 1587 } internal enum LEAF { LF_VTSHAPE = 10, LF_COBOL1 = 12, LF_LABEL = 14, LF_NULL = 15, LF_NOTTRAN = 16, LF_ENDPRECOMP = 20, LF_TYPESERVER_ST = 22, LF_LIST = 515, LF_REFSYM = 524, LF_ENUMERATE_ST = 1027, LF_TI16_MAX = 4096, LF_MODIFIER = 4097, LF_POINTER = 4098, LF_ARRAY_ST = 4099, LF_CLASS_ST = 4100, LF_STRUCTURE_ST = 4101, LF_UNION_ST = 4102, LF_ENUM_ST = 4103, LF_PROCEDURE = 4104, LF_MFUNCTION = 4105, LF_COBOL0 = 4106, LF_BARRAY = 4107, LF_DIMARRAY_ST = 4108, LF_VFTPATH = 4109, LF_PRECOMP_ST = 4110, LF_OEM = 4111, LF_ALIAS_ST = 4112, LF_OEM2 = 4113, LF_SKIP = 4608, LF_ARGLIST = 4609, LF_DEFARG_ST = 4610, LF_FIELDLIST = 4611, LF_DERIVED = 4612, LF_BITFIELD = 4613, LF_METHODLIST = 4614, LF_DIMCONU = 4615, LF_DIMCONLU = 4616, LF_DIMVARU = 4617, LF_DIMVARLU = 4618, LF_BCLASS = 5120, LF_VBCLASS = 5121, LF_IVBCLASS = 5122, LF_FRIENDFCN_ST = 5123, LF_INDEX = 5124, LF_MEMBER_ST = 5125, LF_STMEMBER_ST = 5126, LF_METHOD_ST = 5127, LF_NESTTYPE_ST = 5128, LF_VFUNCTAB = 5129, LF_FRIENDCLS = 5130, LF_ONEMETHOD_ST = 5131, LF_VFUNCOFF = 5132, LF_NESTTYPEEX_ST = 5133, LF_MEMBERMODIFY_ST = 5134, LF_MANAGED_ST = 5135, LF_ST_MAX = 5376, LF_TYPESERVER = 5377, LF_ENUMERATE = 5378, LF_ARRAY = 5379, LF_CLASS = 5380, LF_STRUCTURE = 5381, LF_UNION = 5382, LF_ENUM = 5383, LF_DIMARRAY = 5384, LF_PRECOMP = 5385, LF_ALIAS = 5386, LF_DEFARG = 5387, LF_FRIENDFCN = 5388, LF_MEMBER = 5389, LF_STMEMBER = 5390, LF_METHOD = 5391, LF_NESTTYPE = 5392, LF_ONEMETHOD = 5393, LF_NESTTYPEEX = 5394, LF_MEMBERMODIFY = 5395, LF_MANAGED = 5396, LF_TYPESERVER2 = 5397, LF_NUMERIC = 32768, LF_CHAR = 32768, LF_SHORT = 32769, LF_USHORT = 32770, LF_LONG = 32771, LF_ULONG = 32772, LF_REAL32 = 32773, LF_REAL64 = 32774, LF_REAL80 = 32775, LF_REAL128 = 32776, LF_QUADWORD = 32777, LF_UQUADWORD = 32778, LF_COMPLEX32 = 32780, LF_COMPLEX64 = 32781, LF_COMPLEX80 = 32782, LF_COMPLEX128 = 32783, LF_VARSTRING = 32784, LF_OCTWORD = 32791, LF_UOCTWORD = 32792, LF_DECIMAL = 32793, LF_DATE = 32794, LF_UTF8STRING = 32795, LF_PAD0 = 240, LF_PAD1 = 241, LF_PAD2 = 242, LF_PAD3 = 243, LF_PAD4 = 244, LF_PAD5 = 245, LF_PAD6 = 246, LF_PAD7 = 247, LF_PAD8 = 248, LF_PAD9 = 249, LF_PAD10 = 250, LF_PAD11 = 251, LF_PAD12 = 252, LF_PAD13 = 253, LF_PAD14 = 254, LF_PAD15 = 255 } internal enum CV_ptrtype { CV_PTR_BASE_SEG = 3, CV_PTR_BASE_VAL = 4, CV_PTR_BASE_SEGVAL = 5, CV_PTR_BASE_ADDR = 6, CV_PTR_BASE_SEGADDR = 7, CV_PTR_BASE_TYPE = 8, CV_PTR_BASE_SELF = 9, CV_PTR_NEAR32 = 10, CV_PTR_64 = 12, CV_PTR_UNUSEDPTR = 13 } internal enum CV_ptrmode { CV_PTR_MODE_PTR, CV_PTR_MODE_REF, CV_PTR_MODE_PMEM, CV_PTR_MODE_PMFUNC, CV_PTR_MODE_RESERVED } internal enum CV_pmtype { CV_PMTYPE_Undef, CV_PMTYPE_D_Single, CV_PMTYPE_D_Multiple, CV_PMTYPE_D_Virtual, CV_PMTYPE_D_General, CV_PMTYPE_F_Single, CV_PMTYPE_F_Multiple, CV_PMTYPE_F_Virtual, CV_PMTYPE_F_General } internal enum CV_methodprop { CV_MTvanilla, CV_MTvirtual, CV_MTstatic, CV_MTfriend, CV_MTintro, CV_MTpurevirt, CV_MTpureintro } internal enum CV_VTS_desc { CV_VTS_near, CV_VTS_far, CV_VTS_thin, CV_VTS_outer, CV_VTS_meta, CV_VTS_near32, CV_VTS_far32, CV_VTS_unused } internal enum CV_LABEL_TYPE { CV_LABEL_NEAR = 0, CV_LABEL_FAR = 4 } [Flags] internal enum CV_modifier : ushort { MOD_const = 1, MOD_volatile = 2, MOD_unaligned = 4 } [Flags] internal enum CV_prop : ushort { packed = 1, ctor = 2, ovlops = 4, isnested = 8, cnested = 0x10, opassign = 0x20, opcast = 0x40, fwdref = 0x80, scoped = 0x100 } [Flags] internal enum CV_fldattr { access = 3, mprop = 0x1C, pseudo = 0x20, noinherit = 0x40, noconstruct = 0x80, compgenx = 0x100 } internal struct TYPTYPE { internal ushort len; internal ushort leaf; } internal struct CV_PDMR32_NVVFCN { internal int mdisp; } internal struct CV_PDMR32_VBASE { internal int mdisp; internal int pdisp; internal int vdisp; } internal struct CV_PMFR32_NVSA { internal uint off; } internal struct CV_PMFR32_NVMA { internal uint off; internal int disp; } internal struct CV_PMFR32_VBASE { internal uint off; internal int mdisp; internal int pdisp; internal int vdisp; } internal struct LeafModifier { internal uint type; internal CV_modifier attr; } [Flags] internal enum LeafPointerAttr : uint { ptrtype = 0x1Fu, ptrmode = 0xE0u, isflat32 = 0x100u, isvolatile = 0x200u, isconst = 0x400u, isunaligned = 0x800u, isrestrict = 0x1000u } [StructLayout(LayoutKind.Sequential, Size = 1)] internal struct LeafPointer { internal struct LeafPointerBody { internal uint utype; internal LeafPointerAttr attr; } } internal struct LeafArray { internal uint elemtype; internal uint idxtype; internal byte[] data; internal string name; } internal struct LeafClass { internal ushort count; internal ushort property; internal uint field; internal uint derived; internal uint vshape; internal byte[] data; internal string name; } internal struct LeafUnion { internal ushort count; internal ushort property; internal uint field; internal byte[] data; internal string name; } internal struct LeafAlias { internal uint utype; internal string name; } internal struct LeafManaged { internal string name; } internal struct LeafEnum { internal ushort count; internal ushort property; internal uint utype; internal uint field; internal string name; } internal struct LeafProc { internal uint rvtype; internal byte calltype; internal byte reserved; internal ushort parmcount; internal uint arglist; } internal struct LeafMFunc { internal uint rvtype; internal uint classtype; internal uint thistype; internal byte calltype; internal byte reserved; internal ushort parmcount; internal uint arglist; internal int thisadjust; } internal struct LeafVTShape { internal ushort count; internal byte[] desc; } internal struct LeafCobol0 { internal uint type; internal byte[] data; } internal struct LeafCobol1 { internal byte[] data; } internal struct LeafBArray { internal uint utype; } internal struct LeafLabel { internal ushort mode; } internal struct LeafDimArray { internal uint utype; internal uint diminfo; internal string name; } internal struct LeafVFTPath { internal uint count; internal uint[] bases; } internal struct LeafPreComp { internal uint start; internal uint count; internal uint signature; internal string name; } internal struct LeafEndPreComp { internal uint signature; } internal struct LeafOEM { internal ushort cvOEM; internal ushort recOEM; internal uint count; internal uint[] index; } internal enum OEM_ID { OEM_MS_FORTRAN90 = 61584, OEM_ODI = 16, OEM_THOMSON_SOFTWARE = 21587, OEM_ODI_REC_BASELIST = 0 } internal struct LeafOEM2 { internal Guid idOem; internal uint count; internal uint[] index; } internal struct LeafTypeServer { internal uint signature; internal uint age; internal string name; } internal struct LeafTypeServer2 { internal Guid sig70; internal uint age; internal string name; } internal struct LeafSkip { internal uint type; internal byte[] data; } internal struct LeafArgList { internal uint count; internal uint[] arg; } internal struct LeafDerived { internal uint count; internal uint[] drvdcls; } internal struct LeafDefArg { internal uint type; internal byte[] expr; } internal struct LeafList { internal byte[] data; } internal struct LeafFieldList { internal char[] data; } internal struct mlMethod { internal ushort attr; internal ushort pad0; internal uint index; internal uint[] vbaseoff; } internal struct LeafMethodList { internal byte[] mList; } internal struct LeafBitfield { internal uint type; internal byte length; internal byte position; } internal struct LeafDimCon { internal uint typ; internal ushort rank; internal byte[] dim; } internal struct LeafDimVar { internal uint rank; internal uint typ; internal uint[] dim; } internal struct LeafRefSym { internal byte[] Sym; } internal struct LeafChar { internal sbyte val; } internal struct LeafShort { internal short val; } internal struct LeafUShort { internal ushort val; } internal struct LeafLong { internal int val; } internal struct LeafULong { internal uint val; } internal struct LeafQuad { internal long val; } internal struct LeafUQuad { internal ulong val; } internal struct LeafOct { internal ulong val0; internal ulong val1; } internal struct LeafUOct { internal ulong val0; internal ulong val1; } internal struct LeafReal32 { internal float val; } internal struct LeafReal64 { internal double val; } internal struct LeafReal80 { internal FLOAT10 val; } internal struct LeafReal128 { internal ulong val0; internal ulong val1; } internal struct LeafCmplx32 { internal float val_real; internal float val_imag; } internal struct LeafCmplx64 { internal double val_real; internal double val_imag; } internal struct LeafCmplx80 { internal FLOAT10 val_real; internal FLOAT10 val_imag; } internal struct LeafCmplx128 { internal ulong val0_real; internal ulong val1_real; internal ulong val0_imag; internal ulong val1_imag; } internal struct LeafVarString { internal ushort len; internal byte[] value; } internal struct LeafIndex { internal ushort pad0; internal uint index; } internal struct LeafBClass { internal ushort attr; internal uint index; internal byte[] offset; } internal struct LeafVBClass { internal ushort attr; internal uint index; internal uint vbptr; internal byte[] vbpoff; } internal struct LeafFriendCls { internal ushort pad0; internal uint index; } internal struct LeafFriendFcn { internal ushort pad0; internal uint index; internal string name; } internal struct LeafMember { internal ushort attr; internal uint index; internal byte[] offset; internal string name; } internal struct LeafSTMember { internal ushort attr; internal uint index; internal string name; } internal struct LeafVFuncTab { internal ushort pad0; internal uint type; } internal struct LeafVFuncOff { internal ushort pad0; internal uint type; internal int offset; } internal struct LeafMethod { internal ushort count; internal uint mList; internal string name; } internal struct LeafOneMethod { internal ushort attr; internal uint index; internal uint[] vbaseoff; internal string name; } internal struct LeafEnumerate { internal ushort attr; internal byte[] value; internal string name; } internal struct LeafNestType { internal ushort pad0; internal uint index; internal string name; } internal struct LeafNestTypeEx { internal ushort attr; internal uint index; internal string name; } internal struct LeafMemberModify { internal ushort
BepInExPack\BepInEx\core\Mono.Cecil.Rocks.dll
Decompiled 2 months agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Text; using Mono.Cecil.Cil; using Mono.Cecil.PE; using Mono.Collections.Generic; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyProduct("Mono.Cecil")] [assembly: AssemblyCopyright("Copyright © 2008 - 2018 Jb Evain")] [assembly: ComVisible(false)] [assembly: AssemblyFileVersion("0.10.4.0")] [assembly: AssemblyInformationalVersion("0.10.4.0")] [assembly: AssemblyTitle("Mono.Cecil.Rocks")] [assembly: CLSCompliant(false)] [assembly: AssemblyVersion("0.10.4.0")] namespace Mono.Cecil.Rocks; public class DocCommentId { private StringBuilder id; private DocCommentId() { id = new StringBuilder(); } private void WriteField(FieldDefinition field) { WriteDefinition('F', (IMemberDefinition)(object)field); } private void WriteEvent(EventDefinition @event) { WriteDefinition('E', (IMemberDefinition)(object)@event); } private void WriteType(TypeDefinition type) { id.Append('T').Append(':'); WriteTypeFullName((TypeReference)(object)type); } private void WriteMethod(MethodDefinition method) { WriteDefinition('M', (IMemberDefinition)(object)method); if (((MethodReference)method).HasGenericParameters) { id.Append('`').Append('`'); id.Append(((MethodReference)method).GenericParameters.Count); } if (((MethodReference)method).HasParameters) { WriteParameters((IList<ParameterDefinition>)((MethodReference)method).Parameters); } if (IsConversionOperator(method)) { WriteReturnType(method); } } private static bool IsConversionOperator(MethodDefinition self) { if (self == null) { throw new ArgumentNullException("self"); } if (self.IsSpecialName) { if (!(((MemberReference)self).Name == "op_Explicit")) { return ((MemberReference)self).Name == "op_Implicit"; } return true; } return false; } private void WriteReturnType(MethodDefinition method) { id.Append('~'); WriteTypeSignature(((MethodReference)method).ReturnType); } private void WriteProperty(PropertyDefinition property) { WriteDefinition('P', (IMemberDefinition)(object)property); if (property.HasParameters) { WriteParameters((IList<ParameterDefinition>)((PropertyReference)property).Parameters); } } private void WriteParameters(IList<ParameterDefinition> parameters) { id.Append('('); WriteList(parameters, delegate(ParameterDefinition p) { WriteTypeSignature(((ParameterReference)p).ParameterType); }); id.Append(')'); } private void WriteTypeSignature(TypeReference type) { //IL_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_0007: 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_002c: Expected I4, but got Unknown //IL_010c: 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_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Expected O, but got Unknown //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Expected O, but got Unknown //IL_002c: 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_004d: Expected I4, but got Unknown //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Expected O, but got Unknown //IL_00db: 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_0109: Expected O, but got Unknown //IL_00ee: Unknown result type (might be due to invalid IL or missing references) //IL_00fa: Expected O, but got Unknown MetadataType metadataType = type.MetadataType; switch (metadataType - 15) { default: switch (metadataType - 27) { case 0: WriteFunctionPointerTypeSignature((FunctionPointerType)type); return; case 3: id.Append('`').Append('`'); id.Append(((GenericParameter)type).Position); return; case 5: WriteModiferTypeSignature((IModifierType)(OptionalModifierType)type, '!'); return; case 4: WriteModiferTypeSignature((IModifierType)(RequiredModifierType)type, '|'); return; } break; case 5: WriteArrayTypeSignature((ArrayType)type); return; case 1: WriteTypeSignature(((TypeSpecification)(ByReferenceType)type).ElementType); id.Append('@'); return; case 6: WriteGenericInstanceTypeSignature((GenericInstanceType)type); return; case 4: id.Append('`'); id.Append(((GenericParameter)type).Position); return; case 0: WriteTypeSignature(((TypeSpecification)(PointerType)type).ElementType); id.Append('*'); return; case 2: case 3: break; } WriteTypeFullName(type); } private void WriteGenericInstanceTypeSignature(GenericInstanceType type) { if (Mixin.IsTypeSpecification(((TypeSpecification)type).ElementType)) { throw new NotSupportedException(); } WriteTypeFullName(((TypeSpecification)type).ElementType, stripGenericArity: true); id.Append('{'); WriteList((IList<TypeReference>)type.GenericArguments, WriteTypeSignature); id.Append('}'); } private void WriteList<T>(IList<T> list, Action<T> action) { for (int i = 0; i < list.Count; i++) { if (i > 0) { id.Append(','); } action(list[i]); } } private void WriteModiferTypeSignature(IModifierType type, char id) { WriteTypeSignature(type.ElementType); this.id.Append(id); WriteTypeSignature(type.ModifierType); } private void WriteFunctionPointerTypeSignature(FunctionPointerType type) { id.Append("=FUNC:"); WriteTypeSignature(type.ReturnType); if (type.HasParameters) { WriteParameters((IList<ParameterDefinition>)type.Parameters); } } private void WriteArrayTypeSignature(ArrayType type) { WriteTypeSignature(((TypeSpecification)type).ElementType); if (type.IsVector) { id.Append("[]"); return; } id.Append("["); WriteList((IList<ArrayDimension>)type.Dimensions, delegate(ArrayDimension dimension) { if (((ArrayDimension)(ref dimension)).LowerBound.HasValue) { id.Append(((ArrayDimension)(ref dimension)).LowerBound.Value); } id.Append(':'); if (((ArrayDimension)(ref dimension)).UpperBound.HasValue) { id.Append(((ArrayDimension)(ref dimension)).UpperBound.Value - (((ArrayDimension)(ref dimension)).LowerBound.GetValueOrDefault() + 1)); } }); id.Append("]"); } private void WriteDefinition(char id, IMemberDefinition member) { this.id.Append(id).Append(':'); WriteTypeFullName((TypeReference)(object)member.DeclaringType); this.id.Append('.'); WriteItemName(member.Name); } private void WriteTypeFullName(TypeReference type, bool stripGenericArity = false) { if (((MemberReference)type).DeclaringType != null) { WriteTypeFullName(((MemberReference)type).DeclaringType); id.Append('.'); } if (!string.IsNullOrEmpty(type.Namespace)) { id.Append(type.Namespace); id.Append('.'); } string text = ((MemberReference)type).Name; if (stripGenericArity) { int num = text.LastIndexOf('`'); if (num > 0) { text = text.Substring(0, num); } } id.Append(text); } private void WriteItemName(string name) { id.Append(name.Replace('.', '#').Replace('<', '{').Replace('>', '}')); } public override string ToString() { return id.ToString(); } public static string GetDocCommentId(IMemberDefinition member) { //IL_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_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_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Invalid comparison between Unknown and I4 //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Invalid comparison between Unknown and I4 //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Invalid comparison between Unknown and I4 //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Expected O, but got Unknown //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Invalid comparison between Unknown and I4 //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Expected O, but got Unknown //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Invalid comparison between Unknown and I4 //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Expected O, but got Unknown //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Invalid comparison between Unknown and I4 //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Expected O, but got Unknown //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Expected O, but got Unknown if (member == null) { throw new ArgumentNullException("member"); } DocCommentId docCommentId = new DocCommentId(); MetadataToken metadataToken = ((IMetadataTokenProvider)member).MetadataToken; TokenType tokenType = ((MetadataToken)(ref metadataToken)).TokenType; if ((int)tokenType <= 67108864) { if ((int)tokenType != 33554432) { if ((int)tokenType != 67108864) { goto IL_009d; } docCommentId.WriteField((FieldDefinition)member); } else { docCommentId.WriteType((TypeDefinition)member); } } else if ((int)tokenType != 100663296) { if ((int)tokenType != 335544320) { if ((int)tokenType != 385875968) { goto IL_009d; } docCommentId.WriteProperty((PropertyDefinition)member); } else { docCommentId.WriteEvent((EventDefinition)member); } } else { docCommentId.WriteMethod((MethodDefinition)member); } return docCommentId.ToString(); IL_009d: throw new NotSupportedException(member.FullName); } } internal static class Functional { public static Func<A, R> Y<A, R>(Func<Func<A, R>, Func<A, R>> f) { Func<A, R> g = null; g = f((A a) => g(a)); return g; } public static IEnumerable<TSource> Prepend<TSource>(this IEnumerable<TSource> source, TSource element) { if (source == null) { throw new ArgumentNullException("source"); } return PrependIterator(source, element); } private static IEnumerable<TSource> PrependIterator<TSource>(IEnumerable<TSource> source, TSource element) { yield return element; foreach (TSource item in source) { yield return item; } } } public interface IILVisitor { void OnInlineNone(OpCode opcode); void OnInlineSByte(OpCode opcode, sbyte value); void OnInlineByte(OpCode opcode, byte value); void OnInlineInt32(OpCode opcode, int value); void OnInlineInt64(OpCode opcode, long value); void OnInlineSingle(OpCode opcode, float value); void OnInlineDouble(OpCode opcode, double value); void OnInlineString(OpCode opcode, string value); void OnInlineBranch(OpCode opcode, int offset); void OnInlineSwitch(OpCode opcode, int[] offsets); void OnInlineVariable(OpCode opcode, VariableDefinition variable); void OnInlineArgument(OpCode opcode, ParameterDefinition parameter); void OnInlineSignature(OpCode opcode, CallSite callSite); void OnInlineType(OpCode opcode, TypeReference type); void OnInlineField(OpCode opcode, FieldReference field); void OnInlineMethod(OpCode opcode, MethodReference method); } public static class ILParser { private class ParseContext { public CodeReader Code { get; set; } public int Position { get; set; } public MetadataReader Metadata { get; set; } public Collection<VariableDefinition> Variables { get; set; } public IILVisitor Visitor { get; set; } } public static void Parse(MethodDefinition method, IILVisitor visitor) { if (method == null) { throw new ArgumentNullException("method"); } if (visitor == null) { throw new ArgumentNullException("visitor"); } if (!method.HasBody || !((MemberReference)method).HasImage) { throw new ArgumentException(); } ((MemberReference)method).Module.Read<MethodDefinition, bool>(method, (Func<MethodDefinition, MetadataReader, bool>)delegate(MethodDefinition m, MetadataReader _) { ParseMethod(m, visitor); return true; }); } private static void ParseMethod(MethodDefinition method, IILVisitor visitor) { ParseContext parseContext = CreateContext(method, visitor); CodeReader code = parseContext.Code; byte b = ((BinaryReader)(object)code).ReadByte(); switch (b & 3) { case 2: ParseCode(b >> 2, parseContext); break; case 3: ((BinaryStreamReader)code).Advance(-1); ParseFatMethod(parseContext); break; default: throw new NotSupportedException(); } code.MoveBackTo(parseContext.Position); } private static ParseContext CreateContext(MethodDefinition method, IILVisitor visitor) { CodeReader val = ((MemberReference)method).Module.Read<MethodDefinition, CodeReader>(method, (Func<MethodDefinition, MetadataReader, CodeReader>)((MethodDefinition _, MetadataReader reader) => reader.code)); int position = val.MoveTo(method); return new ParseContext { Code = val, Position = position, Metadata = val.reader, Visitor = visitor }; } private static void ParseFatMethod(ParseContext context) { //IL_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_001b: 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_002a: Unknown result type (might be due to invalid IL or missing references) CodeReader code = context.Code; ((BinaryStreamReader)code).Advance(4); int code_size = ((BinaryReader)(object)code).ReadInt32(); MetadataToken val = code.ReadToken(); if (val != MetadataToken.Zero) { context.Variables = (Collection<VariableDefinition>)(object)code.ReadVariables(val); } ParseCode(code_size, context); } private static void ParseCode(int code_size, ParseContext context) { //IL_004d: 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_0052: 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_005d: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Expected I4, but got Unknown //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_0240: Unknown result type (might be due to invalid IL or missing references) //IL_024e: Unknown result type (might be due to invalid IL or missing references) //IL_0253: Unknown result type (might be due to invalid IL or missing references) //IL_0257: 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_025e: Unknown result type (might be due to invalid IL or missing references) //IL_0265: Invalid comparison between Unknown and I4 //IL_015d: Unknown result type (might be due to invalid IL or missing references) //IL_0170: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_0196: Unknown result type (might be due to invalid IL or missing references) //IL_01a9: 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_01c2: Unknown result type (might be due to invalid IL or missing references) //IL_01c6: Unknown result type (might be due to invalid IL or missing references) //IL_0226: 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_0103: 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_012a: Unknown result type (might be due to invalid IL or missing references) //IL_0183: Unknown result type (might be due to invalid IL or missing references) //IL_020d: Unknown result type (might be due to invalid IL or missing references) //IL_01db: Unknown result type (might be due to invalid IL or missing references) //IL_0287: Unknown result type (might be due to invalid IL or missing references) //IL_028e: Invalid comparison between Unknown and I4 //IL_0267: Unknown result type (might be due to invalid IL or missing references) //IL_026e: Invalid comparison between Unknown and I4 //IL_014a: 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_02a4: Unknown result type (might be due to invalid IL or missing references) //IL_02ab: Invalid comparison between Unknown and I4 //IL_0290: Unknown result type (might be due to invalid IL or missing references) //IL_0297: Invalid comparison between Unknown and I4 //IL_02b9: Unknown result type (might be due to invalid IL or missing references) //IL_02bd: Unknown result type (might be due to invalid IL or missing references) //IL_02c7: Expected O, but got Unknown //IL_0270: Unknown result type (might be due to invalid IL or missing references) //IL_0277: Invalid comparison between Unknown and I4 //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_02ad: Unknown result type (might be due to invalid IL or missing references) //IL_02b4: Invalid comparison between Unknown and I4 //IL_02ca: Unknown result type (might be due to invalid IL or missing references) //IL_02ce: Unknown result type (might be due to invalid IL or missing references) //IL_02d8: Expected O, but got Unknown //IL_0299: Unknown result type (might be due to invalid IL or missing references) //IL_02a0: Invalid comparison between Unknown and I4 //IL_0279: Unknown result type (might be due to invalid IL or missing references) //IL_0280: Invalid comparison between Unknown and I4 //IL_02db: 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_02e9: Expected O, but got Unknown //IL_02f9: Unknown result type (might be due to invalid IL or missing references) //IL_0312: Unknown result type (might be due to invalid IL or missing references) CodeReader code = context.Code; MetadataReader metadata = context.Metadata; IILVisitor visitor = context.Visitor; int num = ((BinaryStreamReader)code).Position + code_size; while (((BinaryStreamReader)code).Position < num) { byte b = ((BinaryReader)(object)code).ReadByte(); OpCode val = ((b != 254) ? OpCodes.OneByteOpCode[b] : OpCodes.TwoBytesOpCode[((BinaryReader)(object)code).ReadByte()]); OperandType operandType = ((OpCode)(ref val)).OperandType; IMetadataTokenProvider val2; switch ((int)operandType) { case 5: visitor.OnInlineNone(val); break; case 10: { int num2 = ((BinaryReader)(object)code).ReadInt32(); int[] array = new int[num2]; for (int i = 0; i < num2; i++) { array[i] = ((BinaryReader)(object)code).ReadInt32(); } visitor.OnInlineSwitch(val, array); break; } case 15: visitor.OnInlineBranch(val, ((BinaryReader)(object)code).ReadSByte()); break; case 0: visitor.OnInlineBranch(val, ((BinaryReader)(object)code).ReadInt32()); break; case 16: if (val == OpCodes.Ldc_I4_S) { visitor.OnInlineSByte(val, ((BinaryReader)(object)code).ReadSByte()); } else { visitor.OnInlineByte(val, ((BinaryReader)(object)code).ReadByte()); } break; case 2: visitor.OnInlineInt32(val, ((BinaryReader)(object)code).ReadInt32()); break; case 3: visitor.OnInlineInt64(val, ((BinaryReader)(object)code).ReadInt64()); break; case 17: visitor.OnInlineSingle(val, ((BinaryReader)(object)code).ReadSingle()); break; case 7: visitor.OnInlineDouble(val, ((BinaryReader)(object)code).ReadDouble()); break; case 8: visitor.OnInlineSignature(val, code.GetCallSite(code.ReadToken())); break; case 9: visitor.OnInlineString(val, code.GetString(code.ReadToken())); break; case 19: visitor.OnInlineArgument(val, code.GetParameter((int)((BinaryReader)(object)code).ReadByte())); break; case 14: visitor.OnInlineArgument(val, code.GetParameter((int)((BinaryReader)(object)code).ReadInt16())); break; case 18: visitor.OnInlineVariable(val, GetVariable(context, ((BinaryReader)(object)code).ReadByte())); break; case 13: visitor.OnInlineVariable(val, GetVariable(context, ((BinaryReader)(object)code).ReadInt16())); break; case 1: case 4: case 11: case 12: { val2 = metadata.LookupToken(code.ReadToken()); MetadataToken metadataToken = val2.MetadataToken; TokenType tokenType = ((MetadataToken)(ref metadataToken)).TokenType; if ((int)tokenType <= 67108864) { if ((int)tokenType != 16777216 && (int)tokenType != 33554432) { if ((int)tokenType == 67108864) { visitor.OnInlineField(val, (FieldReference)val2); } break; } goto IL_02b8; } if ((int)tokenType <= 167772160) { if ((int)tokenType != 100663296) { if ((int)tokenType != 167772160) { break; } FieldReference val3 = (FieldReference)(object)((val2 is FieldReference) ? val2 : null); if (val3 != null) { visitor.OnInlineField(val, val3); break; } MethodReference val4 = (MethodReference)(object)((val2 is MethodReference) ? val2 : null); if (val4 != null) { visitor.OnInlineMethod(val, val4); break; } throw new InvalidOperationException(); } } else { if ((int)tokenType == 452984832) { goto IL_02b8; } if ((int)tokenType != 721420288) { break; } } visitor.OnInlineMethod(val, (MethodReference)val2); break; } IL_02b8: visitor.OnInlineType(val, (TypeReference)val2); break; } } } private static VariableDefinition GetVariable(ParseContext context, int index) { return context.Variables[index]; } } public static class MethodBodyRocks { public static void SimplifyMacros(this MethodBody self) { //IL_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_0028: 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_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Invalid comparison between Unknown and I4 //IL_003c: 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_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_004a: 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_0126: Expected I4, but got Unknown //IL_0137: Unknown result type (might be due to invalid IL or missing references) //IL_014e: Unknown result type (might be due to invalid IL or missing references) //IL_0165: Unknown result type (might be due to invalid IL or missing references) //IL_017c: Unknown result type (might be due to invalid IL or missing references) //IL_0193: Unknown result type (might be due to invalid IL or missing references) //IL_01af: Unknown result type (might be due to invalid IL or missing references) //IL_01cb: Unknown result type (might be due to invalid IL or missing references) //IL_01e7: Unknown result type (might be due to invalid IL or missing references) //IL_0203: Unknown result type (might be due to invalid IL or missing references) //IL_021f: Unknown result type (might be due to invalid IL or missing references) //IL_023b: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Unknown result type (might be due to invalid IL or missing references) //IL_0273: Unknown result type (might be due to invalid IL or missing references) //IL_0283: Unknown result type (might be due to invalid IL or missing references) //IL_0293: Unknown result type (might be due to invalid IL or missing references) //IL_02a3: Unknown result type (might be due to invalid IL or missing references) //IL_02b3: Unknown result type (might be due to invalid IL or missing references) //IL_02c3: Unknown result type (might be due to invalid IL or missing references) //IL_02d3: Unknown result type (might be due to invalid IL or missing references) //IL_02e9: Unknown result type (might be due to invalid IL or missing references) //IL_02ff: Unknown result type (might be due to invalid IL or missing references) //IL_0315: 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_0341: Unknown result type (might be due to invalid IL or missing references) //IL_0357: 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_0383: Unknown result type (might be due to invalid IL or missing references) //IL_0399: Unknown result type (might be due to invalid IL or missing references) //IL_03af: Unknown result type (might be due to invalid IL or missing references) //IL_03cf: Unknown result type (might be due to invalid IL or missing references) //IL_03df: Unknown result type (might be due to invalid IL or missing references) //IL_03ef: Unknown result type (might be due to invalid IL or missing references) //IL_03ff: Unknown result type (might be due to invalid IL or missing references) //IL_040f: Unknown result type (might be due to invalid IL or missing references) //IL_041c: Unknown result type (might be due to invalid IL or missing references) //IL_0429: Unknown result type (might be due to invalid IL or missing references) //IL_0436: Unknown result type (might be due to invalid IL or missing references) //IL_0443: Unknown result type (might be due to invalid IL or missing references) //IL_0450: Unknown result type (might be due to invalid IL or missing references) //IL_045d: Unknown result type (might be due to invalid IL or missing references) //IL_046a: Unknown result type (might be due to invalid IL or missing references) //IL_0477: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_012c: Invalid comparison between Unknown and I4 //IL_0484: Unknown result type (might be due to invalid IL or missing references) if (self == null) { throw new ArgumentNullException("self"); } Enumerator<Instruction> enumerator = self.Instructions.GetEnumerator(); try { while (enumerator.MoveNext()) { Instruction current = enumerator.Current; OpCode opCode = current.OpCode; if ((int)((OpCode)(ref opCode)).OpCodeType != 1) { continue; } opCode = current.OpCode; Code code = ((OpCode)(ref opCode)).Code; switch (code - 2) { case 0: ExpandMacro(current, OpCodes.Ldarg, Mixin.GetParameter(self, 0)); continue; case 1: ExpandMacro(current, OpCodes.Ldarg, Mixin.GetParameter(self, 1)); continue; case 2: ExpandMacro(current, OpCodes.Ldarg, Mixin.GetParameter(self, 2)); continue; case 3: ExpandMacro(current, OpCodes.Ldarg, Mixin.GetParameter(self, 3)); continue; case 4: ExpandMacro(current, OpCodes.Ldloc, self.Variables[0]); continue; case 5: ExpandMacro(current, OpCodes.Ldloc, self.Variables[1]); continue; case 6: ExpandMacro(current, OpCodes.Ldloc, self.Variables[2]); continue; case 7: ExpandMacro(current, OpCodes.Ldloc, self.Variables[3]); continue; case 8: ExpandMacro(current, OpCodes.Stloc, self.Variables[0]); continue; case 9: ExpandMacro(current, OpCodes.Stloc, self.Variables[1]); continue; case 10: ExpandMacro(current, OpCodes.Stloc, self.Variables[2]); continue; case 11: ExpandMacro(current, OpCodes.Stloc, self.Variables[3]); continue; case 12: current.OpCode = OpCodes.Ldarg; continue; case 13: current.OpCode = OpCodes.Ldarga; continue; case 14: current.OpCode = OpCodes.Starg; continue; case 15: current.OpCode = OpCodes.Ldloc; continue; case 16: current.OpCode = OpCodes.Ldloca; continue; case 17: current.OpCode = OpCodes.Stloc; continue; case 19: ExpandMacro(current, OpCodes.Ldc_I4, -1); continue; case 20: ExpandMacro(current, OpCodes.Ldc_I4, 0); continue; case 21: ExpandMacro(current, OpCodes.Ldc_I4, 1); continue; case 22: ExpandMacro(current, OpCodes.Ldc_I4, 2); continue; case 23: ExpandMacro(current, OpCodes.Ldc_I4, 3); continue; case 24: ExpandMacro(current, OpCodes.Ldc_I4, 4); continue; case 25: ExpandMacro(current, OpCodes.Ldc_I4, 5); continue; case 26: ExpandMacro(current, OpCodes.Ldc_I4, 6); continue; case 27: ExpandMacro(current, OpCodes.Ldc_I4, 7); continue; case 28: ExpandMacro(current, OpCodes.Ldc_I4, 8); continue; case 29: ExpandMacro(current, OpCodes.Ldc_I4, (int)(sbyte)current.Operand); continue; case 40: current.OpCode = OpCodes.Br; continue; case 41: current.OpCode = OpCodes.Brfalse; continue; case 42: current.OpCode = OpCodes.Brtrue; continue; case 43: current.OpCode = OpCodes.Beq; continue; case 44: current.OpCode = OpCodes.Bge; continue; case 45: current.OpCode = OpCodes.Bgt; continue; case 46: current.OpCode = OpCodes.Ble; continue; case 47: current.OpCode = OpCodes.Blt; continue; case 48: current.OpCode = OpCodes.Bne_Un; continue; case 49: current.OpCode = OpCodes.Bge_Un; continue; case 50: current.OpCode = OpCodes.Bgt_Un; continue; case 51: current.OpCode = OpCodes.Ble_Un; continue; case 52: current.OpCode = OpCodes.Blt_Un; continue; case 18: case 30: case 31: case 32: case 33: case 34: case 35: case 36: case 37: case 38: case 39: continue; } if ((int)code == 188) { current.OpCode = OpCodes.Leave; } } } finally { ((IDisposable)enumerator).Dispose(); } } private static void ExpandMacro(Instruction instruction, OpCode opcode, object operand) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) instruction.OpCode = opcode; instruction.Operand = operand; } private static void MakeMacro(Instruction instruction, OpCode opcode) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) instruction.OpCode = opcode; instruction.Operand = null; } public static void Optimize(this MethodBody self) { if (self == null) { throw new ArgumentNullException("self"); } self.OptimizeLongs(); self.OptimizeMacros(); } private static void OptimizeLongs(this MethodBody self) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: 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: Invalid comparison between Unknown and I4 //IL_0042: 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) for (int i = 0; i < self.Instructions.Count; i++) { Instruction val = self.Instructions[i]; OpCode opCode = val.OpCode; if ((int)((OpCode)(ref opCode)).Code == 33) { long num = (long)val.Operand; if (num < int.MaxValue && num > int.MinValue) { ExpandMacro(val, OpCodes.Ldc_I4, (int)num); self.Instructions.Insert(++i, Instruction.Create(OpCodes.Conv_I8)); } } } } public static void OptimizeMacros(this MethodBody self) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Invalid comparison between Unknown and I4 //IL_0048: 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_006d: Expected I4, but got Unknown //IL_02fa: Unknown result type (might be due to invalid IL or missing references) //IL_030a: Unknown result type (might be due to invalid IL or missing references) //IL_031a: Unknown result type (might be due to invalid IL or missing references) //IL_0327: 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_0341: 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_035b: Unknown result type (might be due to invalid IL or missing references) //IL_0368: Unknown result type (might be due to invalid IL or missing references) //IL_0375: 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_0238: Unknown result type (might be due to invalid IL or missing references) //IL_0124: Unknown result type (might be due to invalid IL or missing references) //IL_028c: Unknown result type (might be due to invalid IL or missing references) //IL_01ae: Unknown result type (might be due to invalid IL or missing references) //IL_0148: Unknown result type (might be due to invalid IL or missing references) //IL_0158: Unknown result type (might be due to invalid IL or missing references) //IL_0168: 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_02a1: Unknown result type (might be due to invalid IL or missing references) //IL_01d2: Unknown result type (might be due to invalid IL or missing references) //IL_01e2: Unknown result type (might be due to invalid IL or missing references) //IL_01f2: Unknown result type (might be due to invalid IL or missing references) //IL_0202: 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_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: Unknown result type (might be due to invalid IL or missing references) //IL_0271: Unknown result type (might be due to invalid IL or missing references) //IL_0193: Unknown result type (might be due to invalid IL or missing references) //IL_021d: Unknown result type (might be due to invalid IL or missing references) //IL_0109: Unknown result type (might be due to invalid IL or missing references) if (self == null) { throw new ArgumentNullException("self"); } MethodDefinition method = self.Method; Enumerator<Instruction> enumerator = self.Instructions.GetEnumerator(); try { while (enumerator.MoveNext()) { Instruction current = enumerator.Current; OpCode opCode = current.OpCode; Code code = ((OpCode)(ref opCode)).Code; if ((int)code != 32) { switch (code - 199) { case 0: { int index = ((ParameterReference)(ParameterDefinition)current.Operand).Index; if (index == -1 && current.Operand == self.ThisParameter) { index = 0; } else if (((MethodReference)method).HasThis) { index++; } switch (index) { case 0: MakeMacro(current, OpCodes.Ldarg_0); break; case 1: MakeMacro(current, OpCodes.Ldarg_1); break; case 2: MakeMacro(current, OpCodes.Ldarg_2); break; case 3: MakeMacro(current, OpCodes.Ldarg_3); break; default: if (index < 256) { ExpandMacro(current, OpCodes.Ldarg_S, current.Operand); } break; } break; } case 3: { int index = ((VariableReference)(VariableDefinition)current.Operand).Index; switch (index) { case 0: MakeMacro(current, OpCodes.Ldloc_0); break; case 1: MakeMacro(current, OpCodes.Ldloc_1); break; case 2: MakeMacro(current, OpCodes.Ldloc_2); break; case 3: MakeMacro(current, OpCodes.Ldloc_3); break; default: if (index < 256) { ExpandMacro(current, OpCodes.Ldloc_S, current.Operand); } break; } break; } case 5: { int index = ((VariableReference)(VariableDefinition)current.Operand).Index; switch (index) { case 0: MakeMacro(current, OpCodes.Stloc_0); break; case 1: MakeMacro(current, OpCodes.Stloc_1); break; case 2: MakeMacro(current, OpCodes.Stloc_2); break; case 3: MakeMacro(current, OpCodes.Stloc_3); break; default: if (index < 256) { ExpandMacro(current, OpCodes.Stloc_S, current.Operand); } break; } break; } case 1: { int index = ((ParameterReference)(ParameterDefinition)current.Operand).Index; if (index == -1 && current.Operand == self.ThisParameter) { index = 0; } else if (((MethodReference)method).HasThis) { index++; } if (index < 256) { ExpandMacro(current, OpCodes.Ldarga_S, current.Operand); } break; } case 4: if (((VariableReference)(VariableDefinition)current.Operand).Index < 256) { ExpandMacro(current, OpCodes.Ldloca_S, current.Operand); } break; } continue; } int num = (int)current.Operand; switch (num) { case -1: MakeMacro(current, OpCodes.Ldc_I4_M1); continue; case 0: MakeMacro(current, OpCodes.Ldc_I4_0); continue; case 1: MakeMacro(current, OpCodes.Ldc_I4_1); continue; case 2: MakeMacro(current, OpCodes.Ldc_I4_2); continue; case 3: MakeMacro(current, OpCodes.Ldc_I4_3); continue; case 4: MakeMacro(current, OpCodes.Ldc_I4_4); continue; case 5: MakeMacro(current, OpCodes.Ldc_I4_5); continue; case 6: MakeMacro(current, OpCodes.Ldc_I4_6); continue; case 7: MakeMacro(current, OpCodes.Ldc_I4_7); continue; case 8: MakeMacro(current, OpCodes.Ldc_I4_8); continue; } if (num >= -128 && num < 128) { ExpandMacro(current, OpCodes.Ldc_I4_S, (sbyte)num); } } } finally { ((IDisposable)enumerator).Dispose(); } OptimizeBranches(self); } private static void OptimizeBranches(MethodBody body) { //IL_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_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_0025: Unknown result type (might be due to invalid IL or missing references) ComputeOffsets(body); Enumerator<Instruction> enumerator = body.Instructions.GetEnumerator(); try { while (enumerator.MoveNext()) { Instruction current = enumerator.Current; OpCode opCode = current.OpCode; if ((int)((OpCode)(ref opCode)).OperandType == 0 && OptimizeBranch(current)) { ComputeOffsets(body); } } } finally { ((IDisposable)enumerator).Dispose(); } } private static bool OptimizeBranch(Instruction instruction) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //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_0036: 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_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_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Expected I4, but got Unknown //IL_0092: 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_00b2: 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_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00df: 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_00f9: 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_0113: 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_012d: Unknown result type (might be due to invalid IL or missing references) //IL_013a: 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_0087: Invalid comparison between Unknown and I4 //IL_0147: Unknown result type (might be due to invalid IL or missing references) int offset = ((Instruction)instruction.Operand).Offset; int offset2 = instruction.Offset; OpCode opCode = instruction.OpCode; int num = offset - (offset2 + ((OpCode)(ref opCode)).Size + 4); if (num < -128 || num > 127) { return false; } opCode = instruction.OpCode; Code code = ((OpCode)(ref opCode)).Code; switch (code - 55) { default: if ((int)code == 187) { instruction.OpCode = OpCodes.Leave_S; } break; case 0: instruction.OpCode = OpCodes.Br_S; break; case 1: instruction.OpCode = OpCodes.Brfalse_S; break; case 2: instruction.OpCode = OpCodes.Brtrue_S; break; case 3: instruction.OpCode = OpCodes.Beq_S; break; case 4: instruction.OpCode = OpCodes.Bge_S; break; case 5: instruction.OpCode = OpCodes.Bgt_S; break; case 6: instruction.OpCode = OpCodes.Ble_S; break; case 7: instruction.OpCode = OpCodes.Blt_S; break; case 8: instruction.OpCode = OpCodes.Bne_Un_S; break; case 9: instruction.OpCode = OpCodes.Bge_Un_S; break; case 10: instruction.OpCode = OpCodes.Bgt_Un_S; break; case 11: instruction.OpCode = OpCodes.Ble_Un_S; break; case 12: instruction.OpCode = OpCodes.Blt_Un_S; break; } return true; } private static void ComputeOffsets(MethodBody body) { //IL_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) int num = 0; Enumerator<Instruction> enumerator = body.Instructions.GetEnumerator(); try { while (enumerator.MoveNext()) { Instruction current = enumerator.Current; current.Offset = num; num += current.GetSize(); } } finally { ((IDisposable)enumerator).Dispose(); } } } public static class MethodDefinitionRocks { public static MethodDefinition GetBaseMethod(this MethodDefinition self) { if (self == null) { throw new ArgumentNullException("self"); } if (!self.IsVirtual) { return self; } if (self.IsNewSlot) { return self; } for (TypeDefinition val = ResolveBaseType(self.DeclaringType); val != null; val = ResolveBaseType(val)) { MethodDefinition matchingMethod = GetMatchingMethod(val, self); if (matchingMethod != null) { return matchingMethod; } } return self; } public static MethodDefinition GetOriginalBaseMethod(this MethodDefinition self) { if (self == null) { throw new ArgumentNullException("self"); } while (true) { MethodDefinition baseMethod = self.GetBaseMethod(); if (baseMethod == self) { break; } self = baseMethod; } return self; } private static TypeDefinition ResolveBaseType(TypeDefinition type) { if (type == null) { return null; } TypeReference baseType = type.BaseType; if (baseType == null) { return null; } return baseType.Resolve(); } private static MethodDefinition GetMatchingMethod(TypeDefinition type, MethodDefinition method) { return MetadataResolver.GetMethod(type.Methods, (MethodReference)(object)method); } } public static class ModuleDefinitionRocks { public static IEnumerable<TypeDefinition> GetAllTypes(this ModuleDefinition self) { if (self == null) { throw new ArgumentNullException("self"); } return ((IEnumerable<TypeDefinition>)self.Types).SelectMany(Functional.Y((Func<TypeDefinition, IEnumerable<TypeDefinition>> f) => (TypeDefinition type) => ((IEnumerable<TypeDefinition>)type.NestedTypes).SelectMany(f).Prepend(type))); } } public static class ParameterReferenceRocks { public static int GetSequence(this ParameterReference self) { return self.Index + 1; } } public static class SecurityDeclarationRocks { public static PermissionSet ToPermissionSet(this SecurityDeclaration self) { if (self == null) { throw new ArgumentNullException("self"); } if (TryProcessPermissionSetAttribute(self, out var set)) { return set; } return CreatePermissionSet(self); } private static bool TryProcessPermissionSetAttribute(SecurityDeclaration declaration, out PermissionSet set) { //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Expected I4, but got Unknown //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Expected O, but got Unknown //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_005c: 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) set = null; if (!declaration.HasSecurityAttributes && declaration.SecurityAttributes.Count != 1) { return false; } SecurityAttribute val = declaration.SecurityAttributes[0]; if (!Mixin.IsTypeOf(val.AttributeType, "System.Security.Permissions", "PermissionSetAttribute")) { return false; } PermissionSetAttribute val2 = new PermissionSetAttribute((SecurityAction)declaration.Action); CustomAttributeNamedArgument val3 = val.Properties[0]; CustomAttributeArgument argument = ((CustomAttributeNamedArgument)(ref val3)).Argument; string text = (string)((CustomAttributeArgument)(ref argument)).Value; string name = ((CustomAttributeNamedArgument)(ref val3)).Name; if (!(name == "XML")) { if (!(name == "Name")) { throw new NotImplementedException(((CustomAttributeNamedArgument)(ref val3)).Name); } val2.Name = text; } else { val2.XML = text; } set = val2.CreatePermissionSet(); return true; } private static PermissionSet CreatePermissionSet(SecurityDeclaration declaration) { //IL_000d: 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) PermissionSet permissionSet = new PermissionSet(PermissionState.None); Enumerator<SecurityAttribute> enumerator = declaration.SecurityAttributes.GetEnumerator(); try { while (enumerator.MoveNext()) { SecurityAttribute current = enumerator.Current; IPermission perm = CreatePermission(declaration, current); permissionSet.AddPermission(perm); } return permissionSet; } finally { ((IDisposable)enumerator).Dispose(); } } private static IPermission CreatePermission(SecurityDeclaration declaration, SecurityAttribute attribute) { SecurityAttribute obj = CreateSecurityAttribute(Type.GetType(((MemberReference)attribute.AttributeType).FullName) ?? throw new ArgumentException("attribute"), declaration) ?? throw new InvalidOperationException(); CompleteSecurityAttribute(obj, attribute); return obj.CreatePermission(); } private static void CompleteSecurityAttribute(SecurityAttribute security_attribute, SecurityAttribute attribute) { if (attribute.HasFields) { CompleteSecurityAttributeFields(security_attribute, attribute); } if (attribute.HasProperties) { CompleteSecurityAttributeProperties(security_attribute, attribute); } } private static void CompleteSecurityAttributeFields(SecurityAttribute security_attribute, SecurityAttribute attribute) { //IL_000d: 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_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_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) Type type = security_attribute.GetType(); Enumerator<CustomAttributeNamedArgument> enumerator = attribute.Fields.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttributeNamedArgument current = enumerator.Current; FieldInfo? field = type.GetField(((CustomAttributeNamedArgument)(ref current)).Name); CustomAttributeArgument argument = ((CustomAttributeNamedArgument)(ref current)).Argument; field.SetValue(security_attribute, ((CustomAttributeArgument)(ref argument)).Value); } } finally { ((IDisposable)enumerator).Dispose(); } } private static void CompleteSecurityAttributeProperties(SecurityAttribute security_attribute, SecurityAttribute attribute) { //IL_000d: 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_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_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) Type type = security_attribute.GetType(); Enumerator<CustomAttributeNamedArgument> enumerator = attribute.Properties.GetEnumerator(); try { while (enumerator.MoveNext()) { CustomAttributeNamedArgument current = enumerator.Current; PropertyInfo? property = type.GetProperty(((CustomAttributeNamedArgument)(ref current)).Name); CustomAttributeArgument argument = ((CustomAttributeNamedArgument)(ref current)).Argument; property.SetValue(security_attribute, ((CustomAttributeArgument)(ref argument)).Value, null); } } finally { ((IDisposable)enumerator).Dispose(); } } private static SecurityAttribute CreateSecurityAttribute(Type attribute_type, SecurityDeclaration declaration) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Expected I4, but got Unknown try { return (SecurityAttribute)Activator.CreateInstance(attribute_type, (SecurityAction)declaration.Action); } catch (MissingMethodException) { return (SecurityAttribute)Activator.CreateInstance(attribute_type, new object[0]); } } public static SecurityDeclaration ToSecurityDeclaration(this PermissionSet self, SecurityAction action, ModuleDefinition module) { //IL_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_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Expected O, but got Unknown //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Expected O, but got Unknown if (self == null) { throw new ArgumentNullException("self"); } if (module == null) { throw new ArgumentNullException("module"); } SecurityDeclaration val = new SecurityDeclaration(action); SecurityAttribute val2 = new SecurityAttribute(module.TypeSystem.LookupType("System.Security.Permissions", "PermissionSetAttribute")); val2.Properties.Add(new CustomAttributeNamedArgument("XML", new CustomAttributeArgument(module.TypeSystem.String, (object)self.ToXml().ToString()))); val.SecurityAttributes.Add(val2); return val; } } public static class TypeDefinitionRocks { public static IEnumerable<MethodDefinition> GetConstructors(this TypeDefinition self) { if (self == null) { throw new ArgumentNullException("self"); } if (!self.HasMethods) { return Empty<MethodDefinition>.Array; } return ((IEnumerable<MethodDefinition>)self.Methods).Where((MethodDefinition method) => method.IsConstructor); } public static MethodDefinition GetStaticConstructor(this TypeDefinition self) { if (self == null) { throw new ArgumentNullException("self"); } if (!self.HasMethods) { return null; } return self.GetConstructors().FirstOrDefault((Func<MethodDefinition, bool>)((MethodDefinition ctor) => ctor.IsStatic)); } public static IEnumerable<MethodDefinition> GetMethods(this TypeDefinition self) { if (self == null) { throw new ArgumentNullException("self"); } if (!self.HasMethods) { return Empty<MethodDefinition>.Array; } return ((IEnumerable<MethodDefinition>)self.Methods).Where((MethodDefinition method) => !method.IsConstructor); } public static TypeReference GetEnumUnderlyingType(this TypeDefinition self) { if (self == null) { throw new ArgumentNullException("self"); } if (!self.IsEnum) { throw new ArgumentException(); } return Mixin.GetEnumUnderlyingType(self); } } public static class TypeReferenceRocks { public static ArrayType MakeArrayType(this TypeReference self) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown return new ArrayType(self); } public static ArrayType MakeArrayType(this TypeReference self, int rank) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Expected O, but got Unknown //IL_0021: 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) if (rank == 0) { throw new ArgumentOutOfRangeException("rank"); } ArrayType val = new ArrayType(self); for (int i = 1; i < rank; i++) { val.Dimensions.Add(default(ArrayDimension)); } return val; } public static PointerType MakePointerType(this TypeReference self) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown return new PointerType(self); } public static ByReferenceType MakeByReferenceType(this TypeReference self) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown return new ByReferenceType(self); } public static OptionalModifierType MakeOptionalModifierType(this TypeReference self, TypeReference modifierType) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown return new OptionalModifierType(modifierType, self); } public static RequiredModifierType MakeRequiredModifierType(this TypeReference self, TypeReference modifierType) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown return new RequiredModifierType(modifierType, self); } public static GenericInstanceType MakeGenericInstanceType(this TypeReference self, params TypeReference[] arguments) { //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Expected O, but got Unknown if (self == null) { throw new ArgumentNullException("self"); } if (arguments == null) { throw new ArgumentNullException("arguments"); } if (arguments.Length == 0) { throw new ArgumentException(); } if (self.GenericParameters.Count != arguments.Length) { throw new ArgumentException(); } GenericInstanceType val = new GenericInstanceType(self); foreach (TypeReference val2 in arguments) { val.GenericArguments.Add(val2); } return val; } public static PinnedType MakePinnedType(this TypeReference self) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown return new PinnedType(self); } public static SentinelType MakeSentinelType(this TypeReference self) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown return new SentinelType(self); } }
BepInExPack\BepInEx\core\MonoMod.RuntimeDetour.dll
Decompiled 2 months ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Net; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Mono.Cecil; using Mono.Cecil.Cil; using Mono.Collections.Generic; using MonoMod.Cil; using MonoMod.RuntimeDetour.HookGen; using MonoMod.RuntimeDetour.Platforms; using MonoMod.Utils; using MonoMod.Utils.Cil; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyCompany("0x0ade")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright 2022 0x0ade")] [assembly: AssemblyDescription("Flexible and easily extensible runtime detouring library. Wrap, replace and manipulate (Mono.Cecil) methods at runtime.")] [assembly: AssemblyFileVersion("22.5.1.1")] [assembly: AssemblyInformationalVersion("22.05.01.01")] [assembly: AssemblyProduct("MonoMod.RuntimeDetour")] [assembly: AssemblyTitle("MonoMod.RuntimeDetour")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("22.5.1.1")] [module: UnverifiableCode] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } } internal static class MultiTargetShims { private static readonly object[] _NoArgs = new object[0]; public static string Replace(this string self, string oldValue, string newValue, StringComparison comparison) { return self.Replace(oldValue, newValue); } public static bool Contains(this string self, string value, StringComparison comparison) { return self.Contains(value); } public static int GetHashCode(this string self, StringComparison comparison) { return self.GetHashCode(); } public static int IndexOf(this string self, char value, StringComparison comparison) { return self.IndexOf(value); } public static int IndexOf(this string self, string value, StringComparison comparison) { return self.IndexOf(value); } public static TypeReference GetConstraintType(this TypeReference type) { return type; } } namespace MonoMod { internal static class MMDbgLog { public static readonly string Tag; public static TextWriter Writer; public static bool Debugging; static MMDbgLog() { Tag = typeof(MMDbgLog).Assembly.GetName().Name; if (!(Environment.GetEnvironmentVariable("MONOMOD_DBGLOG") == "1")) { string? environmentVariable = Environment.GetEnvironmentVariable("MONOMOD_DBGLOG"); bool? obj; if (environmentVariable == null) { obj = null; } else { string text = environmentVariable.ToLower(CultureInfo.InvariantCulture); obj = ((text != null) ? new bool?(MultiTargetShims.Contains(text, Tag.ToLower(CultureInfo.InvariantCulture), StringComparison.Ordinal)) : ((bool?)null)); } bool? flag = obj; if (flag != true) { return; } } Start(); } public static void WaitForDebugger() { if (!Debugging) { Debugging = true; Debugger.Launch(); Thread.Sleep(6000); Debugger.Break(); } } public static void Start() { if (Writer != null) { return; } string text = Environment.GetEnvironmentVariable("MONOMOD_DBGLOG_PATH"); if (text == "-") { Writer = Console.Out; return; } if (string.IsNullOrEmpty(text)) { text = "mmdbglog.txt"; } text = Path.GetFullPath(Path.GetFileNameWithoutExtension(text) + "-" + Tag + Path.GetExtension(text)); try { if (File.Exists(text)) { File.Delete(text); } } catch { } try { string directoryName = Path.GetDirectoryName(text); if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } Writer = new StreamWriter(new FileStream(text, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete), Encoding.UTF8); } catch { } } public static void Log(string str) { TextWriter writer = Writer; if (writer != null) { writer.WriteLine(str); writer.Flush(); } } public static T Log<T>(string str, T value) { TextWriter writer = Writer; if (writer == null) { return value; } writer.WriteLine(string.Format(CultureInfo.InvariantCulture, str, new object[1] { value })); writer.Flush(); return value; } } } namespace MonoMod.RuntimeDetour { public struct DetourConfig { public bool ManualApply; public int Priority; public string ID; public IEnumerable<string> Before; public IEnumerable<string> After; } public class Detour : ISortableDetour, IDetour, IDisposable { private static Dictionary<MethodBase, List<Detour>> _DetourMap = new Dictionary<MethodBase, List<Detour>>((IEqualityComparer<MethodBase>?)new GenericMethodInstantiationComparer()); private static Dictionary<MethodBase, MethodInfo> _BackupMethods = new Dictionary<MethodBase, MethodInfo>(); private static uint _GlobalIndexNext = 0u; public static Func<Detour, MethodBase, MethodBase, bool> OnDetour; public static Func<Detour, bool> OnUndo; public static Func<Detour, MethodBase, MethodBase> OnGenerateTrampoline; private readonly uint _GlobalIndex; private int _Priority; private string _ID; private List<string> _Before = new List<string>(); private ReadOnlyCollection<string> _BeforeRO; private List<string> _After = new List<string>(); private ReadOnlyCollection<string> _AfterRO; public readonly MethodBase Method; public readonly MethodBase Target; public readonly MethodBase TargetReal; private NativeDetour _TopDetour; private MethodInfo _ChainedTrampoline; private static int compileMethodSubscribed = 0; private List<Detour> _DetourChain { get { if (!_DetourMap.TryGetValue(Method, out var value)) { return null; } return value; } } public bool IsValid => Index != -1; public bool IsApplied { get; private set; } private bool IsTop => _TopDetour != null; public int Index => _DetourChain?.IndexOf(this) ?? (-1); public int MaxIndex => _DetourChain?.Count ?? (-1); public uint GlobalIndex => _GlobalIndex; public int Priority { get { return _Priority; } set { if (_Priority != value) { _Priority = value; _RefreshChain(Method); } } } public string ID { get { return _ID; } set { if (string.IsNullOrEmpty(value)) { value = Extensions.GetID(Target, (string)null, (string)null, true, false, true); } if (!(_ID == value)) { _ID = value; _RefreshChain(Method); } } } public IEnumerable<string> Before { get { return _BeforeRO ?? (_BeforeRO = _Before.AsReadOnly()); } set { lock (_Before) { _Before.Clear(); if (value != null) { foreach (string item in value) { _Before.Add(item); } } _RefreshChain(Method); } } } public IEnumerable<string> After { get { return _AfterRO ?? (_AfterRO = _After.AsReadOnly()); } set { lock (_After) { _After.Clear(); if (value != null) { foreach (string item in value) { _After.Add(item); } } _RefreshChain(Method); } } } public Detour(MethodBase from, MethodBase to, ref DetourConfig config) { //IL_024f: Unknown result type (might be due to invalid IL or missing references) //IL_0256: Expected O, but got Unknown from = from.GetIdentifiable(); if (from.Equals(to)) { throw new ArgumentException("Cannot detour a method to itself!"); } MMDbgLog.Log("detour from " + Extensions.GetID(from, (string)null, (string)null, true, false, false) + " to " + Extensions.GetID(to, (string)null, (string)null, true, false, false)); Method = from; Target = to.Pin(); TargetReal = DetourHelper.Runtime.GetDetourTarget(from, to); _GlobalIndex = _GlobalIndexNext++; _Priority = config.Priority; _ID = config.ID; if (config.Before != null) { foreach (string item in config.Before) { _Before.Add(item); } } if (config.After != null) { foreach (string item2 in config.After) { _After.Add(item2); } } lock (_BackupMethods) { if ((!_BackupMethods.TryGetValue(Method, out var value) || (object)value == null) && (object)(value = Method.CreateILCopy()) != null) { _BackupMethods[Method] = value.Pin(); } } ParameterInfo[] parameters = Method.GetParameters(); Type[] array; if (!Method.IsStatic) { array = new Type[parameters.Length + 1]; array[0] = Extensions.GetThisParamType(Method); for (int i = 0; i < parameters.Length; i++) { array[i + 1] = parameters[i].ParameterType; } } else { array = new Type[parameters.Length]; for (int j = 0; j < parameters.Length; j++) { array[j] = parameters[j].ParameterType; } } DynamicMethodDefinition val = new DynamicMethodDefinition($"Chain<{Extensions.GetID(Method, (string)null, (string)null, true, false, true)}>?{GetHashCode()}", (Method as MethodInfo)?.ReturnType ?? typeof(void), array); try { _ChainedTrampoline = val.StubCriticalDetour().Generate().Pin(); } finally { ((IDisposable)val)?.Dispose(); } List<Detour> value2; lock (_DetourMap) { if (!_DetourMap.TryGetValue(Method, out value2)) { value2 = (_DetourMap[Method] = new List<Detour>()); } } lock (value2) { value2.Add(this); } if (!config.ManualApply) { Apply(); } } public Detour(MethodBase from, MethodBase to, DetourConfig config) : this(from, to, ref config) { } public Detour(MethodBase from, MethodBase to) : this(from, to, DetourContext.Current?.DetourConfig ?? default(DetourConfig)) { } public Detour(MethodBase method, IntPtr to, ref DetourConfig config) : this(method, DetourHelper.GenerateNativeProxy(to, method), ref config) { } public Detour(MethodBase method, IntPtr to, DetourConfig config) : this(method, DetourHelper.GenerateNativeProxy(to, method), ref config) { } public Detour(MethodBase method, IntPtr to) : this(method, DetourHelper.GenerateNativeProxy(to, method)) { } public Detour(Delegate from, IntPtr to, ref DetourConfig config) : this(from.Method, to, ref config) { } public Detour(Delegate from, IntPtr to, DetourConfig config) : this(from.Method, to, ref config) { } public Detour(Delegate from, IntPtr to) : this(from.Method, to) { } public Detour(Delegate from, Delegate to, ref DetourConfig config) : this(from.Method, to.Method, ref config) { } public Detour(Delegate from, Delegate to, DetourConfig config) : this(from.Method, to.Method, ref config) { } public Detour(Delegate from, Delegate to) : this(from.Method, to.Method) { } public Detour(Expression from, IntPtr to, ref DetourConfig config) : this(((MethodCallExpression)from).Method, to, ref config) { } public Detour(Expression from, IntPtr to, DetourConfig config) : this(((MethodCallExpression)from).Method, to, ref config) { } public Detour(Expression from, IntPtr to) : this(((MethodCallExpression)from).Method, to) { } public Detour(Expression from, Expression to, ref DetourConfig config) : this(((MethodCallExpression)from).Method, ((MethodCallExpression)to).Method, ref config) { } public Detour(Expression from, Expression to, DetourConfig config) : this(((MethodCallExpression)from).Method, ((MethodCallExpression)to).Method, ref config) { } public Detour(Expression from, Expression to) : this(((MethodCallExpression)from).Method, ((MethodCallExpression)to).Method) { } public Detour(Expression<Action> from, IntPtr to, ref DetourConfig config) : this(from.Body, to, ref config) { } public Detour(Expression<Action> from, IntPtr to, DetourConfig config) : this(from.Body, to, ref config) { } public Detour(Expression<Action> from, IntPtr to) : this(from.Body, to) { } public Detour(Expression<Action> from, Expression<Action> to, ref DetourConfig config) : this(from.Body, to.Body, ref config) { } public Detour(Expression<Action> from, Expression<Action> to, DetourConfig config) : this(from.Body, to.Body, ref config) { } public Detour(Expression<Action> from, Expression<Action> to) : this(from.Body, to.Body) { } public void Apply() { if (!IsValid) { throw new ObjectDisposedException("Detour"); } if (!IsApplied) { Func<Detour, MethodBase, MethodBase, bool> onDetour = OnDetour; if (onDetour == null || Extensions.InvokeWhileTrue((MulticastDelegate)onDetour, new object[3] { this, Method, Target })) { IsApplied = true; _RefreshChain(Method); } } } public void Undo() { if (!IsValid) { throw new ObjectDisposedException("Detour"); } if (IsApplied) { Func<Detour, bool> onUndo = OnUndo; if (onUndo == null || Extensions.InvokeWhileTrue((MulticastDelegate)onUndo, new object[1] { this })) { IsApplied = false; _RefreshChain(Method); } } } public void Free() { if (!IsValid) { return; } Undo(); List<Detour> detourChain = _DetourChain; lock (detourChain) { detourChain.Remove(this); if (detourChain.Count == 0) { lock (_BackupMethods) { if (_BackupMethods.TryGetValue(Method, out var value)) { value.Unpin(); _BackupMethods.Remove(Method); } } lock (_DetourMap) { _DetourMap.Remove(Method); } } } _ChainedTrampoline.Unpin(); Target.Unpin(); } public void Dispose() { if (IsValid) { Undo(); Free(); } } public MethodBase GenerateTrampoline(MethodBase signature = null) { //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Expected O, but got Unknown //IL_00be: 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_00f6: 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) Func<Detour, MethodBase, MethodBase> onGenerateTrampoline = OnGenerateTrampoline; MethodBase methodBase = ((onGenerateTrampoline != null) ? Extensions.InvokeWhileNull<MethodBase>((MulticastDelegate)onGenerateTrampoline, new object[2] { this, signature }) : null); if ((object)methodBase != null) { return methodBase; } if ((object)signature == null) { signature = Target; } Type type = (signature as MethodInfo)?.ReturnType ?? typeof(void); ParameterInfo[] parameters = signature.GetParameters(); Type[] array = new Type[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { array[i] = parameters[i].ParameterType; } DynamicMethodDefinition val = new DynamicMethodDefinition($"Trampoline<{Extensions.GetID(Method, (string)null, (string)null, true, false, true)}>?{GetHashCode()}", type, array); try { ILProcessor iLProcessor = val.GetILProcessor(); for (int j = 0; j < 32; j++) { iLProcessor.Emit(OpCodes.Nop); } for (int k = 0; k < array.Length; k++) { iLProcessor.Emit(OpCodes.Ldarg, k); } Extensions.Emit(iLProcessor, OpCodes.Call, (MethodBase)_ChainedTrampoline); iLProcessor.Emit(OpCodes.Ret); return val.Generate(); } finally { ((IDisposable)val)?.Dispose(); } } public T GenerateTrampoline<T>() where T : Delegate { if (!typeof(Delegate).IsAssignableFrom(typeof(T))) { throw new InvalidOperationException($"Type {typeof(T)} not a delegate type."); } return Extensions.CreateDelegate(GenerateTrampoline(typeof(T).GetMethod("Invoke")), typeof(T)) as T; } private void _TopUndo() { if (_TopDetour != null) { _TopDetour.Undo(); _TopDetour.Free(); _TopDetour = null; Method.Unpin(); TargetReal.Unpin(); } } private void _TopApply() { if (_TopDetour == null) { _TopDetour = new NativeDetour(Method.Pin().GetNativeStart(), TargetReal.Pin().GetNativeStart()); } } private static void _OnCompileMethod(MethodBase method, IntPtr codeStart, ulong codeLen) { if ((object)method == null) { return; } MMDbgLog.Log("compiling: " + Extensions.GetID(method, (string)null, (string)null, true, false, false)); if (_DetourMap.TryGetValue(method, out var value)) { value.FindLast((Detour d) => d.IsTop)?._TopDetour?.ChangeSource(codeStart); } } private static void _RefreshChain(MethodBase method) { if (Interlocked.CompareExchange(ref compileMethodSubscribed, 1, 0) == 0) { DetourHelper.Runtime.OnMethodCompiled += _OnCompileMethod; } MMDbgLog.Log("detours applying for " + Extensions.GetID(method, (string)null, (string)null, true, false, false)); List<Detour> list = _DetourMap[method]; lock (list) { DetourSorter<Detour>.Sort(list); Detour detour = list.FindLast((Detour d) => d.IsTop); Detour detour2 = list.FindLast((Detour d) => d.IsApplied); if (detour != detour2) { detour?._TopUndo(); } if (list.Count == 0) { return; } MethodBase method2 = _BackupMethods[method]; foreach (Detour item in list) { if (item.IsApplied) { _ = item._ChainedTrampoline; using (NativeDetour nativeDetour = new NativeDetour(item._ChainedTrampoline.GetNativeStart(), method2.GetNativeStart())) { nativeDetour.Free(); } method2 = item.Target; } } if (detour != detour2) { detour2?._TopApply(); } } } } public class Detour<T> : Detour where T : Delegate { public Detour(T from, IntPtr to, ref DetourConfig config) : base(from, to, ref config) { } public Detour(T from, IntPtr to, DetourConfig config) : base(from, to, ref config) { } public Detour(T from, IntPtr to) : base(from, to) { } public Detour(T from, T to, ref DetourConfig config) : base(from, to, ref config) { } public Detour(T from, T to, DetourConfig config) : base(from, to, ref config) { } public Detour(T from, T to) : base(from, to) { } } public sealed class DetourContext : IDisposable { [ThreadStatic] private static List<DetourContext> _Contexts; [ThreadStatic] private static DetourContext Last; private MethodBase Creator; public int Priority; private readonly string _FallbackID; private string _ID; public List<string> Before = new List<string>(); public List<string> After = new List<string>(); private bool IsDisposed; private static List<DetourContext> Contexts => _Contexts ?? (_Contexts = new List<DetourContext>()); internal static DetourContext Current { get { DetourContext last = Last; if (last != null && last.IsValid) { return Last; } List<DetourContext> contexts = Contexts; int num = contexts.Count - 1; while (num > -1) { DetourContext detourContext = contexts[num]; if (!detourContext.IsValid) { contexts.RemoveAt(num); num--; continue; } return Last = detourContext; } return null; } } public string ID { get { return _ID ?? _FallbackID; } set { _ID = (string.IsNullOrEmpty(value) ? null : value); } } public DetourConfig DetourConfig => new DetourConfig { Priority = Priority, ID = ID, Before = Before, After = After }; public HookConfig HookConfig => new HookConfig { Priority = Priority, ID = ID, Before = Before, After = After }; public ILHookConfig ILHookConfig => new ILHookConfig { Priority = Priority, ID = ID, Before = Before, After = After }; internal bool IsValid { get { if (IsDisposed) { return false; } if ((object)Creator == null) { return true; } StackTrace stackTrace = new StackTrace(); int frameCount = stackTrace.FrameCount; for (int i = 0; i < frameCount; i++) { if ((object)stackTrace.GetFrame(i).GetMethod() == Creator) { return true; } } return false; } } public DetourContext(int priority, string id) { StackTrace stackTrace = new StackTrace(); int frameCount = stackTrace.FrameCount; for (int i = 0; i < frameCount; i++) { MethodBase method = stackTrace.GetFrame(i).GetMethod(); if ((object)method?.DeclaringType != typeof(DetourContext)) { Creator = method; break; } } object obj = Creator?.DeclaringType?.Assembly?.GetName().Name; if (obj == null) { MethodBase creator = Creator; obj = (((object)creator != null) ? Extensions.GetID(creator, (string)null, (string)null, true, false, true) : null); } _FallbackID = (string)obj; Last = this; Contexts.Add(this); Priority = priority; ID = id; } public DetourContext(string id) : this(0, id) { } public DetourContext(int priority) : this(priority, null) { } public DetourContext() : this(0, null) { } public void Dispose() { if (IsDisposed) { IsDisposed = true; Last = null; Contexts.Remove(this); } } } public sealed class DetourModManager : IDisposable { private readonly Dictionary<IDetour, Assembly> DetourOwners = new Dictionary<IDetour, Assembly>(); private readonly Dictionary<Assembly, List<IDetour>> OwnedDetourLists = new Dictionary<Assembly, List<IDetour>>(); public HashSet<Assembly> Ignored = new HashSet<Assembly>(); private bool Disposed; private static readonly string[] HookTypeNames = new string[4] { "MonoMod.RuntimeDetour.NativeDetour", "MonoMod.RuntimeDetour.Detour", "MonoMod.RuntimeDetour.Hook", "MonoMod.RuntimeDetour.ILHook" }; public event Action<Assembly, MethodBase, Manipulator> OnILHook; public event Action<Assembly, MethodBase, MethodBase, object> OnHook; public event Action<Assembly, MethodBase, MethodBase> OnDetour; public event Action<Assembly, MethodBase, IntPtr, IntPtr> OnNativeDetour; public DetourModManager() { Ignored.Add(typeof(DetourModManager).Assembly); ILHook.OnDetour = (Func<ILHook, MethodBase, Manipulator, bool>)Delegate.Combine(ILHook.OnDetour, new Func<ILHook, MethodBase, Manipulator, bool>(RegisterILHook)); ILHook.OnUndo = (Func<ILHook, bool>)Delegate.Combine(ILHook.OnUndo, new Func<ILHook, bool>(UnregisterDetour)); Hook.OnDetour = (Func<Hook, MethodBase, MethodBase, object, bool>)Delegate.Combine(Hook.OnDetour, new Func<Hook, MethodBase, MethodBase, object, bool>(RegisterHook)); Hook.OnUndo = (Func<Hook, bool>)Delegate.Combine(Hook.OnUndo, new Func<Hook, bool>(UnregisterDetour)); Detour.OnDetour = (Func<Detour, MethodBase, MethodBase, bool>)Delegate.Combine(Detour.OnDetour, new Func<Detour, MethodBase, MethodBase, bool>(RegisterDetour)); Detour.OnUndo = (Func<Detour, bool>)Delegate.Combine(Detour.OnUndo, new Func<Detour, bool>(UnregisterDetour)); NativeDetour.OnDetour = (Func<NativeDetour, MethodBase, IntPtr, IntPtr, bool>)Delegate.Combine(NativeDetour.OnDetour, new Func<NativeDetour, MethodBase, IntPtr, IntPtr, bool>(RegisterNativeDetour)); NativeDetour.OnUndo = (Func<NativeDetour, bool>)Delegate.Combine(NativeDetour.OnUndo, new Func<NativeDetour, bool>(UnregisterDetour)); } public void Dispose() { if (!Disposed) { Disposed = true; OwnedDetourLists.Clear(); ILHook.OnDetour = (Func<ILHook, MethodBase, Manipulator, bool>)Delegate.Remove(ILHook.OnDetour, new Func<ILHook, MethodBase, Manipulator, bool>(RegisterILHook)); ILHook.OnUndo = (Func<ILHook, bool>)Delegate.Remove(ILHook.OnUndo, new Func<ILHook, bool>(UnregisterDetour)); Hook.OnDetour = (Func<Hook, MethodBase, MethodBase, object, bool>)Delegate.Remove(Hook.OnDetour, new Func<Hook, MethodBase, MethodBase, object, bool>(RegisterHook)); Hook.OnUndo = (Func<Hook, bool>)Delegate.Remove(Hook.OnUndo, new Func<Hook, bool>(UnregisterDetour)); Detour.OnDetour = (Func<Detour, MethodBase, MethodBase, bool>)Delegate.Remove(Detour.OnDetour, new Func<Detour, MethodBase, MethodBase, bool>(RegisterDetour)); Detour.OnUndo = (Func<Detour, bool>)Delegate.Remove(Detour.OnUndo, new Func<Detour, bool>(UnregisterDetour)); NativeDetour.OnDetour = (Func<NativeDetour, MethodBase, IntPtr, IntPtr, bool>)Delegate.Remove(NativeDetour.OnDetour, new Func<NativeDetour, MethodBase, IntPtr, IntPtr, bool>(RegisterNativeDetour)); NativeDetour.OnUndo = (Func<NativeDetour, bool>)Delegate.Remove(NativeDetour.OnUndo, new Func<NativeDetour, bool>(UnregisterDetour)); } } public void Unload(Assembly asm) { if ((object)asm == null || Ignored.Contains(asm)) { return; } HookEndpointManager.RemoveAllOwnedBy(asm); if (OwnedDetourLists.TryGetValue(asm, out var value)) { IDetour[] array = value.ToArray(); for (int i = 0; i < array.Length; i++) { array[i].Dispose(); } if (value.Count > 0) { throw new Exception("Some detours failed to unregister in " + asm.FullName); } OwnedDetourLists.Remove(asm); } } internal Assembly GetHookOwner(StackTrace stack = null) { if (stack == null) { stack = new StackTrace(); } Assembly assembly = null; int frameCount = stack.FrameCount; string text = null; for (int i = 0; i < frameCount; i++) { MethodBase method = stack.GetFrame(i).GetMethod(); if ((object)method?.DeclaringType == null) { continue; } string fullName = method.DeclaringType.FullName; if (text == null) { if (HookTypeNames.Contains(fullName)) { text = method.DeclaringType.FullName; } } else if (!(fullName == text)) { assembly = method?.DeclaringType.Assembly; break; } } if (Ignored.Contains(assembly)) { return null; } return assembly; } internal void TrackDetour(Assembly owner, IDetour detour) { if (!OwnedDetourLists.TryGetValue(owner, out var value)) { value = (OwnedDetourLists[owner] = new List<IDetour>()); } value.Add(detour); DetourOwners[detour] = owner; } internal bool RegisterILHook(ILHook _detour, MethodBase from, Manipulator manipulator) { Assembly hookOwner = GetHookOwner(); if ((object)hookOwner == null) { return true; } this.OnILHook?.Invoke(hookOwner, from, manipulator); TrackDetour(hookOwner, _detour); return true; } internal bool RegisterHook(Hook _detour, MethodBase from, MethodBase to, object target) { Assembly hookOwner = GetHookOwner(); if ((object)hookOwner == null) { return true; } this.OnHook?.Invoke(hookOwner, from, to, target); TrackDetour(hookOwner, _detour); return true; } internal bool RegisterDetour(Detour _detour, MethodBase from, MethodBase to) { Assembly hookOwner = GetHookOwner(); if ((object)hookOwner == null) { return true; } this.OnDetour?.Invoke(hookOwner, from, to); TrackDetour(hookOwner, _detour); return true; } internal bool RegisterNativeDetour(NativeDetour _detour, MethodBase method, IntPtr from, IntPtr to) { Assembly hookOwner = GetHookOwner(); if ((object)hookOwner == null) { return true; } this.OnNativeDetour?.Invoke(hookOwner, method, from, to); TrackDetour(hookOwner, _detour); return true; } internal bool UnregisterDetour(IDetour _detour) { if (DetourOwners.TryGetValue(_detour, out var value)) { DetourOwners.Remove(_detour); OwnedDetourLists[value].Remove(_detour); } return true; } } public static class HarmonyDetourBridge { public enum Type { Auto, Basic, AsOriginal, Override } private class DetourToRDAttribute : Attribute { public string Type { get; } public int SkipParams { get; } public string Name { get; } public DetourToRDAttribute(string type, int skipParams = 0, string name = null) { Type = type; SkipParams = skipParams; Name = name; } } private class DetourToHAttribute : Attribute { public string Type { get; } public int SkipParams { get; } public string Name { get; } public DetourToHAttribute(string type, int skipParams = 0, string name = null) { Type = type; SkipParams = skipParams; Name = name; } } private class TranspileAttribute : Attribute { public string Type { get; } public string Name { get; } public TranspileAttribute(string type, string name = null) { Type = type; Name = name; } } private class CriticalAttribute : Attribute { } private static Type CurrentType; private static Assembly _HarmonyASM; private static readonly HashSet<IDisposable> _Detours; private static readonly Dictionary<System.Type, MethodInfo> _Emitters; [ThreadStatic] private static DynamicMethodDefinition _LastWrapperDMD; private static Assembly _SharedStateASM; private static DetourConfig _DetourConfig; public static bool Initialized { get; private set; } static HarmonyDetourBridge() { _Detours = new HashSet<IDisposable>(); _Emitters = new Dictionary<System.Type, MethodInfo>(); System.Type typeFromHandle = typeof(OpCode); System.Type proxyType = ILGeneratorShim.GetProxyType<CecilILGenerator>(); MethodInfo[] methods = proxyType.GetMethods(); foreach (MethodInfo methodInfo in methods) { if (methodInfo.Name != "Emit") { continue; } ParameterInfo[] parameters = methodInfo.GetParameters(); if (parameters.Length == 2 && (object)parameters[0].ParameterType == typeFromHandle) { System.Type parameterType = parameters[1].ParameterType; if (!_Emitters.ContainsKey(parameterType) || (object)methodInfo.DeclaringType == proxyType) { _Emitters[parameterType] = methodInfo; } } } } public static bool Init(bool forceLoad = true, Type type = Type.Auto) { //IL_0227: Unknown result type (might be due to invalid IL or missing references) //IL_022e: Expected O, but got Unknown //IL_0238: 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_024a: Expected O, but got Unknown if ((object)_HarmonyASM == null) { _HarmonyASM = _FindHarmony(); } if ((object)_HarmonyASM == null && forceLoad) { _HarmonyASM = Assembly.Load(new AssemblyName { Name = "0Harmony" }); } if ((object)_HarmonyASM == null) { return false; } if (Initialized) { return true; } Initialized = true; if (type == Type.Auto) { type = Type.AsOriginal; } _DetourConfig = new DetourConfig { Priority = type switch { Type.Override => 536870911, Type.AsOriginal => -536870912, _ => 0, } }; CurrentType = type; try { MethodInfo[] methods = typeof(HarmonyDetourBridge).GetMethods(BindingFlags.Static | BindingFlags.NonPublic); foreach (MethodInfo methodInfo in methods) { bool flag = methodInfo.GetCustomAttributes(typeof(CriticalAttribute), inherit: false).Any(); object[] customAttributes = methodInfo.GetCustomAttributes(typeof(DetourToRDAttribute), inherit: false); for (int j = 0; j < customAttributes.Length; j++) { DetourToRDAttribute detourToRDAttribute = (DetourToRDAttribute)customAttributes[j]; foreach (MethodInfo item in GetHarmonyMethod(methodInfo, detourToRDAttribute.Type, detourToRDAttribute.SkipParams, detourToRDAttribute.Name)) { flag = false; _Detours.Add(new Hook(item, methodInfo)); } } customAttributes = methodInfo.GetCustomAttributes(typeof(DetourToHAttribute), inherit: false); for (int j = 0; j < customAttributes.Length; j++) { DetourToHAttribute detourToHAttribute = (DetourToHAttribute)customAttributes[j]; foreach (MethodInfo item2 in GetHarmonyMethod(methodInfo, detourToHAttribute.Type, detourToHAttribute.SkipParams, detourToHAttribute.Name)) { flag = false; _Detours.Add(new Detour(methodInfo, item2)); } } customAttributes = methodInfo.GetCustomAttributes(typeof(TranspileAttribute), inherit: false); for (int j = 0; j < customAttributes.Length; j++) { TranspileAttribute transpileAttribute = (TranspileAttribute)customAttributes[j]; foreach (MethodInfo item3 in GetHarmonyMethod(methodInfo, transpileAttribute.Type, -1, transpileAttribute.Name)) { DynamicMethodDefinition val = new DynamicMethodDefinition((MethodBase)item3); try { flag = false; ILContext val2 = new ILContext(val.Definition) { ReferenceBag = (IILReferenceBag)(object)RuntimeILReferenceBag.Instance }; _Detours.Add((IDisposable)val2); val2.Invoke(Extensions.CreateDelegate<Manipulator>((MethodBase)methodInfo)); if (val2.IsReadOnly) { val2.Dispose(); _Detours.Remove((IDisposable)val2); } else { _Detours.Add(new Detour(item3, val.Generate())); } } finally { ((IDisposable)val)?.Dispose(); } } } if (flag) { throw new Exception("Cannot apply HarmonyDetourBridge rule " + methodInfo.Name); } } } catch { _EarlyReset(); throw; } return true; } private static bool _EarlyReset() { foreach (IDisposable detour in _Detours) { detour.Dispose(); } _Detours.Clear(); return false; } public static void Reset() { if (Initialized) { Initialized = false; _EarlyReset(); } } private static System.Type GetHarmonyType(string typeName) { return _HarmonyASM.GetType(typeName) ?? _HarmonyASM.GetType("HarmonyLib." + typeName) ?? _HarmonyASM.GetType("Harmony." + typeName) ?? _HarmonyASM.GetType("Harmony.ILCopying." + typeName); } private static IEnumerable<MethodInfo> GetHarmonyMethod(MethodInfo ctx, string typeName, int skipParams, string name) { System.Type harmonyType = GetHarmonyType(typeName); if ((object)harmonyType == null) { return null; } if (string.IsNullOrEmpty(name)) { name = ctx.Name; } if (skipParams < 0) { return from method in harmonyType.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) where method.Name == name select method; } return new MethodInfo[1] { harmonyType.GetMethod(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, (from p in ctx.GetParameters().Skip(skipParams) select p.ParameterType).ToArray(), null) }; } private static DynamicMethodDefinition CreateDMD(MethodBase original, string suffix) { //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Expected O, but got Unknown if ((object)original == null) { throw new ArgumentNullException("original"); } ParameterInfo[] parameters = original.GetParameters(); System.Type[] array; if (!original.IsStatic) { array = new System.Type[parameters.Length + 1]; array[0] = Extensions.GetThisParamType(original); for (int i = 0; i < parameters.Length; i++) { array[i + 1] = parameters[i].ParameterType; } } else { array = new System.Type[parameters.Length]; for (int j = 0; j < parameters.Length; j++) { array[j] = parameters[j].ParameterType; } } return new DynamicMethodDefinition(MultiTargetShims.Replace(original.Name + suffix, "<>", "", StringComparison.Ordinal), (original as MethodInfo)?.ReturnType ?? typeof(void), array); } [DetourToRD("Memory", 0, null)] private static long GetMethodStart(MethodBase method, out Exception exception) { exception = null; try { _Detours.Add((IDisposable)new LazyDisposable<MethodBase>(method, (Action<MethodBase>)delegate(MethodBase m) { m.Unpin(); })); return (long)method.Pin().GetNativeStart(); } catch (Exception ex) { exception = ex; return 0L; } } [DetourToRD("Memory", 0, null)] [Critical] private static string WriteJump(long memory, long destination) { _Detours.Add(new NativeDetour((IntPtr)memory, (IntPtr)destination)); return null; } [DetourToRD("Memory", 0, null)] [Critical] private static string DetourMethod(MethodBase original, MethodBase replacement) { if ((object)replacement == null) { replacement = _LastWrapperDMD.Generate(); _LastWrapperDMD.Dispose(); _LastWrapperDMD = null; } _Detours.Add(new Detour(original, replacement, ref _DetourConfig)); return null; } [DetourToRD("MethodBodyReader", 1, null)] private static MethodInfo EmitMethodForType(object self, System.Type type) { foreach (KeyValuePair<System.Type, MethodInfo> emitter in _Emitters) { if ((object)emitter.Key == type) { return emitter.Value; } } foreach (KeyValuePair<System.Type, MethodInfo> emitter2 in _Emitters) { if (emitter2.Key.IsAssignableFrom(type)) { return emitter2.Value; } } return null; } [DetourToRD("PatchProcessor", 2, null)] [Critical] private static List<DynamicMethod> Patch(Func<object, List<DynamicMethod>> orig, object self) { orig(self); return new List<DynamicMethod>(); } [Transpile("PatchFunctions", null)] [Critical] private static void UpdateWrapper(ILContext il) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown //IL_003c: Unknown result type (might be due to invalid IL or missing references) ILCursor val = new ILCursor(il); val.GotoNext(new Func<Instruction, bool>[1] { (Instruction i) => ILPatternMatchingExt.MatchThrow(i) }); val.Next.OpCode = OpCodes.Pop; } [Transpile("MethodPatcher", null)] [Critical] private static void CreatePatchedMethod(ILContext il) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Expected O, but got Unknown //IL_0047: 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_014e: Unknown result type (might be due to invalid IL or missing references) ILCursor val = new ILCursor(il); System.Type t_DynamicTools = GetHarmonyType("DynamicTools"); if (!val.TryGotoNext(new Func<Instruction, bool>[1] { (Instruction i) => ILPatternMatchingExt.MatchCall(i, t_DynamicTools, "CreateDynamicMethod") })) { il.MakeReadOnly(); return; } val.Next.OpCode = OpCodes.Call; val.Next.Operand = il.Import((MethodBase)typeof(HarmonyDetourBridge).GetMethod("CreateDMD", BindingFlags.Static | BindingFlags.NonPublic)); int varDMDi = -1; val.GotoNext(new Func<Instruction, bool>[1] { (Instruction i) => ILPatternMatchingExt.MatchStloc(i, ref varDMDi) }); ((VariableReference)il.Body.Variables[varDMDi]).VariableType = il.Import(typeof(DynamicMethodDefinition)); val.GotoNext(new Func<Instruction, bool>[1] { (Instruction i) => ILPatternMatchingExt.MatchCallvirt<DynamicMethod>(i, "GetILGenerator") }); val.Next.OpCode = OpCodes.Call; val.Next.Operand = il.Import((MethodBase)typeof(DynamicMethodDefinition).GetMethod("GetILGenerator", BindingFlags.Instance | BindingFlags.Public)); val.GotoNext(new Func<Instruction, bool>[1] { (Instruction i) => ILPatternMatchingExt.MatchCall(i, t_DynamicTools, "PrepareDynamicMethod") }); val.Next.OpCode = OpCodes.Pop; val.Next.Operand = null; val.GotoNext(new Func<Instruction, bool>[1] { (Instruction i) => ILPatternMatchingExt.MatchLdloc(i, varDMDi) }); int index = val.Index; val.Index = index + 1; val.EmitDelegate<Func<DynamicMethodDefinition, DynamicMethod>>((Func<DynamicMethodDefinition, DynamicMethod>)delegate(DynamicMethodDefinition dmd) { _LastWrapperDMD = dmd; return (DynamicMethod)null; }); } [DetourToRD("HarmonySharedState", 1, null)] private static Assembly SharedStateAssembly(Func<Assembly> orig) { //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Expected O, but got Unknown //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_0085: Expected O, but got Unknown //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Expected O, but got Unknown //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Expected O, but got Unknown Assembly assembly = orig(); if ((object)assembly != null) { return assembly; } if ((object)_SharedStateASM != null) { return _SharedStateASM; } string text = (string)GetHarmonyType("HarmonySharedState").GetField("name", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null); ModuleDefinition val = ModuleDefinition.CreateModule("MonoMod.RuntimeDetour." + text, new ModuleParameters { Kind = (ModuleKind)0, ReflectionImporterProvider = MMReflectionImporter.Provider }); try { TypeDefinition val2 = new TypeDefinition("", text, (TypeAttributes)385) { BaseType = val.TypeSystem.Object }; val.Types.Add(val2); val2.Fields.Add(new FieldDefinition("state", (FieldAttributes)22, val.ImportReference(typeof(Dictionary<MethodBase, byte[]>)))); val2.Fields.Add(new FieldDefinition("version", (FieldAttributes)22, val.ImportReference(typeof(int)))); return _SharedStateASM = ReflectionHelper.Load(val); } finally { ((IDisposable)val)?.Dispose(); } } private static Assembly _FindHarmony() { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in assemblies) { if (assembly.GetName().Name == "0Harmony" || assembly.GetName().Name == "Harmony" || (object)assembly.GetType("Harmony.HarmonyInstance") != null || (object)assembly.GetType("HarmonyLib.Harmony") != null) { return assembly; } } object obj = System.Type.GetType("Harmony.HarmonyInstance", throwOnError: false, ignoreCase: false)?.Assembly; if (obj == null) { System.Type? type = System.Type.GetType("HarmonyLib.Harmony", throwOnError: false, ignoreCase: false); if ((object)type == null) { return null; } obj = type.Assembly; } return (Assembly)obj; } } public struct HookConfig { public bool ManualApply; public int Priority; public string ID; public IEnumerable<string> Before; public IEnumerable<string> After; } public class Hook : IDetour, IDisposable { public static Func<Hook, MethodBase, MethodBase, object, bool> OnDetour; public static Func<Hook, bool> OnUndo; public static Func<Hook, MethodBase, MethodBase> OnGenerateTrampoline; public readonly MethodBase Method; public readonly MethodBase Target; public readonly MethodBase TargetReal; public readonly object DelegateTarget; private Detour _Detour; private readonly Type _OrigDelegateType; private readonly MethodInfo _OrigDelegateInvoke; private int? _RefTarget; private int? _RefTrampoline; private int? _RefTrampolineTmp; public bool IsValid => _Detour.IsValid; public bool IsApplied => _Detour.IsApplied; public Detour Detour => _Detour; public Hook(MethodBase from, MethodInfo to, object target, ref HookConfig config) { //IL_0251: Unknown result type (might be due to invalid IL or missing references) //IL_0256: Unknown result type (might be due to invalid IL or missing references) //IL_0259: Expected O, but got Unknown //IL_025b: Expected O, but got Unknown //IL_0298: Unknown result type (might be due to invalid IL or missing references) //IL_02b3: Unknown result type (might be due to invalid IL or missing references) //IL_02c5: Unknown result type (might be due to invalid IL or missing references) //IL_036f: Unknown result type (might be due to invalid IL or missing references) //IL_0374: Unknown result type (might be due to invalid IL or missing references) //IL_0377: Expected O, but got Unknown //IL_0379: Expected O, but got Unknown //IL_0397: Unknown result type (might be due to invalid IL or missing references) //IL_03cd: Unknown result type (might be due to invalid IL or missing references) //IL_03e8: Unknown result type (might be due to invalid IL or missing references) //IL_03f6: Unknown result type (might be due to invalid IL or missing references) from = from.GetIdentifiable(); Method = from; Target = to; DelegateTarget = target; Type type = (from as MethodInfo)?.ReturnType ?? typeof(void); if ((object)to.ReturnType != type && !Extensions.IsCompatible(to.ReturnType, type)) { throw new InvalidOperationException($"Return type of hook for {from} doesn't match, must be {((from as MethodInfo)?.ReturnType ?? typeof(void)).FullName}"); } if (target == null && !to.IsStatic) { throw new InvalidOperationException($"Hook for method {from} must be static, or you must pass a target instance."); } ParameterInfo[] parameters = Target.GetParameters(); ParameterInfo[] parameters2 = Method.GetParameters(); Type[] array; if (!Method.IsStatic) { array = new Type[parameters2.Length + 1]; array[0] = Extensions.GetThisParamType(Method); for (int i = 0; i < parameters2.Length; i++) { array[i + 1] = parameters2[i].ParameterType; } } else { array = new Type[parameters2.Length]; for (int j = 0; j < parameters2.Length; j++) { array[j] = parameters2[j].ParameterType; } } Type type2 = null; if (parameters.Length == array.Length + 1 && typeof(Delegate).IsAssignableFrom(parameters[0].ParameterType)) { type2 = (_OrigDelegateType = parameters[0].ParameterType); } else if (parameters.Length != array.Length) { throw new InvalidOperationException($"Parameter count of hook for {from} doesn't match, must be {array.Length}"); } for (int k = 0; k < array.Length; k++) { Type type3 = array[k]; Type parameterType = parameters[k + (((object)type2 != null) ? 1 : 0)].ParameterType; if (!Extensions.IsCompatible(type3, parameterType)) { throw new InvalidOperationException($"Parameter #{k} of hook for {from} doesn't match, must be {type3.FullName} or related"); } } MethodInfo methodInfo = (_OrigDelegateInvoke = type2?.GetMethod("Invoke")); DynamicMethodDefinition val = new DynamicMethodDefinition($"Hook<{Extensions.GetID(Method, (string)null, (string)null, true, false, true)}>?{GetHashCode()}", (Method as MethodInfo)?.ReturnType ?? typeof(void), array); DynamicMethodDefinition val2 = val; DynamicMethodDefinition val3 = val; try { ILProcessor iLProcessor = val2.GetILProcessor(); if (target != null) { _RefTarget = DynamicMethodHelper.EmitReference<object>(iLProcessor, target); } if ((object)type2 != null) { _RefTrampoline = DynamicMethodHelper.EmitReference<Delegate>(iLProcessor, (Delegate)null); } for (int l = 0; l < array.Length; l++) { iLProcessor.Emit(OpCodes.Ldarg, l); } Extensions.Emit(iLProcessor, OpCodes.Call, Target); iLProcessor.Emit(OpCodes.Ret); TargetReal = val2.Generate().Pin(); } finally { ((IDisposable)val3)?.Dispose(); } if ((object)type2 != null) { ParameterInfo[] parameters3 = methodInfo.GetParameters(); Type[] array2 = new Type[parameters3.Length]; for (int m = 0; m < parameters3.Length; m++) { array2[m] = parameters3[m].ParameterType; } DynamicMethodDefinition val4 = new DynamicMethodDefinition($"Chain:TMP<{Extensions.GetID(Method, (string)null, (string)null, true, false, true)}>?{GetHashCode()}", methodInfo?.ReturnType ?? typeof(void), array2); val2 = val4; val3 = val4; try { ILProcessor iLProcessor = val2.GetILProcessor(); _RefTrampolineTmp = DynamicMethodHelper.EmitReference<Delegate>(iLProcessor, (Delegate)null); iLProcessor.Emit(OpCodes.Brfalse, iLProcessor.Body.Instructions[0]); DynamicMethodHelper.EmitGetReference<Delegate>(iLProcessor, _RefTrampolineTmp.Value); for (int n = 0; n < array.Length; n++) { iLProcessor.Emit(OpCodes.Ldarg, n); } Extensions.Emit(iLProcessor, OpCodes.Callvirt, (MethodBase)methodInfo); iLProcessor.Emit(OpCodes.Ret); DynamicMethodHelper.SetReference(_RefTrampoline.Value, (object)Extensions.CreateDelegate((MethodBase)val2.Generate(), type2)); } finally { ((IDisposable)val3)?.Dispose(); } } _Detour = new Detour(Method, TargetReal, new DetourConfig { ManualApply = true, Priority = config.Priority, ID = config.ID, Before = config.Before, After = config.After }); _UpdateOrig(null); if (!config.ManualApply) { Apply(); } } public Hook(MethodBase from, MethodInfo to, object target, HookConfig config) : this(from, to, target, ref config) { } public Hook(MethodBase from, MethodInfo to, object target) : this(from, to, target, DetourContext.Current?.HookConfig ?? default(HookConfig)) { } public Hook(MethodBase from, MethodInfo to, ref HookConfig config) : this(from, to, null, ref config) { } public Hook(MethodBase from, MethodInfo to, HookConfig config) : this(from, to, null, ref config) { } public Hook(MethodBase from, MethodInfo to) : this(from, to, null) { } public Hook(MethodBase method, IntPtr to, ref HookConfig config) : this(method, DetourHelper.GenerateNativeProxy(to, method), null, ref config) { } public Hook(MethodBase method, IntPtr to, HookConfig config) : this(method, DetourHelper.GenerateNativeProxy(to, method), null, ref config) { } public Hook(MethodBase method, IntPtr to) : this(method, DetourHelper.GenerateNativeProxy(to, method), null) { } public Hook(MethodBase method, Delegate to, ref HookConfig config) : this(method, to.Method, to.Target, ref config) { } public Hook(MethodBase method, Delegate to, HookConfig config) : this(method, to.Method, to.Target, ref config) { } public Hook(MethodBase method, Delegate to) : this(method, to.Method, to.Target) { } public Hook(Delegate from, IntPtr to, ref HookConfig config) : this(from.Method, to, ref config) { } public Hook(Delegate from, IntPtr to, HookConfig config) : this(from.Method, to, ref config) { } public Hook(Delegate from, IntPtr to) : this(from.Method, to) { } public Hook(Delegate from, Delegate to, ref HookConfig config) : this(from.Method, to, ref config) { } public Hook(Delegate from, Delegate to, HookConfig config) : this(from.Method, to, ref config) { } public Hook(Delegate from, Delegate to) : this(from.Method, to) { } public Hook(Expression from, IntPtr to, ref HookConfig config) : this(((MethodCallExpression)from).Method, to, ref config) { } public Hook(Expression from, IntPtr to, HookConfig config) : this(((MethodCallExpression)from).Method, to, ref config) { } public Hook(Expression from, IntPtr to) : this(((MethodCallExpression)from).Method, to) { } public Hook(Expression from, Delegate to, ref HookConfig config) : this(((MethodCallExpression)from).Method, to, ref config) { } public Hook(Expression from, Delegate to, HookConfig config) : this(((MethodCallExpression)from).Method, to, ref config) { } public Hook(Expression from, Delegate to) : this(((MethodCallExpression)from).Method, to) { } public Hook(Expression<Action> from, IntPtr to, ref HookConfig config) : this(from.Body, to, ref config) { } public Hook(Expression<Action> from, IntPtr to, HookConfig config) : this(from.Body, to, ref config) { } public Hook(Expression<Action> from, IntPtr to) : this(from.Body, to) { } public Hook(Expression<Action> from, Delegate to, ref HookConfig config) : this(from.Body, to, ref config) { } public Hook(Expression<Action> from, Delegate to, HookConfig config) : this(from.Body, to, ref config) { } public Hook(Expression<Action> from, Delegate to) : this(from.Body, to) { } public void Apply() { if (!IsValid) { throw new ObjectDisposedException("Hook"); } if (!IsApplied) { Func<Hook, MethodBase, MethodBase, object, bool> onDetour = OnDetour; if (onDetour != null && !Extensions.InvokeWhileTrue((MulticastDelegate)onDetour, new object[4] { this, Method, Target, DelegateTarget })) { return; } } _Detour.Apply(); } public void Undo() { if (!IsValid) { throw new ObjectDisposedException("Hook"); } if (IsApplied) { Func<Hook, bool> onUndo = OnUndo; if (onUndo != null && !Extensions.InvokeWhileTrue((MulticastDelegate)onUndo, new object[1] { this })) { return; } } _Detour.Undo(); if (!IsValid) { _Free(); } } public void Free() { if (IsValid) { _Detour.Free(); _Free(); } } public void Dispose() { if (IsValid) { Undo(); Free(); } } private void _Free() { if (_RefTarget.HasValue) { DynamicMethodHelper.FreeReference(_RefTarget.Value); } if (_RefTrampoline.HasValue) { DynamicMethodHelper.FreeReference(_RefTrampoline.Value); } if (_RefTrampolineTmp.HasValue) { DynamicMethodHelper.FreeReference(_RefTrampolineTmp.Value); } TargetReal.Unpin(); } public MethodBase GenerateTrampoline(MethodBase signature = null) { Func<Hook, MethodBase, MethodBase> onGenerateTrampoline = OnGenerateTrampoline; MethodBase methodBase = ((onGenerateTrampoline != null) ? Extensions.InvokeWhileNull<MethodBase>((MulticastDelegate)onGenerateTrampoline, new object[2] { this, signature }) : null); if ((object)methodBase != null) { return methodBase; } return _Detour.GenerateTrampoline(signature); } public T GenerateTrampoline<T>() where T : Delegate { if (!typeof(Delegate).IsAssignableFrom(typeof(T))) { throw new InvalidOperationException($"Type {typeof(T)} not a delegate type."); } return Extensions.CreateDelegate(GenerateTrampoline(typeof(T).GetMethod("Invoke")), typeof(T)) as T; } internal void _UpdateOrig(MethodBase invoke) { if ((object)_OrigDelegateType != null) { Delegate obj = Extensions.CreateDelegate(invoke ?? GenerateTrampoline(_OrigDelegateInvoke), _OrigDelegateType); DynamicMethodHelper.SetReference(_RefTrampoline.Value, (object)obj); DynamicMethodHelper.SetReference(_RefTrampolineTmp.Value, (object)obj); } } } public class Hook<T> : Hook { public Hook(Expression<Action> from, T to, ref HookConfig config) : base(from.Body, to as Delegate, ref config) { } public Hook(Expression<Action> from, T to, HookConfig config) : base(from.Body, to as Delegate, ref config) { } public Hook(Expression<Action> from, T to) : base(from.Body, to as Delegate) { } public Hook(Expression<Func<T>> from, IntPtr to, ref HookConfig config) : base(from.Body, to, ref config) { } public Hook(Expression<Func<T>> from, IntPtr to, HookConfig config) : base(from.Body, to, ref config) { } public Hook(Expression<Func<T>> from, IntPtr to) : base(from.Body, to) { } public Hook(Expression<Func<T>> from, Delegate to, ref HookConfig config) : base(from.Body, to, ref config) { } public Hook(Expression<Func<T>> from, Delegate to, HookConfig config) : base(from.Body, to, ref config) { } public Hook(Expression<Func<T>> from, Delegate to) : base(from.Body, to) { } public Hook(T from, IntPtr to, ref HookConfig config) : base(from as Delegate, to, ref config) { } public Hook(T from, IntPtr to, HookConfig config) : base(from as Delegate, to, ref config) { } public Hook(T from, IntPtr to) : base(from as Delegate, to) { } public Hook(T from, T to, ref HookConfig config) : base(from as Delegate, to as Delegate, ref config) { } public Hook(T from, T to, HookConfig config) : base(from as Delegate, to as Delegate, ref config) { } public Hook(T from, T to) : base(from as Delegate, to as Delegate) { } } public class Hook<TFrom, TTo> : Hook { public Hook(Expression<Func<TFrom>> from, TTo to, ref HookConfig config) : base(from.Body, to as Delegate) { } public Hook(Expression<Func<TFrom>> from, TTo to, HookConfig config) : base(from.Body, to as Delegate) { } public Hook(Expression<Func<TFrom>> from, TTo to) : base(from.Body, to as Delegate) { } public Hook(TFrom from, TTo to, ref HookConfig config) : base(from as Delegate, to as Delegate) { } public Hook(TFrom from, TTo to, HookConfig config) : base(from as Delegate, to as Delegate) { } public Hook(TFrom from, TTo to) : base(from as Delegate, to as Delegate) { } } public interface IDetour : IDisposable { bool IsValid { get; } bool IsApplied { get; } void Apply(); void Undo(); void Free(); MethodBase GenerateTrampoline(MethodBase signature = null); T GenerateTrampoline<T>() where T : Delegate; } public interface ISortableDetour : IDetour, IDisposable { uint GlobalIndex { get; } int Priority { get; set; } string ID { get; set; } IEnumerable<string> Before { get; set; } IEnumerable<string> After { get; set; } } public struct ILHookConfig { public bool ManualApply; public int Priority; public string ID; public IEnumerable<string> Before; public IEnumerable<string> After; } public class ILHook : ISortableDetour, IDetour, IDisposable { private class Context { public List<ILHook> Chain = new List<ILHook>(); public HashSet<ILContext> Active = new HashSet<ILContext>(); public MethodBase Method; public Detour Detour; public Context(MethodBase method) { Method = method; } public void Add(ILHook hook) { List<ILHook> chain = Chain; lock (chain) { chain.Add(hook); } } public void Remove(ILHook hook) { List<ILHook> chain = Chain; lock (chain) { chain.Remove(hook); if (chain.Count == 0) { Refresh(); lock (_Map) { _Map.Remove(Method); return; } } } } public void Refresh() { //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Expected O, but got Unknown List<ILHook> chain = Chain; lock (chain) { foreach (ILContext item in Active) { item.Dispose(); } Active.Clear(); Detour?.Dispose(); Detour = null; if (chain.Count == 0) { return; } bool flag = false; foreach (ILHook item2 in chain) { if (item2.IsApplied) { flag = true; break; } } if (!flag) { return; } DetourSorter<ILHook>.Sort(chain); DynamicMethodDefinition val = new DynamicMethodDefinition(Method); MethodBase to; try { MethodDefinition definition = val.Definition; foreach (ILHook item3 in chain) { if (item3.IsApplied) { InvokeManipulator(definition, item3.Manipulator); } } to = val.Generate(); } finally { ((IDisposable)val)?.Dispose(); } Detour = new Detour(Method, to, ref ILDetourConfig); } } private void InvokeManipulator(MethodDefinition def, Manipulator cb) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown ILContext val = new ILContext(def); val.ReferenceBag = (IILReferenceBag)(object)RuntimeILReferenceBag.Instance; val.Invoke(cb); if (val.IsReadOnly) { val.Dispose(); return; } val.MakeReadOnly(); Active.Add(val); } } public static Func<ILHook, MethodBase, Manipulator, bool> OnDetour; public static Func<ILHook, bool> OnUndo; private static DetourConfig ILDetourConfig = new DetourConfig { Priority = -268435456, Before = new string[1] { "*" } }; private static Dictionary<MethodBase, Context> _Map = new Dictionary<MethodBase, Context>(); private static uint _GlobalIndexNext = 0u; private readonly uint _GlobalIndex; private int _Priority; private string _ID; private List<string> _Before = new List<string>(); private ReadOnlyCollection<string> _BeforeRO; private List<string> _After = new List<string>(); private ReadOnlyCollection<string> _AfterRO; public readonly MethodBase Method; public readonly Manipulator Manipulator; private Context _Ctx { get { if (!_Map.TryGetValue(Method, out var value)) { return null; } return value; } } public bool IsValid => Index != -1; public bool IsApplied { get; private set; } public int Index => _Ctx?.Chain.IndexOf(this) ?? (-1); public int MaxIndex => _Ctx?.Chain.Count ?? (-1); public uint GlobalIndex => _GlobalIndex; public int Priority { get { return _Priority; } set { if (_Priority != value) { _Priority = value; _Ctx.Refresh(); } } } public string ID { get { return _ID; } set { if (string.IsNullOrEmpty(value)) { MethodInfo method = ((Delegate)(object)Manipulator).Method; value = (((object)method != null) ? Extensions.GetID((MethodBase)method, (string)null, (string)null, true, false, true) : null) ?? GetHashCode().ToString(CultureInfo.InvariantCulture); } if (!(_ID == value)) { _ID = value; _Ctx.Refresh(); } } } public IEnumerable<string> Before { get { return _BeforeRO ?? (_BeforeRO = _Before.AsReadOnly()); } set { lock (_Before) { _Before.Clear(); if (value != null) { foreach (string item in value) { _Before.Add(item); } } _Ctx.Refresh(); } } } public IEnumerable<string> After { get { return _AfterRO ?? (_AfterRO = _After.AsReadOnly()); } set { lock (_After) { _After.Clear(); if (value != null) { foreach (string item in value) { _After.Add(item); } } _Ctx.Refresh(); } } } public ILHook(MethodBase from, Manipulator manipulator, ref ILHookConfig config) { from = from.GetIdentifiable(); Method = from.Pin(); Manipulator = manipulator; _GlobalIndex = _GlobalIndexNext++; _Priority = config.Priority; _ID = config.ID; if (config.Before != null) { foreach (string item in config.Before) { _Before.Add(item); } } if (config.After != null) { foreach (string item2 in config.After) { _After.Add(item2); } } Context value; lock (_Map) { if (!_Map.TryGetValue(Method, out value)) { value = (_Map[Method] = new Context(Method)); } } lock (value) { value.Add(this); } if (!config.ManualApply) { Apply(); } } public ILHook(MethodBase from, Manipulator manipulator, ILHookConfig config) : this(from, manipulator, ref config) { } public ILHook(MethodBase from, Manipulator manipulator) : this(from, manipulator, DetourContext.Current?.ILHookConfig ?? default(ILHookConfig)) { } public void Apply() { if (!IsValid) { throw new ObjectDisposedException("ILHook"); } if (!IsApplied) { Func<ILHook, MethodBase, Manipulator, bool> onDetour = OnDetour; if (onDetour == null || Extensions.InvokeWhileTrue((MulticastDelegate)onDetour, new object[3] { this, Method, Manipulator })) { IsApplied = true; _Ctx.Refresh(); } } } public void Undo() { if (!IsValid) { throw new ObjectDisposedException("ILHook"); } if (IsApplied) { Func<ILHook, bool> onUndo = OnUndo; if (onUndo == null || Extensions.InvokeWhileTrue((MulticastDelegate)onUndo, new object[1] { this })) { IsApplied = false; _Ctx.Refresh(); } } } public void Free() { if (IsValid) { Undo(); _Ctx.Remove(this); Method.Unpin(); } } public void Dispose() { if (IsValid) { Undo(); Free(); } } public MethodBase GenerateTrampoline(MethodBase signature = null) { throw new NotSupportedException(); } public T GenerateTrampoline<T>() where T : Delegate { throw new NotSupportedException(); } } public struct NativeDetourConfig { public bool ManualApply; public bool SkipILCopy; } public class NativeDetour : IDetour, IDisposable { public static Func<NativeDetour, MethodBase, IntPtr, IntPtr, bool> OnDetour; public static Func<NativeDetour, bool> OnUndo; public static Func<NativeDetour, MethodBase, MethodBase> OnGenerateTrampoline; private NativeDetourData _Data; public readonly MethodBase Method; private readonly MethodInfo _BackupMethod; private readonly IntPtr _BackupNative; private HashSet<MethodBase> _Pinned = new HashSet<MethodBase>(); public bool IsValid { get; private set; } public bool IsApplied { get; private set; } public NativeDetourData Data => _Data; public NativeDetour(MethodBase method, IntPtr from, IntPtr to, ref NativeDetourConfig config) { if (from == to) { throw new InvalidOperationException($"Cannot detour from a location to itself! (from: {from:X16} to: {to:X16} method: {method})"); } method = method?.GetIdentifiable(); Method = method; Func<NativeDetour, MethodBase, IntPtr, IntPtr, bool> onDetour = OnDetour; if (onDetour == null || Extensions.InvokeWhileTrue((MulticastDelegate)onDetour, new object[4] { this, method, from, to })) { IsValid = true; _Data = DetourHelper.Native.Create(from, to); if (!config.SkipILCopy) { method?.TryCreateILCopy(out _BackupMethod); } _BackupNative = DetourHelper.Native.MemAlloc(_Data.Size); if (!config.ManualApply) { Apply(); } } } public NativeDetour(MethodBase method, IntPtr from, IntPtr to, NativeDetourConfig config) : this(method, from, to, ref config) { } public NativeDetour(MethodBase method, IntPtr from, IntPtr to) : this(method, from, to, default(NativeDetourConfig)) { } public NativeDetour(IntPtr from, IntPtr to, ref NativeDetourConfig config) : this(null, from, to, ref config) { } public NativeDetour(IntPtr from, IntPtr to, NativeDetourConfig config) : this(null, from, to, ref config) { } public NativeDetour(IntPtr from, IntPtr to) : this(null, from, to) { } public NativeDetour(MethodBase from, IntPtr to, ref NativeDetourConfig config) : this(from, from.Pin().GetNativeStart(), to, ref config) { _Pinned.Add(from); } public NativeDetour(MethodBase from, IntPtr to, NativeDetourConfig config) : this(from, from.Pin().GetNativeStart(), to, ref config) { _Pinned.Add(from); } public NativeDetour(MethodBase from, IntPtr to) : this(from, from.Pin().GetNativeStart(), to) { _Pinned.Add(from); } public NativeDetour(IntPtr from, MethodBase to, ref NativeDetourConfig config) : this(from, to.Pin().GetNativeStart(), ref config) { _Pinned.Add(to); } public NativeDetour(IntPtr from, MethodBase to, NativeDetourConfig config) : this(from, to.Pin().GetNativeStart(), ref config) { _Pinned.Add(to); } public NativeDetour(IntPtr from, MethodBase to) : this(from, to.Pin().GetNativeStart()) { _Pinned.Add(to); } public NativeDetour(MethodBase from, MethodBase to, ref NativeDetourConfig config) : this(from.Pin().GetNativeStart(), DetourHelper.Runtime.GetDetourTarget(from, to), ref config) { _Pinned.Add(from); } public NativeDetour(MethodBase from, MethodBase to, NativeDetourConfig config) : this(from.Pin().GetNativeStart(), DetourHelper.Runtime.GetDetourTarget(from, to), ref config) { _Pinned.Add(from); } public NativeDetour(MethodBase from, MethodBase to) : this(from.Pin().GetNativeStart(), DetourHelper.Runtime.GetDetourTarget(from, to)) { _Pinned.Add(from); } public NativeDetour(Delegate from, IntPtr to, ref NativeDetourConfig config) : this(from.Method, to, ref config) { } public NativeDetour(Delegate from, IntPtr to, NativeDetourConfig config) : this(from.Method, to, ref config) { } public NativeDetour(Delegate from, IntPtr to) : this(from.Method, to) { } public NativeDetour(IntPtr from, Delegate to, ref NativeDetourConfig config) : this(from, to.Method, ref config) { } public NativeDetour(IntPtr from, Delegate to, NativeDetourConfig config) : this(from, to.Method, ref config) { } public NativeDetour(IntPtr from, Delegate to) : this(from, to.Method) { } public NativeDetour(Delegate from, Delegate to, ref NativeDetourConfig config) : this(from.Method, to.Method, ref config) { } public NativeDetour(Delegate from, Delegate to, NativeDetourConfig config) : this(from.Method, to.Method, ref config) { } public NativeDetour(Delegate from, Delegate to) : this(from.Method, to.Method) { } public void Apply() { if (!IsValid) { throw new ObjectDisposedException("NativeDetour"); } if (!IsApplied) { IsApplied = true; DetourHelper.Native.Copy(_Data.Method, _BackupNative, _Data.Type); DetourHelper.Native.MakeWritable(_Data); DetourHelper.Native.Apply(_Data); DetourHelper.Native.MakeExecutable(_Data); DetourHelper.Native.FlushICache(_Data); } } public void Undo() { if (!IsValid) { throw new ObjectDisposedException("NativeDetour"); } Func<NativeDetour, bool> onUndo = OnUndo; if ((onUndo == null || Extensions.InvokeWhileTrue((MulticastDelegate)onUndo, new object[1] { this })) && IsApplied) { IsApplied = false; DetourHelper.Native.MakeWritable(_Data); DetourHelper.Native.Copy(_BackupNative, _Data.Method, _Data.Type); DetourHelper.Native.MakeExecutable(_Data); DetourHelper.Native.FlushICache(_Data); } } public void ChangeSource(IntPtr newSource) { if (!IsValid) { throw new ObjectDisposedException("NativeDetour"); } NativeDetourData data = _Data; _Data = DetourHelper.Native.Create(newSource, _Data.Target); IsApplied = false; Apply(); DetourHelper.Native.Free(data); } public void ChangeTarget(IntPtr newTarget) { if (!IsValid) { throw new ObjectDisposedException("NativeDetour"); } NativeDetourData data = _Data; _Data = DetourHelper.Native.Create(_Data.Method, newTarget); IsApplied = false; Apply(); DetourHelper.Native.Free(data); } public void Free() { if (!IsValid) { return; } IsValid = false; DetourHelper.Native.MemFree(_BackupNative); DetourHelper.Native.Free(_Data); if (IsApplied) { return; } foreach (MethodBase item in _Pinned) { item.Unpin(); } _Pinned.Clear(); } public void Dispose() { if (IsValid) { Undo(); Free(); } } public MethodBase GenerateTrampoline(MethodBase signature = null) { //IL_0119: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Expected O, but got Unknown //IL_012a: Unknown result type (might be due to invalid IL or missing references) //IL_0131: Expected O, but got Unknown //IL_018b: Unknown result type (might be due to invalid IL or missing references) //IL_0190: Unknown result type (might be due to invalid IL or missing references) //IL_0193: Expected O, but got Unknown //IL_0198: Expected O, but got Unknown //IL_01b2: Unknown result type (might be due to invalid IL or missing references) //IL_01d6: Unknown result type (might be due to invalid IL or missing references) //IL_01f2: Unknown result type (might be due to invalid IL or missing references) //IL_0238: Unknown result type (might be due to invalid IL or missing references) //IL_022a: Unknown result type (might be due to invalid IL or missing references) //IL_02e9: Unknown result type (might be due to invalid IL or missing references) //IL_02b5: Unknown result type (might be due to invalid IL or missing references) Func<NativeDetour, MethodBase, MethodBase> onGenerateTrampoline = OnGenerateTrampoline; MethodBase methodBase = ((onGenerateTrampoline != null) ? Extensions.InvokeWhileNull<MethodBase>((MulticastDelegate)onGenerateTrampoline, new object[2] { this, signature }) : null); if ((object)methodBase != null) { return methodBase; } if (!IsValid) { throw new ObjectDisposedException("NativeDetour"); } if ((object)_BackupMethod != null) { return _BackupMethod; } if ((object)signature == null) { throw new ArgumentNullException("A signature must be given if the NativeDetour doesn't hold a reference to a managed method."); } MethodBase methodBase2 = Method; if ((object)methodBase2 == null) { methodBase2 = DetourHelper.GenerateNativeProxy(_Data.Method, signature); } Type type = (signature as MethodInfo)?.ReturnType ?? typeof(void); ParameterInfo[] parameters = signature.GetParameters(); Type[] array = new Type[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { array[i] = parameters[i].ParameterType; } MethodBase method = Method; DynamicMethodDefinition val = new DynamicMethodDefinition(string.Format("Trampoline:Native<{0}>?{1}", (((object)method != null) ? Extensions.GetID(method, (string)null, (string)null, true, false, true) : null) ?? ((long)_Data.Method).ToString("X16", CultureInfo.InvariantCulture), GetHashCode()), type, array); try { ILProcessor iLProcessor = val.GetILProcessor(); ExceptionHandler val2 = new ExceptionHandler((ExceptionHandlerType)2); iLProcessor.Body.ExceptionHandlers.Add(val2); iLProcessor.EmitDetourCopy(_BackupNative, _Data.Method, _Data.Type); VariableDefinition val3 = null; if ((object)type != typeof(void)) { Collection<VariableDefinition> variables = iLProcessor.Body.Variables; VariableDefinition val4 = new VariableDefinition(Extensions.Import(iLProcessor, type)); val3 = val4; variables.Add(val4); } int count = iLProcessor.Body.Instructions.Count; for (int j = 0; j < array.Length; j++) { iLProcessor.Emit(OpCodes.Ldarg, j); } if (methodBase2 is MethodInfo) { Extensions.Emit(iLProcessor, OpCodes.Call, (MethodBase)(MethodInfo)methodBase2); } else { if (!(methodBase2 is ConstructorInfo)) { throw new NotSupportedException("Method type " + methodBase2.GetType().FullName + " not supported."); } Extensions.Emit(iLProcessor, OpCodes.Call, (MethodBase)(ConstructorInfo)methodBase2); } if (val3 != null) { iLProcessor.Emit(OpCodes.Stloc, val3); } Extensions.Emit(iLProcessor, OpCodes.Leave, (object)null); Instruction obj = iLProcessor.Body.Instructions[iLProcessor.Body.Instructions.Count - 1]; int count2 = iLProcessor.Body.Instructions.Count; _ = iLProcessor.Body.Instructions.Count; iLProcessor.EmitDetourApply(_Data); int count3 = iLProcessor.Body.Instructions.Count; Instruction val5 = null; if (val3 != null) { iLProcessor.Emit(OpCodes.Ldloc, val3); val5 = iLProcessor.Body.Instructions[iLProcessor.Body.Instructions.Count - 1]; } iLProcessor.Emit(OpCodes.Ret); val5 = val5 ?? iLProcessor.Body.Instructions[iLProcessor.Body.Instructions.Count - 1]; obj.Operand = val5; val2.TryStart = iLProcessor.Body.Instructions[count]; val2.TryEnd = iLProcessor.Body.Instructions[count2]; val2.HandlerStart = iLProcessor.Body.Instructions[count2]; val2.HandlerEnd = iLProcessor.Body.Instructions[count3]; return val.Generate(); } finally { ((IDisposable)val)?.Dispose(); } } public T GenerateTrampoline<T>() where T : Delegate { if (!typeof(Delegate).IsAssignableFrom(typeof(T))) { throw new InvalidOperationException($"Type {typeof(T)} not a delegate type."); } return Extensions.CreateDelegate(GenerateTrampoline(typeof(T).GetMethod("Invoke")), typeof(T)) as T; } } internal static class DetourSorter<T> where T : ISortableDetour { private sealed class Group { public readonly string StepName; public List<T> Items = new List<T>(); public List<Group> Children = new List<Group>(); public List<Group> NonMatching = new List<Group>(); public Group(string stepName) { StepName = stepName; } public Group(string stepName, List<T> items) : this(stepName) { Items.AddRange(items); } public void Step(Step step) { if (Children.Count != 0) { foreach (Group child in Children) { child.Step(step); } return; } if (Items.Count <= 1) { return; } if ((Items.Count == 2 && !((!step.IsFlat) ?? false)) || step.IsFlat == true) { Items.Sort(step); return; } string name = step.GetType().Name; Group obj = new Group(name, new List<T> { Items[0] }); Children.Add(obj); for (int i = 1; i < Items.Count; i++) { T val = Items[i]; if (step.Any(obj.Items, val)) { Group obj2 = obj; obj = null; if (Children.Count > 1) { foreach (Group child2 in Children) { if (child2 != obj2 && !step.Any(child2.Items, val) && !step.Any(child2.NonMatching, val)) { obj = child2; break; } } } if (obj == null) { obj = new Group(name); Children.Add(obj); obj.NonMatching.Add(obj2); obj2.NonMatching.Add(obj); } } obj.Items.Add(val); } if (Children.Count == 1) { Children.Clear(); } else { Children.Sort(step.ForGroup); } } public void Flatten() { if (Children.Count != 0) { Items.Clear(); Flatten(Items); } } public void Flatten(List<T> total) { if (Children.Count == 0) { total.AddRange(Items); return; } foreach (Group child in Children) { child.Flatten(total); } } } private abstract class Step : IComparer<T> { public abstract GroupComparer ForGroup { get; } public virtual bool? IsFlat => null; public abstract int Compare(T x, T y); public bool Any(List<T> xlist, T y) { foreach (T item in xlist) { if (Compare(item, y) != 0) { return true; } } return false; } public bool Any(List<Group> groups, T y) { foreach (Group group in groups) { if (Any(group.Items, y)) { return true; } } return false; } } private sealed class GroupComparer : IComparer<Group> { public Step Step; public GroupComparer(Step step) { Step = step; } public int Compare(Group xg, Group yg) { foreach (T item in xg.Items) { foreach (T item2 in yg.Items) { int result; if ((result = Step.Compare(item, item2)) != 0) { return result; } } } return 0; } } private sealed class BeforeAfterAll : Step { public static readonly BeforeAfterAll _ = new BeforeAfterAll(); public static readonly GroupComparer Group = new GroupComparer(_); public override GroupComparer ForGroup => Group; public override bool? IsFlat => false; public override int Compare(T a, T b) { if (a.Before.Contains("*") && !b.Before.Contains("*")) { return -1; } if (!a.Before.Contains("*") && b.Before.Contains("*")) { return 1; } if (a.After.Contains("*") && !b.After.Contains("*")) { return 1; } if (!a.After.Contains("*") && b.After.Contains("*")) { return -1; } return 0; } } private sealed class BeforeAfter : Step { public static readonly BeforeAfter _ = new BeforeAfter(); public static readonly GroupComparer Group = new GroupComparer(_); public override GroupComparer ForGroup => Group; public override int Compare(T a, T b) { if (a.Before.Contains(b.ID)) { return -1; } if (a.After.Contains(b.ID)) { return 1; } if (b.Before.Contains(a.ID)) { return 1; } if (b.After.Contains(a.ID)) { return -1; } return 0; } } private sealed class Priority : Step { public static readonly Priority _ = new Priority(); public static readonly GroupComparer Group = new GroupComparer(_); public override GroupComparer ForGroup => Group; public override int Compare(T a, T b) { int num = a.Priority - b.Priority; if (num != 0) { return num; } return 0; } } private sealed class GlobalIndex : Step { public static readonly GlobalIndex _ = new GlobalIndex(); public static readonly GroupComparer Group = new GroupComparer(_); public override GroupComparer ForGroup => Group; public override int Compare(T a, T b) { return a.GlobalIndex.CompareTo(b.GlobalIndex); } } public static void Sort(List<T> detours) { lock (detours) { if (detours.Count > 1) { detours.Sort(GlobalIndex._); Group obj = new Group("Init", detours); obj.Step(BeforeAfterAll._); obj.Step(BeforeAfter._); obj.Step(Priority._); obj.Step(GlobalIndex._); detours.Clear(); obj.Flatten(detours); } } } } public static class DetourHelper { private static readonly object _RuntimeLock = new object(); private static bool _RuntimeInit = false; private static IDetourRuntimePlatform _Runtime; private static readonly object _NativeLock = new object(); private static bool _NativeInit = false; private static IDetourNativePlatform _Native; private static readonly FieldInfo _f_Native = typeof(DetourHelper).GetField("_Native", BindingFlags.Static | BindingFlags.NonPublic); private static readonly MethodInfo _m_ToNativeDetourData = typeof(DetourHelper).GetMethod("ToNativeDetourData", BindingFlags.Static | BindingFlags.NonPublic); private static readonly MethodInfo _m_Copy = typeof(IDetourNativePlatform).GetMethod("Copy"); private static readonly MethodInfo _m_Apply = typeof(IDetourNativePlatform).GetMethod("Apply"); private static readonly ConstructorInfo _ctor_Exception = typeof(Exception).GetConstructor(new Type[1] { typeof(string) }); public static IDetourRuntimePlatform Runtime { get { if (_Runtime != null) { return _Runtime; } lock (_RuntimeLock) { if (_Runtime != null) { return _Runtime; } if (_RuntimeInit) { return null; } _RuntimeInit = true; if (ReflectionHelper.IsMono) { _Runtime = new DetourRuntimeMonoPlatform(); } else if (ReflectionHelper.IsCore) { _Runtime = DetourRuntimeNETCorePlatform.Create(); } else { _Runtime = new DetourRuntimeNETPlatform(); } return _Runtime; } } set { _Runtime = value; } } public static IDetourNativePlatform Native { get { if (_Native != null) { return _Native; } lock (_NativeLock) { if (_Native != null) { return _Native; } if (_NativeInit) { return null; } _NativeInit = true; IDetourNativePlatform detourNativePlatform = ((!PlatformHelper.Is((Platform)65536)) ? ((IDetourNativePlatform)new DetourNativeX86Platform()) : ((IDetourNativePlatform)new DetourNativeARMPlatform())); if (PlatformHelper.Is((Platform)37)) { return _Native = new DetourNativeWindowsPlatform(detourNativePlatform); } if (ReflectionHelper.IsMono) { try { return _Native = new DetourNativeMonoPlatform(detourNativePlatform, "libmonosgen-2.0." + PlatformHelper.LibrarySuffix); } catch { } } string environmentVariable = Environment.GetEnvironmentVariable("MONOMOD_RUNTIMEDETOUR_MONOPOSIXHELPER"); if ((ReflectionHelper.IsMono && environmentVariable != "0") || environmentVariable == "1") { try { return _Native = new DetourNativeMonoPosixPlatform(detourNativePlatform); } catch { } } try { return _Native = new DetourNativeLibcPlatform(detourNativePlatform); } catch { } return detourNativePlatform; } } set { _Native = value; } } public static void MakeWritable(this IDetourNativePlatform plat, NativeDetourData detour) { plat.MakeWritable(detour.Method, detour.Size); } public static void MakeExecutable(this IDetourNativePlatform plat, NativeDetourData detour) { plat.MakeExecutable(detour.Method, detour.Size); } public static void FlushICache(this IDetourNativePlatform plat, NativeDetourData detour) { plat.FlushICache(detour.Method, detour.Size); } public unsafe static void Write(this IntPtr to, ref int offs, byte value) { *(byte*)((long)to + offs) = value; offs++; } public unsafe static void Write(this IntPtr to, ref int offs, ushort value) { *(ushort*)((long)to + offs) = value; offs += 2; } public unsafe static void Write(this IntPtr to, ref int offs, uint value) { *(uint*)((long)to + offs) = value; offs += 4; } public unsafe static void Write(this IntPtr to, ref int offs, ulong value) { *(ulong*)((long)to + offs) = value; offs += 8; } public static MethodBase GetIdentifiable(this MethodBase method) { return Runtime.GetIdentifiable(method); } public static IntPtr GetNativeStart(this MethodBase method) { return Runtime.GetNativeStart(method); } public static IntPtr GetNativeStart(this Delegate method) { return method.Method.GetNativeStart(); } public static IntPtr GetNativeStart(this Expression method) { return ((MethodCallExpression)method).Method.GetNativeStart(); } public static MethodInfo CreateILCopy(this MethodBase method) { return Runtime.CreateCopy(method); } public static bool TryCreateILCopy(this MethodBase method, out MethodInfo dm) { return Runtime.TryCreateCopy(method, out dm); } public static T Pin<T>(this T method) where T : MethodBase { Runtime.Pin(method); return method; } public static T Unpin<T>(this T method) where T : MethodBase { Runtime.Unpin(method); return method; } public static MethodInfo GenerateNativeProxy(IntPtr target, MethodBase signature) { //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Expected O, but got Unknown Type type = (signature as MethodInfo)?.ReturnType ?? typeof(void); ParameterInfo[] parameters = signature.GetParameters(); Type[] array = new Type[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { array[i] = parameters[i].ParameterType; } DynamicMethodDefinition val = new DynamicMethodDefinition("Native<" + ((long)target).ToString("X16", CultureInfo.InvariantCulture) + ">", type, array); MethodInfo methodInfo; try { methodInfo = val.StubCriticalDetour().Generate().Pin(); } finally { ((IDisposable)val)?.Dispose(); } NativeDetourData detour = Native.Create(methodInfo.GetNativeStart(), target); Native.MakeWritable(detour); Native.Apply(detour); Native.MakeExecutable(detour); Native.FlushICache(detour); Native.Free(detour); return methodInfo; } private static NativeDetourData ToNativeDetourData(IntPtr method, IntPtr target, uint size, byte type, IntPtr extra) { return new NativeDetourData { Method = method, Target = target, Size = size, Type = type, Extra = extra }; } public static DynamicMethodDefinition StubCriticalDetour(this DynamicMethodDefinition dm) { //IL_001d: 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_0051: 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) ILProcessor iLProcessor = dm.GetILProcessor(); ModuleDefinition module = ((MemberReference)iLProcessor.Body.Method).Module; for (int i = 0; i < 32; i++) { iLProcessor.Emit(OpCodes.Nop); } iLProcessor.Emit(OpCodes.Ldstr, ((MemberReference)dm.Definition).Name + " should've been detoured!"); iLProcessor.Emit(OpCodes.Newobj, module.ImportReference((MethodBase)_ctor_Exception)); iLProcessor.Emit(OpCodes.Throw); return dm; } public static void EmitDetourCopy(this ILProcessor il, IntPtr src, IntPtr dst, byte type) { //IL_0012: 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_0039: 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_0055: 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_006c: 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) ModuleDefinition module = ((MemberReference)il.Body.Method).Module; il.Emit(OpCodes.Ldsfld, module.ImportReference(_f_Native)); il.Emit(OpCodes.Ldc_I8, (long)src); il.Emit(OpCodes.Conv_I); il.Emit(OpCodes.Ldc_I8, (long)dst); il.Emit(OpCodes.Conv_I); il.Emit(OpCodes.Ldc_I4, (int)type); il.Emit(OpCodes.Conv_U1); il.Emit(OpCodes.Callvirt, module.ImportReference((MethodBase)_m_Copy)); } public static void EmitDetourApply(this ILProcessor il, NativeDetourData data) { //IL_0012: 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_003e: 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_005f: 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_007b: 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_0097: 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_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) ModuleDefinition module = ((MemberReference)il.Body.Method).Module; il.Emit(OpCodes.Ldsfld, module.ImportReference(_f_Native)); il.Emit(OpCodes.Ldc_I8, (long)data.Method); il.Emit(OpCodes.Conv_I); il.Emit(OpCodes.Ldc_I8, (long)data.Target); il.Emit(OpCodes.Conv_I); il.Emit(OpCodes.Ldc_I4, (int)data.Size); il.Emit(OpCodes.Ldc_I4, (int)data.Type); il.Emit(OpCodes.Conv_U1); il.Emit(OpCodes.Ldc_I8, (long)data.Extra); il.Emit(OpCodes.Conv_I); il.Emit(OpCodes.Call, module.ImportReference((MethodBase)_m_ToNativeDetourData)); il.Emit(OpCodes.Callvirt, module.ImportReference((MethodBase)_m_Apply)); } } public interface IDetourNativePlatform { NativeDetourData Create(IntPtr from, IntPtr to, byte? type = null); void Free(NativeDetourData detour); void Apply(NativeDetourData detour); void Copy(IntPtr src, IntPtr dst, byte type); void MakeWritable(IntPtr src, uint size); void MakeExecutable(IntPtr src, uint size); void MakeReadWriteExecutable(IntPtr src, uint size); void FlushICache(IntPtr src, uint size); IntPtr MemAlloc(uint size); void MemFree(IntPtr ptr); } public interface IDetourRuntimePlatform { bool OnMethodCompiledWillBeCalled { get; } event OnMethodCompiledEvent OnMethodCompiled; MethodBase GetIdentifiable(MethodBase method); IntPtr GetNativeStart(MethodBase method); MethodInfo CreateCopy(MethodBase method); bool TryCreateCopy(MethodBase method, out MethodInfo dm); void Pin(MethodBase method); void Unpin(MethodBase method); MethodBase GetDetourTarget(MethodBase from, MethodBase to); uint TryMemAllocScratchCloseTo(IntPtr target, out IntPtr ptr, int size); } public delegate void OnMethodCompiledEvent(MethodBase method, IntPtr codeStart, ulong codeSize); public struct NativeDetourData { public IntPtr Method; public IntPtr Target; public byte Type; public uint Size; public IntPtr Extra; } } namespace MonoMod.RuntimeDetour.Platforms { public class DetourNativeARMPlatform : IDetourNativePlatform { public enum DetourType : byte { Thumb, ThumbBX, AArch32, AArch32BX, AArch64 } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int d_flushicache(IntPtr code, ulong size); private static readonly uint[] DetourSizes = new uint[5] { 8u, 12u, 8u, 12u, 16u }; public bool ShouldFlushICache = true; private readonly byte[] _FlushCache32 = new byte[44] { 128, 64, 45, 233, 0, 48, 160, 225, 1, 192, 128, 224, 20, 224, 159, 229, 3, 0, 160, 225, 12, 16, 160, 225, 14, 112, 160, 225, 0, 32, 160, 227, 0, 0, 0, 239, 128, 128, 189, 232, 2, 0, 15, 0 }; private readonly byte[] _FlushCache64 = new byte[76] { 1, 0, 1, 139, 0, 244, 126, 146, 63, 0, 0, 235, 201, 0, 0, 84, 226, 3, 0, 170, 34, 126, 11, 213, 66, 16, 0, 145, 63, 0, 2, 235, 168, 255, 255, 84, 159, 59, 3, 213, 63, 0, 0, 235, 169, 0, 0, 84, 32, 117, 11, 213, 0, 16, 0, 145, 63, 0, 0, 235, 168, 255, 255, 84, 159, 59, 3, 213, 223, 63, 3, 213, 192, 3, 95, 214 }; private static DetourType GetDetourType(IntPtr from, IntPtr to) { if (IntPtr.Size >= 8) { return DetourType.AArch64; } bool num = ((long)from & 1) == 1; bool flag = ((long)to & 1) == 1; if (num) { if (flag) { return DetourType.Thumb; } return DetourType.ThumbBX; } if (flag) { return DetourType.AArch32BX; } return DetourType.AArch32; } public NativeDetourData Create(IntPtr from, IntPtr to, byte? type) { NativeDetourData result = new NativeDetourData { Method = (IntPtr)((long)from & -2), Target = (IntPtr)((long)to & -2) }; uint[] detourSizes = DetourSizes; int num = ((int?)type) ?? ((int)GetDetourType(from, to)); byte b = (byte)num; result.Type = (byte)num; result.Size = detourSizes[b]; return result; } public void Free(NativeDetourData detour) { } public void Apply(NativeDetourData detour) { int offs = 0; switch ((DetourType)detour.Type) { case DetourType.Thumb: detour.Method.Write(ref offs, 223); detour.Method.Write(ref offs, 248); detour.Method.Write(ref offs, 0); detour.Method.Write(ref offs, 240); detour.Method.Write(ref offs, (uint)((int)detour.Target | 1)); break; case DetourType.ThumbBX: detour.Method.Write(ref offs, 223); detour.Method.Write(ref offs, 248); detour.Method.Write(ref offs, 4); detour.Method.Write(ref offs, 160); detour.Method.Write(ref offs, 80); detour.Method.Write(ref offs, 71); detour.Method.Write(ref offs, 0); detour.Method.Write(ref offs, 191); detour.Method.Write(ref offs, (uint)((int)detour.Target | 0)); break; case DetourType.AArch32: detour.Method.Write(ref offs, 4); detour.Method.Write(ref offs, 240); detour.Method.Write(ref offs, 31); detour.Method.Write(ref offs, 229); detour.Method.Write(ref offs, (uint)((int)detour.Target | 0)); break; case DetourType.AArch32BX: detour.Method.Write(ref offs, 0); detour.Method.Write(ref offs, 128); detour.Method.Write(ref offs, 159); detour.Method.Write(ref offs, 229); detour.Method.Write(ref offs, 24); detour.Method.Write(ref offs, byte.MaxValue); detour.Method.Write(ref offs, 47); detour.Method.Write(ref offs, 225); detour.Method.Write(ref offs, (uint)((int)detour.Target | 1)); break; case DetourType.AArch64: detour.Method.Write(ref offs, 79); detour.Method.Write(ref offs, 0); detour.Method.Write(ref offs, 0); detour.Method.Write(ref offs, 88); detour.Method.Write(ref offs, 224); detour.Method.Write(ref offs, 1); detour.Method.Write(ref offs, 31); detour.Method.Write(ref offs, 214); detour.Method.Write(ref offs, (ulong)(long)detour.Target); break; default: throw new NotSupportedException($"Unknown detour type {detour.Type}"); } } public unsafe void Copy(IntPtr src, IntPtr dst, byte type) { switch ((DetourType)type) { case DetourType.Thumb: *(int*)(long)dst = *(int*)(long)src; *(int*)((long)dst + 4) = *(int*)((long)src + 4); break; case DetourType.ThumbBX: *(int*)(long)dst = *(int*)(long)src; *(short*)((long)dst + 4) = *(short*)((long)src + 4); *(short*)((long)dst + 6) = *(short*)((long)src + 6); *(int*)((long)dst + 8) = *(int*)((long)src + 8); break; case DetourType.AArch32: *(int*)(long)dst = *(int*)(long)src; *(int*)((long)dst + 4) = *(int*)((long)src + 4); break; case DetourType.AArch32BX: *(int*)(long)dst = *(int*)(long)src; *(int*)((long)dst + 4) = *(int*)((long)src + 4); *(int*)((long)dst + 8) = *(int*)((long)src + 8); break; case DetourType.AArch64: *(int*)(long)dst = *(int*)(long)src; *(int*)((long)dst + 4) = *(int*)((long)src + 4); *(long*)((long)dst + 8) = *(long*)((long)src + 8); break; default: throw new NotSupportedException($"Unknown detour type {type}"); } } public void MakeWritable(IntPtr src, uint size) { } public void MakeExecutable(IntPtr src, uint size) { } public void MakeReadWriteExecutable(IntPtr src, uint size) { } public unsafe void FlushICache(IntPtr src, uint size) { if (ShouldFlushICache) { byte[] array = ((IntPtr.Size >= 8) ? _FlushCache64 : _FlushCache32); fixed (byte* ptr = array) { DetourHelper.Native.MakeExecutable((IntPtr)ptr, (uint)array.Length); (Marshal.GetDelegateForFunctionPointer((IntPtr)ptr, typeof(d_flushicache)) as d_flushicache)(src, size); } } } public IntPtr MemAlloc(uint size) { return Marshal.AllocHGlobal((int)size); } public void MemFree(IntPtr ptr) { Marshal.FreeHGlobal(ptr); } } public class DetourNativeLibcPlatform : IDetourNativePlatform { [Flags] private enum MmapProts { PROT_READ = 1, PROT_WRITE = 2, PROT_EXEC = 4, PROT_NONE = 0, PROT_GROWSDOWN = 0x1000000, PROT_GROWSUP = 0x2000000 } private readonly IDetourNativePlatform Inner; private readonly long _Pagesize; public DetourNativeLibcPlatform(IDetourNativePlatform inner) { Inner = inner; PropertyInfo property = typeof(Environment).GetProperty("SystemPageSize"); if ((object)property == null) { throw new NotSupportedException("Unsupported runtime"); } _Pagesize = (int)property.GetValue(null, new object[0]); } private void SetMemPerms(IntPtr start, ulong len, MmapProts prot) { long pagesize = _Pagesize; long num = (long)start & ~(pagesize - 1); long num2 = ((long)start + (long)len + pagesize - 1) & ~(pagesize - 1); if (mprotect((IntPtr)num, (IntPtr)(num2 - num), prot) != 0) { throw new Win32Exception(); } } public void MakeWritable(IntPtr src, uint size) { SetMemPerms(src, size, MmapProts.PROT_READ | MmapProts.PROT_WRITE | MmapProts.PROT_EXEC); } public void MakeExecutable(IntPtr src, uint size) { SetMemPerms(src, size, MmapProts.PROT_READ | MmapProts.PROT_WRITE | MmapProts.PROT_EXEC); } public void MakeReadWriteExecutable(IntPtr src, uint size) { SetMemPerms(src, size, MmapProts.PROT_READ | MmapProts.PROT_WRITE | MmapProts.PROT_EXEC); } public void FlushICache(IntPtr src, uint size) { Inner.FlushICache(src, size); } public NativeDetourData Create(IntPtr from, IntPtr to, byte? type) { return Inner.Create(from, to, type); } public void Free(NativeDetourData detour) { Inner.Free(detour); } public void Apply(NativeDetourData detour) { Inner.Apply(detour); } public void Copy(IntPtr src, IntPtr dst, byte type) { Inner.Copy(src, dst, type); } public IntPtr MemAlloc(uint size) { return Inner.MemAlloc(size); } public void MemFree(IntPtr ptr) { Inne
BepInExPack\BepInEx\core\MonoMod.Utils.dll
Decompiled 2 months ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.SymbolStore; 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.Security; using System.Security.Permissions; using System.Text; using System.Threading; using Mono.Cecil; using Mono.Cecil.Cil; using Mono.Collections.Generic; using MonoMod.Utils; using MonoMod.Utils.Cil; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("MonoMod.Utils.Cil.ILGeneratorProxy")] [assembly: AssemblyCompany("0x0ade")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Copyright 2022 0x0ade")] [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("22.5.1.1")] [assembly: AssemblyInformationalVersion("22.05.01.01")] [assembly: AssemblyProduct("MonoMod.Utils")] [assembly: AssemblyTitle("MonoMod.Utils")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("22.5.1.1")] [module: UnverifiableCode] internal static class MultiTargetShims { private static readonly object[] _NoArgs = new object[0]; public static string Replace(this string self, string oldValue, string newValue, StringComparison comparison) { return self.Replace(oldValue, newValue); } public static bool Contains(this string self, string value, StringComparison comparison) { return self.Contains(value); } public static int GetHashCode(this string self, StringComparison comparison) { return self.GetHashCode(); } public static int IndexOf(this string self, char value, StringComparison comparison) { return self.IndexOf(value); } public static int IndexOf(this string self, string value, StringComparison comparison) { return self.IndexOf(value); } public static TypeReference GetConstraintType(this TypeReference type) { return type; } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] public class IgnoresAccessChecksToAttribute : Attribute { public string AssemblyName { get; } public IgnoresAccessChecksToAttribute(string assemblyName) { AssemblyName = assemblyName; } } } namespace MonoMod { internal static class MMDbgLog { public static readonly string Tag; public static TextWriter Writer; public static bool Debugging; static MMDbgLog() { Tag = typeof(MMDbgLog).Assembly.GetName().Name; if (!(Environment.GetEnvironmentVariable("MONOMOD_DBGLOG") == "1")) { string? environmentVariable = Environment.GetEnvironmentVariable("MONOMOD_DBGLOG"); bool? obj; if (environmentVariable == null) { obj = null; } else { string text = environmentVariable.ToLower(CultureInfo.InvariantCulture); obj = ((text != null) ? new bool?(MultiTargetShims.Contains(text, Tag.ToLower(CultureInfo.InvariantCulture), StringComparison.Ordinal)) : ((bool?)null)); } bool? flag = obj; if (flag != true) { return; } } Start(); } public static void WaitForDebugger() { if (!Debugging) { Debugging = true; Debugger.Launch(); Thread.Sleep(6000); Debugger.Break(); } } public static void Start() { if (Writer != null) { return; } string text = Environment.GetEnvironmentVariable("MONOMOD_DBGLOG_PATH"); if (text == "-") { Writer = Console.Out; return; } if (string.IsNullOrEmpty(text)) { text = "mmdbglog.txt"; } text = Path.GetFullPath(Path.GetFileNameWithoutExtension(text) + "-" + Tag + Path.GetExtension(text)); try { if (File.Exists(text)) { File.Delete(text); } } catch { } try { string directoryName = Path.GetDirectoryName(text); if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } Writer = new StreamWriter(new FileStream(text, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete), Encoding.UTF8); } catch { } } public static void Log(string str) { TextWriter writer = Writer; if (writer != null) { writer.WriteLine(str); writer.Flush(); } } public static T Log<T>(string str, T value) { TextWriter writer = Writer; if (writer == null) { return value; } writer.WriteLine(string.Format(CultureInfo.InvariantCulture, str, new object[1] { value })); writer.Flush(); return value; } } } namespace MonoMod.ModInterop { [AttributeUsage(AttributeTargets.Class)] public sealed class ModExportNameAttribute : Attribute { public string Name; public ModExportNameAttribute(string name) { Name = name; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Field)] public sealed class ModImportNameAttribute : Attribute { public string Name; public ModImportNameAttribute(string name) { Name = name; } } public static class ModInteropManager { private static HashSet<Type> Registered = new HashSet<Type>(); private static Dictionary<string, List<MethodInfo>> Methods = new Dictionary<string, List<MethodInfo>>(); private static List<FieldInfo> Fields = new List<FieldInfo>(); public static void ModInterop(this 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 var 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) { 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 var value)) { value = (Methods[text] = new List<MethodInfo>()); } 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; } 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.Utils { public sealed class DynData<TTarget> : IDisposable where TTarget : class { private class _Data_ : IDisposable { public readonly Dictionary<string, Func<TTarget, object>> Getters = new Dictionary<string, Func<TTarget, object>>(); public readonly Dictionary<string, Action<TTarget, object>> Setters = new Dictionary<string, Action<TTarget, object>>(); public readonly Dictionary<string, object> Data = new Dictionary<string, object>(); public readonly HashSet<string> Disposable = new HashSet<string>(); ~_Data_() { Dispose(); } public void Dispose() { lock (Data) { if (Data.Count == 0) { return; } foreach (string item in Disposable) { if (Data.TryGetValue(item, out var value) && value is IDisposable disposable) { disposable.Dispose(); } } Disposable.Clear(); Data.Clear(); } } } private static int CreationsInProgress; private static readonly object[] _NoArgs; private static readonly _Data_ _DataStatic; private static readonly Dictionary<WeakReference, _Data_> _DataMap; private static readonly HashSet<WeakReference> _DataMapDead; private static readonly Dictionary<string, Func<TTarget, object>> _SpecialGetters; private static readonly Dictionary<string, Action<TTarget, object>> _SpecialSetters; private readonly WeakReference Weak; private TTarget KeepAlive; private readonly _Data_ _Data; public Dictionary<string, Func<TTarget, object>> Getters => _Data.Getters; public Dictionary<string, Action<TTarget, object>> Setters => _Data.Setters; public Dictionary<string, object> Data => _Data.Data; public bool IsAlive { get { if (Weak != null) { return Weak.SafeGetIsAlive(); } return true; } } public TTarget Target => Weak?.SafeGetTarget() as TTarget; public object this[string name] { get { if (_SpecialGetters.TryGetValue(name, out var value) || Getters.TryGetValue(name, out value)) { return value(Weak?.SafeGetTarget() as TTarget); } if (Data.TryGetValue(name, out var value2)) { return value2; } return null; } set { if (_SpecialSetters.TryGetValue(name, out var value2) || Setters.TryGetValue(name, out value2)) { value2(Weak?.SafeGetTarget() as TTarget, 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<DynData<TTarget>, TTarget> OnInitialize; static DynData() { CreationsInProgress = 0; _NoArgs = new object[0]; _DataStatic = new _Data_(); _DataMap = new Dictionary<WeakReference, _Data_>(new WeakReferenceComparer()); _DataMapDead = new HashSet<WeakReference>(); _SpecialGetters = new Dictionary<string, Func<TTarget, object>>(); _SpecialSetters = new Dictionary<string, Action<TTarget, object>>(); GCListener.OnCollect += delegate { if (CreationsInProgress != 0) { return; } lock (_DataMap) { foreach (KeyValuePair<WeakReference, _Data_> item in _DataMap) { if (!item.Key.SafeGetIsAlive()) { _DataMapDead.Add(item.Key); item.Value.Dispose(); } } foreach (WeakReference item2 in _DataMapDead) { _DataMap.Remove(item2); } _DataMapDead.Clear(); } }; 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 ((object)get != null) { _SpecialGetters[name2] = (TTarget obj) => get.Invoke(obj, _NoArgs); } MethodInfo set = propertyInfo.GetSetMethod(nonPublic: true); if ((object)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 weakReference = new WeakReference(obj); WeakReference key = weakReference; CreationsInProgress++; lock (_DataMap) { if (!_DataMap.TryGetValue(key, out _Data)) { _Data = new _Data_(); _DataMap.Add(key, _Data); } } CreationsInProgress--; Weak = weakReference; if (keepAlive) { KeepAlive = obj; } } else { _Data = _DataStatic; } DynData<TTarget>.OnInitialize?.Invoke(this, obj); } public T Get<T>(string name) { return (T)this[name]; } public void Set<T>(string name, T value) { this[name] = value; } public void RegisterProperty(string name, Func<TTarget, object> getter, Action<TTarget, object> 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; } ~DynData() { Dispose(disposing: false); } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } } public static class Extensions { private static readonly Type t_StateMachineAttribute = typeof(object).Assembly.GetType("System.Runtime.CompilerServices.StateMachineAttribute"); private static readonly PropertyInfo p_StateMachineType = t_StateMachineAttribute?.GetProperty("StateMachineType"); private static readonly Type t_Code = typeof(Code); private static readonly Type t_OpCodes = typeof(OpCodes); private static readonly Dictionary<int, OpCode> _ToLongOp = new Dictionary<int, OpCode>(); private static readonly Dictionary<int, OpCode> _ToShortOp = new Dictionary<int, OpCode>(); private static readonly object[] _NoArgs = new object[0]; private static readonly Dictionary<Type, FieldInfo> fmap_mono_assembly = new Dictionary<Type, FieldInfo>(); 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); private static readonly FieldInfo f_GenericParameter_type = typeof(GenericParameter).GetField("type", BindingFlags.Instance | BindingFlags.NonPublic); private static readonly Dictionary<Type, int> _GetManagedSizeCache = new Dictionary<Type, int> { { typeof(void), 0 } }; private static MethodInfo _GetManagedSizeHelper; private static readonly Dictionary<MethodBase, Func<IntPtr>> _GetLdftnPointerCache = new Dictionary<MethodBase, Func<IntPtr>>(); public static string ToHexadecimalString(this byte[] data) { return MultiTargetShims.Replace(BitConverter.ToString(data), "-", string.Empty, StringComparison.Ordinal); } public static T InvokePassing<T>(this MulticastDelegate md, T val, params object[] args) { if ((object)md == null) { return val; } 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; } 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; } 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<T>(this MulticastDelegate md, params object[] args) where T : class { if ((object)md == null) { return null; } 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) { 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) { string text = ""; char c; while ((c = stream.ReadChar()) != 0) { text += c; } return text; } public static void WriteNullTerminatedString(this BinaryWriter stream, string text) { if (text != null) { foreach (char ch in text) { stream.Write(ch); } } stream.Write('\0'); } public static T CastDelegate<T>(this Delegate source) where T : class { return source.CastDelegate(typeof(T)) as T; } public static Delegate CastDelegate(this Delegate source, Type type) { if ((object)source == null) { return null; } Delegate[] invocationList = source.GetInvocationList(); if (invocationList.Length == 1) { return CreateDelegate(invocationList[0].Method, type, invocationList[0].Target); } Delegate[] array = new Delegate[invocationList.Length]; for (int i = 0; i < invocationList.Length; i++) { array[i] = invocationList[i].CastDelegate(type); } return Delegate.Combine(array); } public static bool TryCastDelegate<T>(this Delegate source, out T result) where T : class { if (source is T val) { result = val; return true; } Delegate result3; bool result2 = source.TryCastDelegate(typeof(T), out result3); result = result3 as T; return result2; } public static bool TryCastDelegate(this Delegate source, Type type, out Delegate result) { result = null; if ((object)source == null) { return false; } try { Delegate[] invocationList = source.GetInvocationList(); if (invocationList.Length == 1) { result = CreateDelegate(invocationList[0].Method, type, invocationList[0].Target); return true; } Delegate[] array = new Delegate[invocationList.Length]; for (int i = 0; i < invocationList.Length; i++) { array[i] = invocationList[i].CastDelegate(type); } result = Delegate.Combine(array); return true; } catch { return false; } } public static void LogDetailed(this Exception e, string tag = null) { if (tag == null) { Console.WriteLine("--------------------------------"); Console.WriteLine("Detailed exception log:"); } for (Exception ex = e; ex != null; ex = ex.InnerException) { Console.WriteLine("--------------------------------"); Console.WriteLine(ex.GetType().FullName + ": " + ex.Message + "\n" + ex.StackTrace); if (ex is ReflectionTypeLoadException ex2) { for (int i = 0; i < ex2.Types.Length; i++) { Console.WriteLine("ReflectionTypeLoadException.Types[" + i + "]: " + ex2.Types[i]); } for (int j = 0; j < ex2.LoaderExceptions.Length; j++) { ex2.LoaderExceptions[j].LogDetailed(tag + ((tag == null) ? "" : ", ") + "rtle:" + j); } } if (ex is TypeLoadException) { Console.WriteLine("TypeLoadException.TypeName: " + ((TypeLoadException)ex).TypeName); } if (ex is BadImageFormatException) { Console.WriteLine("BadImageFormatException.FileName: " + ((BadImageFormatException)ex).FileName); } } } public static MethodInfo GetStateMachineTarget(this MethodInfo method) { if ((object)p_StateMachineType == null) { return null; } 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) { return (method.IsGenericMethod ? method.GetGenericMethodDefinition() : method).GetUnfilledMethodOnGenericType(); } public static MethodBase GetUnfilledMethodOnGenericType(this MethodBase method) { if ((object)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) { if (member == null) { return false; } return MultiTargetShims.Replace(member.FullName, "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(fullName, "+", "/", StringComparison.Ordinal); } public static bool Is(this MemberReference member, string typeFullName, string name) { if (member == null) { return false; } if (MultiTargetShims.Replace(((MemberReference)member.DeclaringType).FullName, "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(typeFullName, "+", "/", StringComparison.Ordinal)) { return member.Name == name; } return false; } public static bool Is(this MemberReference member, Type type, string name) { if (member == null) { return false; } if (MultiTargetShims.Replace(((MemberReference)member.DeclaringType).FullName, "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(type.FullName, "+", "/", StringComparison.Ordinal)) { return member.Name == name; } return false; } public static bool Is(this MethodReference method, string fullName) { if (method == null) { return false; } if (MultiTargetShims.Contains(fullName, " ", StringComparison.Ordinal)) { if (MultiTargetShims.Replace(method.GetID(null, null, withType: true, simple: true), "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(fullName, "+", "/", StringComparison.Ordinal)) { return true; } if (MultiTargetShims.Replace(method.GetID(), "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(fullName, "+", "/", StringComparison.Ordinal)) { return true; } } return MultiTargetShims.Replace(((MemberReference)method).FullName, "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(fullName, "+", "/", StringComparison.Ordinal); } public static bool Is(this MethodReference method, string typeFullName, string name) { if (method == null) { return false; } if (MultiTargetShims.Contains(name, " ", StringComparison.Ordinal) && MultiTargetShims.Replace(((MemberReference)((MemberReference)method).DeclaringType).FullName, "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(typeFullName, "+", "/", StringComparison.Ordinal) && MultiTargetShims.Replace(method.GetID(null, null, withType: false), "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(name, "+", "/", StringComparison.Ordinal)) { return true; } if (MultiTargetShims.Replace(((MemberReference)((MemberReference)method).DeclaringType).FullName, "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(typeFullName, "+", "/", StringComparison.Ordinal)) { return ((MemberReference)method).Name == name; } return false; } public static bool Is(this MethodReference method, Type type, string name) { if (method == null) { return false; } if (MultiTargetShims.Contains(name, " ", StringComparison.Ordinal) && MultiTargetShims.Replace(((MemberReference)((MemberReference)method).DeclaringType).FullName, "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(type.FullName, "+", "/", StringComparison.Ordinal) && MultiTargetShims.Replace(method.GetID(null, null, withType: false), "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(name, "+", "/", StringComparison.Ordinal)) { return true; } if (MultiTargetShims.Replace(((MemberReference)((MemberReference)method).DeclaringType).FullName, "+", "/", StringComparison.Ordinal) == MultiTargetShims.Replace(type.FullName, "+", "/", StringComparison.Ordinal)) { return ((MemberReference)method).Name == name; } return false; } public static void ReplaceOperands(this ILProcessor il, object from, object to) { //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) Enumerator<Instruction> 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)il.Body.Method).Module.ImportReference(field); } public static MethodReference Import(this ILProcessor il, MethodBase method) { return ((MemberReference)il.Body.Method).Module.ImportReference(method); } public static TypeReference Import(this ILProcessor il, Type type) { return ((MemberReference)il.Body.Method).Module.ImportReference(type); } public static MemberReference Import(this ILProcessor il, MemberInfo member) { if ((object)member == null) { throw new ArgumentNullException("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_0001: Unknown result type (might be due to invalid IL or missing references) return il.Create(opcode, il.Import(field)); } public static Instruction Create(this ILProcessor il, OpCode opcode, MethodBase method) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) if (method is DynamicMethod) { return il.Create(opcode, (object)method); } return il.Create(opcode, il.Import(method)); } public static Instruction Create(this ILProcessor il, OpCode opcode, Type type) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return il.Create(opcode, il.Import(type)); } public static Instruction Create(this ILProcessor il, OpCode opcode, object operand) { //IL_0001: 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 = il.Create(OpCodes.Nop); obj.OpCode = opcode; obj.Operand = operand; return obj; } public static Instruction Create(this ILProcessor il, OpCode opcode, MemberInfo member) { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) if ((object)member == null) { throw new ArgumentNullException("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_0001: Unknown result type (might be due to invalid IL or missing references) il.Emit(opcode, il.Import(field)); } public static void Emit(this ILProcessor il, OpCode opcode, MethodBase method) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) if (method is DynamicMethod) { il.Emit(opcode, (object)method); } else { il.Emit(opcode, il.Import(method)); } } public static void Emit(this ILProcessor il, OpCode opcode, Type type) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) il.Emit(opcode, il.Import(type)); } public static void Emit(this ILProcessor il, OpCode opcode, MemberInfo member) { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) if ((object)member == null) { throw new ArgumentNullException("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_0002: Unknown result type (might be due to invalid IL or missing references) il.Append(il.Create(opcode, operand)); } public static TypeDefinition SafeResolve(this TypeReference r) { try { return r.Resolve(); } catch { return null; } } public static FieldDefinition SafeResolve(this FieldReference r) { try { return r.Resolve(); } catch { return null; } } public static MethodDefinition SafeResolve(this MethodReference r) { try { return r.Resolve(); } catch { return null; } } public static PropertyDefinition SafeResolve(this PropertyReference r) { try { return r.Resolve(); } 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<CustomAttribute> 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_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_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_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0035: 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_0044: 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_0053: 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_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0071: 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_0080: 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) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) 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_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_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_001b: 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_002f: 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_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0058: 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_006c: 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_0080: 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_0094: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: 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_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: 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_00ee: Unknown result type (might be due to invalid IL or missing references) 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) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) MethodDefinition method = body.Method; if (called == null) { return false; } TypeReference val = ((MemberReference)called).DeclaringType; while (val is TypeSpecification) { val = ((TypeSpecification)val).ElementType; } string patchFullName = ((MemberReference)(object)val).GetPatchFullName(); bool flag = false; try { TypeDefinition val2 = method.DeclaringType; while ((val2 = val2.BaseType?.SafeResolve()) != null) { if (((MemberReference)(object)val2).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) { if (!method.HasThis) { return false; } if (((MemberReference)method).DeclaringType.IsValueType) { return false; } return true; } public static bool IsStruct(this TypeReference 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_0025: 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: Expected I4, but got Unknown //IL_0053: 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_0049: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: 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_008e: 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_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Expected I4, but got Unknown //IL_00a0: 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) string name = Enum.GetName(t_Code, ((OpCode)(ref op)).Code); if (!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)(((??)(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_0025: 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: Expected I4, but got Unknown //IL_0053: 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_0049: 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_008f: 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_0094: 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_009c: Expected I4, but got Unknown //IL_009c: 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) string name = Enum.GetName(t_Code, ((OpCode)(ref op)).Code); if (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)(((??)(OpCode?)t_OpCodes.GetField(name + "_S")?.GetValue(null)) ?? op); } } public static void RecalculateILOffsets(this MethodDefinition 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_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_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) 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; } TypeReference val = mref.DeclaringType; if (((val != null) ? ((MemberReference)val).FullName : null) == "<Module>") { 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 ((object)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<TypeReference> 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<GenericParameter> 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 == MultiTargetShims.Replace(type3.FullName, "+", "/", 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<ParameterDefinition> 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<TypeReference> 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<GenericParameter> 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) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Expected O, but got Unknown //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Expected O, but got Unknown //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Expected O, but got Unknown if (mtp is TypeReference) { return (IMetadataTokenProvider)(object)mod.ImportReference((TypeReference)mtp); } if (mtp is FieldReference) { return (IMetadataTokenProvider)(object)mod.ImportReference((FieldReference)mtp); } if (mtp is MethodReference) { return (IMetadataTokenProvider)(object)mod.ImportReference((MethodReference)mtp); } return mtp; } public static void AddRange<T>(this Collection<T> list, IEnumerable<T> other) { foreach (T item in other) { list.Add(item); } } public static void AddRange(this IDictionary dict, IDictionary other) { foreach (DictionaryEntry item in other) { dict.Add(item.Key, item.Value); } } public static void AddRange<K, V>(this IDictionary<K, V> dict, IDictionary<K, V> other) { foreach (KeyValuePair<K, V> item in other) { dict.Add(item.Key, item.Value); } } public static void AddRange<K, V>(this Dictionary<K, V> dict, Dictionary<K, V> other) { foreach (KeyValuePair<K, V> item in other) { dict.Add(item.Key, item.Value); } } public static void InsertRange<T>(this Collection<T> list, int index, IEnumerable<T> other) { foreach (T item in other) { list.Insert(index++, item); } } public static bool IsCompatible(this Type type, Type other) { if (!type._IsCompatible(other)) { return other._IsCompatible(type); } return true; } private static bool _IsCompatible(this Type type, Type other) { if ((object)type == other) { return true; } if (type.IsAssignableFrom(other)) { return true; } if (other.IsEnum && type.IsCompatible(Enum.GetUnderlyingType(other))) { return true; } if ((other.IsPointer || other.IsByRef) && (object)type == typeof(IntPtr)) { return true; } return false; } public static T GetDeclaredMember<T>(this T member) where T : MemberInfo { if ((object)member.DeclaringType == member.ReflectedType) { return member; } 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 (!ReflectionHelper.IsMono) { return; } Type type = asm?.GetType(); if ((object)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); fmap_mono_assembly[type] = value2; } } if ((object)value2 == null) { return; } AssemblyName assemblyName = new AssemblyName(asm.FullName); lock (ReflectionHelper.AssemblyCache) { WeakReference value3 = new WeakReference(asm); ReflectionHelper.AssemblyCache[asm.GetRuntimeHashedFullName()] = value3; ReflectionHelper.AssemblyCache[assemblyName.FullName] = value3; ReflectionHelper.AssemblyCache[assemblyName.Name] = value3; } long num = 0L; object value4 = value2.GetValue(asm); if (!(value4 is IntPtr intPtr)) { if (value4 is UIntPtr uIntPtr) { num = (long)(ulong)uIntPtr; } } else { num = (long)intPtr; } int num2 = IntPtr.Size + IntPtr.Size + IntPtr.Size + IntPtr.Size + IntPtr.Size + IntPtr.Size + 20 + 4 + 4 + 4 + (_MonoAssemblyNameHasArch ? ((!ReflectionHelper.IsCore) ? ((IntPtr.Size == 4) ? 12 : 16) : ((IntPtr.Size == 4) ? 20 : 24)) : (ReflectionHelper.IsCore ? 16 : 8)) + IntPtr.Size + IntPtr.Size + 1 + 1 + 1; byte* ptr = (byte*)(num + num2); *ptr = (byte)(value ? 1 : 0); } public static bool IsDynamicMethod(this MethodBase method) { if ((object)_RTDynamicMethod != null) { if (!(method is DynamicMethod)) { return (object)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; } MethodInfo[] methods = method.DeclaringType.GetMethods(BindingFlags.Static | BindingFlags.Public); foreach (MethodInfo methodInfo in methods) { if ((object)method == methodInfo) { return false; } } return true; } public static object SafeGetTarget(this WeakReference weak) { try { return weak.Target; } catch (InvalidOperationException) { return null; } } public static bool SafeGetIsAlive(this WeakReference weak) { try { return weak.IsAlive; } catch (InvalidOperationException) { return false; } } public static T CreateDelegate<T>(this MethodBase method) where T : Delegate { return (T)method.CreateDelegate(typeof(T), null); } public static T CreateDelegate<T>(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) { 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); } RuntimeMethodHandle methodHandle = method.MethodHandle; RuntimeHelpers.PrepareMethod(methodHandle); IntPtr functionPointer = methodHandle.GetFunctionPointer(); return (Delegate)Activator.CreateInstance(delegateType, target, functionPointer); } public static MethodDefinition FindMethod(this TypeDefinition type, string id, bool simple = true) { //IL_00ad: 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_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_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_00fa: Unknown result type (might be due to invalid IL or missing references) //IL_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) Enumerator<MethodDefinition> enumerator; if (simple && !MultiTargetShims.Contains(id, " ", 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 = 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) { MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); MethodInfo[] array; if (simple && !MultiTargetShims.Contains(id, " ", 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_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) Enumerator<PropertyDefinition> 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) { 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_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) Enumerator<FieldDefinition> 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) { 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_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) Enumerator<EventDefinition> 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) { 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) { 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<TypeReference> 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<GenericParameter> 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<ParameterDefinition> 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) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(((MemberReference)(object)method.ReturnType).GetPatchFullName()).Append(" "); stringBuilder.Append("("); if (method.HasParameters) { Collection<ParameterDefinition> 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) { while (method is MethodInfo && method.IsGenericMethod && !method.IsGenericMethodDefinition) { method = ((MethodInfo)method).GetGenericMethodDefinition(); } StringBuilder stringBuilder = new StringBuilder(); if (simple) { if (withType && (type != null || (object)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 || (object)method.DeclaringType != null)) { stringBuilder.Append(type ?? MultiTargetShims.Replace(method.DeclaringType.FullName, "+", "/", 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) { MemberReference obj = ((mr is ICustomAttributeProvider) ? mr : null); return ((obj != null) ? ((ICustomAttributeProvider)(object)obj).GetPatchName() : null) ?? mr.Name; } public static string GetPatchFullName(this MemberReference 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_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) 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_003a: 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_0028: 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_00ec: Expected O, but got Unknown //IL_019d: Unknown result type (might be due to invalid IL or missing references) //IL_01a4: Expected O, but got Unknown //IL_0247: Unknown result type (might be due to invalid IL or missing references) //IL_027d: Unknown result type (might be due to invalid IL or missing references) //IL_02a7: Unknown result type (might be due to invalid IL or missing references) //IL_02ae: Expected O, but got Unknown //IL_0323: Unknown result type (might be due to invalid IL or missing references) //IL_032a: Expected O, but got Unknown //IL_01ee: Unknown result type (might be due to invalid IL or missing references) //IL_01f3: Unknown result type (might be due to invalid IL or missing references) 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 (!MultiTargetShims.Contains(text, ".", StringComparison.Ordinal) && !MultiTargetShims.Contains(text, "/", StringComparison.Ordinal)) { if (!string.IsNullOrEmpty(val.Namespace)) { text = val.Namespace + "." + text; } else if (val.IsNested) { text = ((MemberReference)(object)((MemberReference)val).DeclaringType).GetPatchFullName() + "/" + text; } } if (mr is TypeSpecification) { List<TypeSpecification> list = new List<TypeSpecification>(); TypeSpecification val3 = (TypeSpecification)mr; TypeReference elementType; do { list.Add(val3); elementType = val3.ElementType; } while ((val3 = (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--) { val3 = list[num]; if (((TypeReference)val3).IsByReference) { stringBuilder.Append("&"); } else if (((TypeReference)val3).IsPointer) { stringBuilder.Append("*"); } else if (!((TypeReference)val3).IsPinned && !((TypeReference)val3).IsSentinel) { if (((TypeReference)val3).IsArray) { ArrayType val4 = (ArrayType)val3; if (val4.IsVector) { stringBuilder.Append("[]"); } else { stringBuilder.Append("["); for (int i = 0; i < val4.Dimensions.Count; i++) { if (i > 0) { stringBuilder.Append(","); } stringBuilder.Append(((object)val4.Dimensions[i]/*cast due to .constrained prefix*/).ToString()); } stringBuilder.Append("]"); } } else if (((TypeReference)val3).IsRequiredModifier) { stringBuilder.Append("modreq(").Append(((RequiredModifierType)val3).ModifierType).Append(")"); } else if (((TypeReference)val3).IsOptionalModifier) { stringBuilder.Append("modopt(").Append(((OptionalModifierType)val3).ModifierType).Append(")"); } else if (((TypeReference)val3).IsGenericInstance) { GenericInstanceType val5 = (GenericInstanceType)val3; stringBuilder.Append("<"); for (int j = 0; j < val5.GenericArguments.Count; j++) { if (j > 0) { stringBuilder.Append(","); } stringBuilder.Append(((MemberReference)(object)val5.GenericArguments[j]).GetPatchFullName()); } stringBuilder.Append(">"); } else { if (!((TypeReference)val3).IsFunctionPointer) { throw new NotSupportedException($"MonoMod can't handle TypeSpecification: {((MemberReference)val).FullName} ({((object)val).GetType()})"); } FunctionPointerType val6 = (FunctionPointerType)val3; stringBuilder.Append(" ").Append(((MemberReference)(object)val6.ReturnType).GetPatchFullName()).Append(" *("); if (val6.HasParameters) { for (int k = 0; k < val6.Parameters.Count; k++) { ParameterDefinition val7 = val6.Parameters[k]; if (k > 0) { stringBuilder.Append(","); } if (((ParameterReference)val7).ParameterType.IsSentinel) { stringBuilder.Append("...,"); } stringBuilder.Append(((MemberReference)((ParameterReference)val7).ParameterType).FullName); } } stringBuilder.Append(")"); } } } text = stringBuilder.ToString(); } return text; } FieldReference val8 = (FieldReference)(object)((cap is FieldReference) ? cap : null); if (val8 != null) { return ((MemberReference)(object)val8.FieldType).GetPatchFullName() + " " + ((MemberReference)(object)((MemberReference)val8).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()}"); } 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<GenericParameter> 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<ParameterDefinition> 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<CustomAttribute> 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<MethodReference> 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<Instruction> 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; } public static MethodBody Clone(this MethodBody bo, MethodDefinition m) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Expected O, but got Unknown //IL_005b: 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_00b4: Unknown result type (might be due to invalid IL or missing references) 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<Instruction>)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; })); Enumerator<Instruction> 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)]; } else if (current.Operand is Instruction[] source) { current.Operand = source.Select((Instruction i) => bc.Instructions[bo.Instructions.IndexOf(i)]).ToArray(); } } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } bc.ExceptionHandlers.AddRange(((IEnumerable<ExceptionHandler>)bo.ExceptionHandlers).Select((Func<ExceptionHandler, ExceptionHandler>)((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<VariableDefinition>)bo.Variables).Select((Func<VariableDefinition, VariableDefinition>)((VariableDefinition o) => new VariableDefinition(((VariableReference)o).VariableType)))); m.CustomDebugInformations.AddRange((IEnumerable<CustomDebugInformation>)bo.Method.CustomDebugInformations); m.DebugInformation.SequencePoints.AddRange(((IEnumerable<SequencePoint>)bo.Method.DebugInformation.SequencePoints).Select((Func<SequencePoint, SequencePoint>)((SequencePoint o) => new SequencePoint(((IEnumerable<Instruction>)bc.Instructions).FirstOrDefault((Func<Instruction, bool>)((Instruction i) => i.Offset == o.Offset)), o.Document) { StartLine = o.StartLine, StartColumn = o.StartColumn, EndLine = o.EndLine, EndColumn = o.EndColumn }))); return bc; } 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_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_0009: 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_0027: Expected O, but got Unknown if (provider is GenericParameter && ((MemberReference)(GenericParameter)provider).Name == ((MemberReference)orig).Name) { return (GenericParameter)provider; } Enumerator<GenericParameter> 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; } public static IMetadataTokenProvider Relink(this IMetadataTokenProvider mtp, Relinker relinker, IGenericParameterProvider context) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Expected O, but got Unknown //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Expected O, but got Unknown //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Expected O, but got Unknown //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Expected O, but got Unknown //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Expected O, but got Unknown if (mtp is TypeReference) { return (IMetadataTokenProvider)(object)Extensions.Relink((TypeReference)mtp, relinker, context); } if (mtp is MethodReference) { return Extensions.Relink((MethodReference)mtp, relinker, context); } if (mtp is FieldReference) { return Extensions.Relink((FieldReference)mtp, relinker, context); } if (mtp is ParameterDefinition) { return (IMetadataTokenProvider)(object)Extensions.Relink((ParameterDefinition)mtp, relinker, context); } if (mtp is CallSite) { return (IMetadataTokenProvider)(object)Extensions.Relink((CallSite)mtp, relinker, context); } throw new InvalidOperationException($"MonoMod can't handle metadata token providers of the type {((object)mtp).GetType()}"); } public static TypeReference Relink(this TypeReference type, Relinker relinker, IGenericParameterProvider context) { //IL_027d: Unknown result type (might be due to invalid IL or missing references) //IL_0283: Expected O, but got Unknown //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected O, but got Unknown //IL_01ec: Unknown result type (might be due to invalid IL or missing references) //IL_01f6: Expected O, but got Unknown //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Expected O, but got Unknown //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Expected O, but got Unknown //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Expected O, but got Unknown //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Expected O, but got Unknown //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_00c7: Expected O, but got Unknown //IL_00d0: 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_00e8: Expected O, but got Unknown //IL_0082: 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_00f1: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: Expected O, but got Unknown //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_0156: Unknown result type (might be due to invalid IL or missing references) //IL_015d: Expected O, but got Unknown if (type == null) { return null; } 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<TypeReference> 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); if (val6 == null) { throw new RelinkTargetNotFoundException(string.Format("{0} {1} (context: {2})", "MonoMod relinker failed finding", ((MemberReference)type).FullName, 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; } public static IMetadataTokenProvider Relink(this MethodReference method, Relinker relinker, IGenericParameterProvider context) { //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Expected O, but got Unknown //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_0009: 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_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Expected O, but got Unknown //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Expected O, but got Unknown //IL_002b: 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_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Expected O, but got Unknown //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) //IL_0172: Unknown result type (might be due to invalid IL or missing references) //IL_0178: Expected O, but got Unknown if (method.IsGenericInstance) { GenericInstanceMethod val = (GenericInstanceMethod)method; GenericInstanceMethod val2 = new GenericInstanceMethod((MethodReference)((MethodSpecification)val).ElementMethod.Relink(relinker, context)); Enumerator<TypeReference> 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<GenericParameter> 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(); }
BepInExPack\BepInEx\core\SemanticVersioning.dll
Decompiled 2 months agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text.RegularExpressions; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SemanticVersioning")] [assembly: AssemblyTrademark("")] [assembly: InternalsVisibleTo("SemanticVersioning.Tests, PublicKey=002400000480000094000000060200000024000052534131000400000100010019351d4288017757df1b69b4d0da9a775e6eec498ec93d209d6db4d62e9962476c8da01545cc47335cdc39ba803f4db368ce5f2fdd6cd395196f3328f9039dccdeb3c0f9aece7b8751cd3bc2cb2297d4f463a376eff61b7295b96af9b9faf3eef6005dc967a7a97431cc42cff72e60f05797f3e16186f8fbaf26074e96a2b5e1")] [assembly: ComVisible(false)] [assembly: Guid("a3ff1b6d-68bb-4a0a-a487-858aaa8e3573")] [assembly: AssemblyCopyright("Copyright 2016 Adam Reeve")] [assembly: AssemblyDescription("This library implements the Semantic Versioning 2.0.0 specification and the version range specification used by npm.")] [assembly: AssemblyFileVersion("2.0.2.0")] [assembly: AssemblyInformationalVersion("2.0.2")] [assembly: AssemblyTitle("SemanticVersioning")] [assembly: AssemblyVersion("2.0.2.0")] namespace System { internal static class Tuple { public static Tuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2) { return new Tuple<T1, T2>(item1, item2); } } [Serializable] internal class Tuple<T1, T2> { public readonly T1 Item1; public readonly T2 Item2; private static readonly IEqualityComparer Item1Cpmparer = EqualityComparer<T1>.Default; private static readonly IEqualityComparer<T2> Item2Comparer = EqualityComparer<T2>.Default; public Tuple(T1 _item1, T2 _item2) { Item1 = _item1; Item2 = _item2; } public override string ToString() { return string.Format("<{0},`1,}>", Item1, Item2); } private static bool IsNull(object obj) { return obj == null; } public static bool operator ==(Tuple<T1, T2> a, Tuple<T1, T2> b) { if (IsNull(a) && !IsNull(b)) { return false; } if (!IsNull(a) && IsNull(b)) { return false; } if (IsNull(a) && IsNull(b)) { return true; } if (a.Item1.Equals(b.Item1)) { return a.Item2.Equals(b.Item2); } return false; } public static bool operator !=(Tuple<T1, T2> a, Tuple<T1, T2> b) { return !(a == b); } } } namespace SemanticVersioning { internal class Comparator : IEquatable<Comparator> { public enum Operator { Equal, LessThan, LessThanOrEqual, GreaterThan, GreaterThanOrEqual, GreaterThanOrEqualIncludingPrereleases, LessThanExcludingPrereleases } public readonly Operator ComparatorType; public readonly Version Version; private const string pattern = "\n \\s*\n ([=<>]*) # Comparator type (can be empty)\n \\s*\n ([0-9a-zA-Z\\-\\+\\.\\*]+) # Version (potentially partial version)\n \\s*\n "; public Comparator(string input) { Match match = new Regex(string.Format("^{0}$", "\n \\s*\n ([=<>]*) # Comparator type (can be empty)\n \\s*\n ([0-9a-zA-Z\\-\\+\\.\\*]+) # Version (potentially partial version)\n \\s*\n "), RegexOptions.IgnorePatternWhitespace).Match(input); if (!match.Success) { throw new ArgumentException($"Invalid comparator string: {input}"); } ComparatorType = ParseComparatorType(match.Groups[1].Value); PartialVersion partialVersion = new PartialVersion(match.Groups[2].Value); if (!partialVersion.IsFull()) { switch (ComparatorType) { case Operator.LessThanOrEqual: ComparatorType = Operator.LessThan; if (!partialVersion.Major.HasValue) { ComparatorType = Operator.GreaterThanOrEqual; Version = new Version(0, 0, 0); } else if (!partialVersion.Minor.HasValue) { Version = new Version(partialVersion.Major.Value + 1, 0, 0); } else { Version = new Version(partialVersion.Major.Value, partialVersion.Minor.Value + 1, 0); } break; case Operator.GreaterThan: ComparatorType = Operator.GreaterThanOrEqualIncludingPrereleases; if (!partialVersion.Major.HasValue) { ComparatorType = Operator.LessThan; Version = new Version(0, 0, 0); } else if (!partialVersion.Minor.HasValue) { Version = new Version(partialVersion.Major.Value + 1, 0, 0); } else { Version = new Version(partialVersion.Major.Value, partialVersion.Minor.Value + 1, 0); } break; case Operator.LessThan: ComparatorType = Operator.LessThanExcludingPrereleases; Version = partialVersion.ToZeroVersion(); break; case Operator.GreaterThanOrEqual: ComparatorType = Operator.GreaterThanOrEqualIncludingPrereleases; Version = partialVersion.ToZeroVersion(); break; default: Version = partialVersion.ToZeroVersion(); break; } } else { Version = partialVersion.ToZeroVersion(); } } public Comparator(Operator comparatorType, Version comparatorVersion) { if (comparatorVersion == null) { throw new NullReferenceException("Null comparator version"); } ComparatorType = comparatorType; Version = comparatorVersion; } public static Tuple<int, Comparator> TryParse(string input) { Match match = new Regex(string.Format("^{0}", "\n \\s*\n ([=<>]*) # Comparator type (can be empty)\n \\s*\n ([0-9a-zA-Z\\-\\+\\.\\*]+) # Version (potentially partial version)\n \\s*\n "), RegexOptions.IgnorePatternWhitespace).Match(input); if (!match.Success) { return null; } return Tuple.Create(match.Length, new Comparator(match.Value)); } private static Operator ParseComparatorType(string input) { if (input != null) { if (input == null || input.Length != 0) { switch (input) { case "=": break; case "<": return Operator.LessThan; case "<=": return Operator.LessThanOrEqual; case ">": return Operator.GreaterThan; case ">=": return Operator.GreaterThanOrEqual; default: goto IL_005b; } } return Operator.Equal; } goto IL_005b; IL_005b: throw new ArgumentException($"Invalid comparator type: {input}"); } public bool IsSatisfied(Version version) { switch (ComparatorType) { case Operator.Equal: return version == Version; case Operator.LessThan: return version < Version; case Operator.LessThanOrEqual: return version <= Version; case Operator.GreaterThan: return version > Version; case Operator.GreaterThanOrEqual: return version >= Version; case Operator.GreaterThanOrEqualIncludingPrereleases: if (!(version >= Version)) { if (version.IsPreRelease) { return version.BaseVersion() == Version; } return false; } return true; case Operator.LessThanExcludingPrereleases: if (version < Version) { if (version.IsPreRelease) { return !(version.BaseVersion() == Version); } return true; } return false; default: throw new InvalidOperationException("Comparator type not recognised."); } } public bool Intersects(Comparator other) { Func<Comparator, bool> func = (Comparator c) => c.ComparatorType == Operator.GreaterThan || c.ComparatorType == Operator.GreaterThanOrEqual || c.ComparatorType == Operator.GreaterThanOrEqualIncludingPrereleases; Func<Comparator, bool> func2 = (Comparator c) => c.ComparatorType == Operator.LessThan || c.ComparatorType == Operator.LessThanOrEqual || c.ComparatorType == Operator.LessThanExcludingPrereleases; Func<Comparator, bool> func3 = (Comparator c) => c.ComparatorType == Operator.GreaterThanOrEqual || c.ComparatorType == Operator.GreaterThanOrEqualIncludingPrereleases || c.ComparatorType == Operator.Equal || c.ComparatorType == Operator.LessThanOrEqual; if (Version > other.Version && (func2(this) || func(other))) { return true; } if (Version < other.Version && (func(this) || func2(other))) { return true; } if (Version == other.Version && ((func3(this) && func3(other)) || (func2(this) && func2(other)) || (func(this) && func(other)))) { return true; } return false; } public override string ToString() { string text = null; switch (ComparatorType) { case Operator.Equal: text = "="; break; case Operator.LessThan: case Operator.LessThanExcludingPrereleases: text = "<"; break; case Operator.LessThanOrEqual: text = "<="; break; case Operator.GreaterThan: text = ">"; break; case Operator.GreaterThanOrEqual: case Operator.GreaterThanOrEqualIncludingPrereleases: text = ">="; break; default: throw new InvalidOperationException("Comparator type not recognised."); } return $"{text}{Version}"; } public bool Equals(Comparator other) { if (other == null) { return false; } if (ComparatorType == other.ComparatorType) { return Version == other.Version; } return false; } public override bool Equals(object other) { return Equals(other as Comparator); } public override int GetHashCode() { return new { ComparatorType, Version }.GetHashCode(); } } internal class ComparatorSet : IEquatable<ComparatorSet> { private readonly List<Comparator> _comparators; public ComparatorSet(string spec) { _comparators = new List<Comparator>(); spec = spec.Trim(); if (spec == "") { spec = "*"; } int num = 0; int length = spec.Length; while (num < length) { int num2 = num; Func<string, Tuple<int, Comparator[]>>[] array = new Func<string, Tuple<int, Comparator[]>>[4] { Desugarer.HyphenRange, Desugarer.TildeRange, Desugarer.CaretRange, Desugarer.StarRange }; for (int i = 0; i < array.Length; i++) { Tuple<int, Comparator[]> tuple = array[i](spec.Substring(num)); if (tuple != null) { num += tuple.Item1; _comparators.AddRange(tuple.Item2); } } Tuple<int, Comparator> tuple2 = Comparator.TryParse(spec.Substring(num)); if (tuple2 != null) { num += tuple2.Item1; _comparators.Add(tuple2.Item2); } if (num == num2) { throw new ArgumentException($"Invalid range specification: \"{spec}\""); } } } private ComparatorSet(IEnumerable<Comparator> comparators) { _comparators = comparators.ToList(); } public bool IsSatisfied(Version version, bool includePrerelease = false) { bool flag = _comparators.All((Comparator c) => c.IsSatisfied(version)); if (version.PreRelease != null && !includePrerelease) { if (flag) { return _comparators.Any((Comparator c) => c.Version.PreRelease != null && c.Version.BaseVersion() == version.BaseVersion()); } return false; } return flag; } public ComparatorSet Intersect(ComparatorSet other) { Func<Comparator, bool> predicate = (Comparator c) => c.ComparatorType == Comparator.Operator.GreaterThan || c.ComparatorType == Comparator.Operator.GreaterThanOrEqual || c.ComparatorType == Comparator.Operator.GreaterThanOrEqualIncludingPrereleases; Func<Comparator, bool> predicate2 = (Comparator c) => c.ComparatorType == Comparator.Operator.LessThan || c.ComparatorType == Comparator.Operator.LessThanOrEqual || c.ComparatorType == Comparator.Operator.LessThanExcludingPrereleases; Func<Comparator.Operator, int> operatorOrdering = (Comparator.Operator op) => op switch { Comparator.Operator.LessThanExcludingPrereleases => 0, Comparator.Operator.LessThan => 1, Comparator.Operator.LessThanOrEqual => 2, Comparator.Operator.GreaterThan => 0, Comparator.Operator.GreaterThanOrEqual => 1, Comparator.Operator.GreaterThanOrEqualIncludingPrereleases => 2, _ => throw new ArgumentOutOfRangeException("op", op, "Unexpected comparator operator"), }; Comparator comparator = (from c in _comparators.Concat(other._comparators).Where(predicate) orderby c.Version descending, operatorOrdering(c.ComparatorType) select c).FirstOrDefault(); Comparator comparator2 = (from c in _comparators.Concat(other._comparators).Where(predicate2) orderby c.Version, operatorOrdering(c.ComparatorType) select c).FirstOrDefault(); if (comparator != null && comparator2 != null && !comparator.Intersects(comparator2)) { return null; } List<Version> equalityVersions = (from c in _comparators.Concat(other._comparators) where c.ComparatorType == Comparator.Operator.Equal select c.Version).ToList(); if (equalityVersions.Count > 1 && equalityVersions.Any((Version v) => v != equalityVersions[0])) { return null; } if (equalityVersions.Count > 0) { if (comparator != null && !comparator.IsSatisfied(equalityVersions[0])) { return null; } if (comparator2 != null && !comparator2.IsSatisfied(equalityVersions[0])) { return null; } return new ComparatorSet(new List<Comparator> { new Comparator(Comparator.Operator.Equal, equalityVersions[0]) }); } List<Comparator> list = new List<Comparator>(); if (comparator != null) { list.Add(comparator); } if (comparator2 != null) { list.Add(comparator2); } if (list.Count <= 0) { return null; } return new ComparatorSet(list); } public bool Equals(ComparatorSet other) { if (other == null) { return false; } return new HashSet<Comparator>(_comparators).SetEquals(other._comparators); } public override bool Equals(object other) { return Equals(other as ComparatorSet); } public override string ToString() { return string.Join(" ", _comparators.Select((Comparator c) => c.ToString()).ToArray()); } public override int GetHashCode() { return _comparators.Aggregate(0, (int accum, Comparator next) => accum ^ next.GetHashCode()); } } internal static class Desugarer { private const string versionChars = "[0-9a-zA-Z\\-\\+\\.\\*]"; public static Tuple<int, Comparator[]> TildeRange(string spec) { Match match = new Regex(string.Format("^\\s*~\\s*({0}+)\\s*", "[0-9a-zA-Z\\-\\+\\.\\*]")).Match(spec); if (!match.Success) { return null; } Version version = null; Version version2 = null; PartialVersion partialVersion = new PartialVersion(match.Groups[1].Value); if (partialVersion.Minor.HasValue) { version = partialVersion.ToZeroVersion(); version2 = new Version(partialVersion.Major.Value, partialVersion.Minor.Value + 1, 0); } else { version = partialVersion.ToZeroVersion(); version2 = new Version(partialVersion.Major.Value + 1, 0, 0); } return Tuple.Create(match.Length, MinMaxComparators(version, version2)); } public static Tuple<int, Comparator[]> CaretRange(string spec) { Match match = new Regex(string.Format("^\\s*\\^\\s*({0}+)\\s*", "[0-9a-zA-Z\\-\\+\\.\\*]")).Match(spec); if (!match.Success) { return null; } Version version = null; Version version2 = null; PartialVersion partialVersion = new PartialVersion(match.Groups[1].Value); if (partialVersion.Major.Value > 0) { version = partialVersion.ToZeroVersion(); version2 = new Version(partialVersion.Major.Value + 1, 0, 0); } else if (!partialVersion.Minor.HasValue) { version = partialVersion.ToZeroVersion(); version2 = new Version(partialVersion.Major.Value + 1, 0, 0); } else if (!partialVersion.Patch.HasValue) { version = partialVersion.ToZeroVersion(); version2 = new Version(0, partialVersion.Minor.Value + 1, 0); } else if (partialVersion.Minor > 0) { version = partialVersion.ToZeroVersion(); version2 = new Version(0, partialVersion.Minor.Value + 1, 0); } else { version = partialVersion.ToZeroVersion(); version2 = new Version(0, 0, partialVersion.Patch.Value + 1); } return Tuple.Create(match.Length, MinMaxComparators(version, version2, Comparator.Operator.GreaterThanOrEqualIncludingPrereleases)); } public static Tuple<int, Comparator[]> HyphenRange(string spec) { Match match = new Regex(string.Format("^\\s*({0}+)\\s+\\-\\s+({0}+)\\s*", "[0-9a-zA-Z\\-\\+\\.\\*]")).Match(spec); if (!match.Success) { return null; } PartialVersion partialVersion = null; PartialVersion partialVersion2 = null; try { partialVersion = new PartialVersion(match.Groups[1].Value); partialVersion2 = new PartialVersion(match.Groups[2].Value); } catch (ArgumentException) { return null; } Version minVersion = partialVersion.ToZeroVersion(); Comparator.Operator maxOperator = (partialVersion2.IsFull() ? Comparator.Operator.LessThanOrEqual : Comparator.Operator.LessThanExcludingPrereleases); Version maxVersion = null; if (partialVersion2.Major.HasValue) { maxVersion = ((!partialVersion2.Minor.HasValue) ? new Version(partialVersion2.Major.Value + 1, 0, 0) : (partialVersion2.Patch.HasValue ? partialVersion2.ToZeroVersion() : new Version(partialVersion2.Major.Value, partialVersion2.Minor.Value + 1, 0))); } return Tuple.Create(match.Length, MinMaxComparators(minVersion, maxVersion, Comparator.Operator.GreaterThanOrEqualIncludingPrereleases, maxOperator)); } public static Tuple<int, Comparator[]> StarRange(string spec) { Match match = new Regex(string.Format("^\\s*=?\\s*({0}+)\\s*", "[0-9a-zA-Z\\-\\+\\.\\*]")).Match(spec); if (!match.Success) { return null; } PartialVersion partialVersion = null; try { partialVersion = new PartialVersion(match.Groups[1].Value); } catch (ArgumentException) { return null; } if (partialVersion.IsFull()) { return null; } Version version = null; Version maxVersion = null; if (!partialVersion.Major.HasValue) { version = partialVersion.ToZeroVersion(); } else if (!partialVersion.Minor.HasValue) { version = partialVersion.ToZeroVersion(); maxVersion = new Version(partialVersion.Major.Value + 1, 0, 0); } else { version = partialVersion.ToZeroVersion(); maxVersion = new Version(partialVersion.Major.Value, partialVersion.Minor.Value + 1, 0); } return Tuple.Create(match.Length, MinMaxComparators(version, maxVersion)); } private static Comparator[] MinMaxComparators(Version minVersion, Version maxVersion, Comparator.Operator minOperator = Comparator.Operator.GreaterThanOrEqual, Comparator.Operator maxOperator = Comparator.Operator.LessThanExcludingPrereleases) { Comparator comparator = new Comparator(minOperator, minVersion); if (!(maxVersion == null)) { Comparator comparator2 = new Comparator(maxOperator, maxVersion); return new Comparator[2] { comparator, comparator2 }; } return new Comparator[1] { comparator }; } } internal class PartialVersion { private static Regex regex = new Regex("^\n [v=\\s]*\n (\\d+|[Xx\\*]) # major version\n (\n \\.\n (\\d+|[Xx\\*]) # minor version\n (\n \\.\n (\\d+|[Xx\\*]) # patch version\n (\\-?([0-9A-Za-z\\-\\.]+))? # pre-release version\n (\\+([0-9A-Za-z\\-\\.]+))? # build version (ignored)\n )?\n )?\n $", RegexOptions.IgnorePatternWhitespace); public int? Major { get; set; } public int? Minor { get; set; } public int? Patch { get; set; } public string PreRelease { get; set; } public PartialVersion(string input) { string[] source = new string[3] { "X", "x", "*" }; if (input.Trim() == "") { return; } Match match = regex.Match(input); if (!match.Success) { throw new ArgumentException($"Invalid version string: \"{input}\""); } if (source.Contains(match.Groups[1].Value)) { Major = null; } else { Major = int.Parse(match.Groups[1].Value); } if (match.Groups[2].Success) { if (source.Contains(match.Groups[3].Value)) { Minor = null; } else { Minor = int.Parse(match.Groups[3].Value); } } if (match.Groups[4].Success) { if (source.Contains(match.Groups[5].Value)) { Patch = null; } else { Patch = int.Parse(match.Groups[5].Value); } } if (match.Groups[6].Success) { PreRelease = match.Groups[7].Value; } } public Version ToZeroVersion() { return new Version(Major.GetValueOrDefault(), Minor.GetValueOrDefault(), Patch.GetValueOrDefault(), PreRelease); } public bool IsFull() { if (Major.HasValue && Minor.HasValue) { return Patch.HasValue; } return false; } } internal static class PreReleaseVersion { private class Identifier { public bool IsNumeric { get; set; } public int IntValue { get; set; } public string Value { get; set; } public Identifier(string input) { Value = input; SetNumeric(); } public string Clean() { if (!IsNumeric) { return Value; } return IntValue.ToString(); } private void SetNumeric() { int result; bool flag = int.TryParse(Value, out result); IsNumeric = flag && result >= 0; IntValue = result; } } public static int Compare(string a, string b) { if (a == null && b == null) { return 0; } if (a == null) { return 1; } if (b == null) { return -1; } foreach (int item in IdentifierComparisons(Identifiers(a), Identifiers(b))) { if (item != 0) { return item; } } return 0; } public static string Clean(string input) { IEnumerable<string> source = from i in Identifiers(input) select i.Clean(); return string.Join(".", source.ToArray()); } private static IEnumerable<Identifier> Identifiers(string input) { string[] array = input.Split(new char[1] { '.' }); foreach (string input2 in array) { yield return new Identifier(input2); } } private static IEnumerable<int> IdentifierComparisons(IEnumerable<Identifier> aIdentifiers, IEnumerable<Identifier> bIdentifiers) { foreach (Tuple<Identifier, Identifier> item3 in ZipIdentifiers(aIdentifiers, bIdentifiers)) { Identifier item = item3.Item1; Identifier item2 = item3.Item2; if (item == item2) { yield return 0; } else if (item == null) { yield return -1; } else if (item2 == null) { yield return 1; } else if (item.IsNumeric && item2.IsNumeric) { yield return item.IntValue.CompareTo(item2.IntValue); } else if (!item.IsNumeric && !item2.IsNumeric) { yield return string.CompareOrdinal(item.Value, item2.Value); } else if (item.IsNumeric && !item2.IsNumeric) { yield return -1; } else { yield return 1; } } } private static IEnumerable<Tuple<Identifier, Identifier>> ZipIdentifiers(IEnumerable<Identifier> first, IEnumerable<Identifier> second) { using IEnumerator<Identifier> ie1 = first.GetEnumerator(); using IEnumerator<Identifier> ie2 = second.GetEnumerator(); while (ie1.MoveNext()) { if (ie2.MoveNext()) { yield return Tuple.Create(ie1.Current, ie2.Current); } else { yield return Tuple.Create<Identifier, Identifier>(ie1.Current, null); } } while (ie2.MoveNext()) { yield return Tuple.Create<Identifier, Identifier>(null, ie2.Current); } } } public class Range : IEquatable<Range> { private readonly ComparatorSet[] _comparatorSets; private readonly string _rangeSpec; public Range(string rangeSpec, bool loose = false) { _rangeSpec = rangeSpec; string[] source = rangeSpec.Split(new string[1] { "||" }, StringSplitOptions.None); _comparatorSets = source.Select((string s) => new ComparatorSet(s)).ToArray(); } private Range(IEnumerable<ComparatorSet> comparatorSets) { _comparatorSets = comparatorSets.ToArray(); _rangeSpec = string.Join(" || ", _comparatorSets.Select((ComparatorSet cs) => cs.ToString()).ToArray()); } public bool IsSatisfied(Version version, bool includePrerelease = false) { return _comparatorSets.Any((ComparatorSet s) => s.IsSatisfied(version, includePrerelease)); } public bool IsSatisfied(string versionString, bool loose = false, bool includePrerelease = false) { try { Version version = new Version(versionString, loose); return IsSatisfied(version, includePrerelease); } catch (ArgumentException) { return false; } } public IEnumerable<Version> Satisfying(IEnumerable<Version> versions, bool includePrerelease = false) { return versions.Where((Version v) => IsSatisfied(v, includePrerelease)); } public IEnumerable<string> Satisfying(IEnumerable<string> versions, bool loose = false, bool includePrerelease = false) { return versions.Where((string v) => IsSatisfied(v, loose, includePrerelease)); } public Version MaxSatisfying(IEnumerable<Version> versions, bool includePrerelease = false) { return Satisfying(versions, includePrerelease).Max(); } public string MaxSatisfying(IEnumerable<string> versionStrings, bool loose = false, bool includePrerelease = false) { IEnumerable<Version> versions = ValidVersions(versionStrings, loose); Version version = MaxSatisfying(versions, includePrerelease); if (!(version == null)) { return version.ToString(); } return null; } public Range Intersect(Range other) { List<ComparatorSet> list = (from cs in _comparatorSets.SelectMany((ComparatorSet thisCs) => other._comparatorSets.Select(thisCs.Intersect)) where cs != null select cs).ToList(); if (list.Count == 0) { return new Range("<0.0.0"); } return new Range(list); } public override string ToString() { return _rangeSpec; } public bool Equals(Range other) { if ((object)other == null) { return false; } return new HashSet<ComparatorSet>(_comparatorSets).SetEquals(other._comparatorSets); } public override bool Equals(object other) { return Equals(other as Range); } public static bool operator ==(Range a, Range b) { return a?.Equals(b) ?? ((object)b == null); } public static bool operator !=(Range a, Range b) { return !(a == b); } public override int GetHashCode() { return _comparatorSets.Aggregate(0, (int accum, ComparatorSet next) => accum ^ next.GetHashCode()); } public static bool IsSatisfied(string rangeSpec, string versionString, bool loose = false, bool includePrerelease = false) { return new Range(rangeSpec).IsSatisfied(versionString, loose, includePrerelease); } public static IEnumerable<string> Satisfying(string rangeSpec, IEnumerable<string> versions, bool loose = false, bool includePrerelease = false) { return new Range(rangeSpec).Satisfying(versions, loose, includePrerelease); } public static string MaxSatisfying(string rangeSpec, IEnumerable<string> versionStrings, bool loose = false, bool includePrerelease = false) { return new Range(rangeSpec).MaxSatisfying(versionStrings, loose: false, includePrerelease); } public static Range Parse(string rangeSpec, bool loose = false) { return new Range(rangeSpec, loose); } public static bool TryParse(string rangeSpec, out Range result) { return TryParse(rangeSpec, loose: false, out result); } public static bool TryParse(string rangeSpec, bool loose, out Range result) { try { result = Parse(rangeSpec, loose); return true; } catch { result = null; return false; } } private IEnumerable<Version> ValidVersions(IEnumerable<string> versionStrings, bool loose) { foreach (string versionString in versionStrings) { Version version = null; try { version = new Version(versionString, loose); } catch (ArgumentException) { } if (version != null) { yield return version; } } } } public class Version : IComparable<Version>, IComparable, IEquatable<Version> { private readonly string _inputString; private readonly int _major; private readonly int _minor; private readonly int _patch; private readonly string _preRelease; private readonly string _build; private static Regex strictRegex = new Regex("^\n \\s*v?\n ([0-9]|[1-9][0-9]+) # major version\n \\.\n ([0-9]|[1-9][0-9]+) # minor version\n \\.\n ([0-9]|[1-9][0-9]+) # patch version\n (\\-([0-9A-Za-z\\-\\.]+))? # pre-release version\n (\\+([0-9A-Za-z\\-\\.]+))? # build metadata\n \\s*\n $", RegexOptions.IgnorePatternWhitespace); private static Regex looseRegex = new Regex("^\n [v=\\s]*\n (\\d+) # major version\n \\.\n (\\d+) # minor version\n \\.\n (\\d+) # patch version\n (\\-?([0-9A-Za-z\\-\\.]+))? # pre-release version\n (\\+([0-9A-Za-z\\-\\.]+))? # build metadata\n \\s*\n $", RegexOptions.IgnorePatternWhitespace); public int Major => _major; public int Minor => _minor; public int Patch => _patch; public string PreRelease => _preRelease; public string Build => _build; public bool IsPreRelease => !string.IsNullOrEmpty(_preRelease); public Version(string input, bool loose = false) { _inputString = input; Match match = (loose ? looseRegex : strictRegex).Match(input); if (!match.Success) { throw new ArgumentException($"Invalid version string: {input}"); } _major = int.Parse(match.Groups[1].Value); _minor = int.Parse(match.Groups[2].Value); _patch = int.Parse(match.Groups[3].Value); if (match.Groups[4].Success) { string value = match.Groups[5].Value; string text = PreReleaseVersion.Clean(value); if (!loose && value != text) { throw new ArgumentException($"Invalid pre-release version: {value}"); } _preRelease = text; } if (match.Groups[6].Success) { _build = match.Groups[7].Value; } } public Version(int major, int minor, int patch, string preRelease = null, string build = null) { _major = major; _minor = minor; _patch = patch; _preRelease = preRelease; _build = build; } public Version BaseVersion() { return new Version(Major, Minor, Patch); } public override string ToString() { return _inputString ?? Clean(); } public string Clean() { string text = ((PreRelease == null) ? "" : $"-{PreReleaseVersion.Clean(PreRelease)}"); string text2 = ((Build == null) ? "" : $"+{Build}"); return $"{Major}.{Minor}.{Patch}{text}{text2}"; } public override int GetHashCode() { int num = 17; num = num * 23 + Major.GetHashCode(); num = num * 23 + Minor.GetHashCode(); num = num * 23 + Patch.GetHashCode(); if (PreRelease != null) { num = num * 23 + PreRelease.GetHashCode(); } return num; } public bool Equals(Version other) { if ((object)other == null) { return false; } return CompareTo(other) == 0; } public int CompareTo(object obj) { if (obj != null) { if (obj is Version other) { return CompareTo(other); } throw new ArgumentException("Object is not a Version"); } return 1; } public int CompareTo(Version other) { if ((object)other == null) { return 1; } foreach (int item in PartComparisons(other)) { if (item != 0) { return item; } } return PreReleaseVersion.Compare(PreRelease, other.PreRelease); } private IEnumerable<int> PartComparisons(Version other) { yield return Major.CompareTo(other.Major); yield return Minor.CompareTo(other.Minor); yield return Patch.CompareTo(other.Patch); } public override bool Equals(object other) { return Equals(other as Version); } public static Version Parse(string input, bool loose = false) { return new Version(input, loose); } public static bool TryParse(string input, out Version result) { return TryParse(input, loose: false, out result); } public static bool TryParse(string input, bool loose, out Version result) { try { result = Parse(input, loose); return true; } catch { result = null; return false; } } public static bool operator ==(Version a, Version b) { return a?.Equals(b) ?? ((object)b == null); } public static bool operator !=(Version a, Version b) { return !(a == b); } public static bool operator >(Version a, Version b) { if ((object)a == null) { return false; } return a.CompareTo(b) > 0; } public static bool operator >=(Version a, Version b) { if ((object)a == null) { if ((object)b != null) { return false; } return true; } return a.CompareTo(b) >= 0; } public static bool operator <(Version a, Version b) { if ((object)a == null) { if ((object)b != null) { return true; } return false; } return a.CompareTo(b) < 0; } public static bool operator <=(Version a, Version b) { if ((object)a == null) { return true; } return a.CompareTo(b) <= 0; } } }
BepInExPack\unstripped_corlib\mscorlib.dll
Decompiled 2 months ago
The result has been truncated due to the large size, download it to view full contents!
#define CONTRACTS_FULL using System; using System.Buffers; using System.Buffers.Binary; using System.Buffers.Text; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Configuration.Assemblies; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Diagnostics.SymbolStore; using System.Diagnostics.Tracing; using System.Globalization; using System.IO; using System.IO.Enumeration; using System.Numerics; using System.Numerics.Hashing; using System.Reflection; using System.Reflection.Emit; using System.Resources; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.ExceptionServices; using System.Runtime.Hosting; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Runtime.InteropServices.WindowsRuntime; using System.Runtime.Remoting; using System.Runtime.Remoting.Activation; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Contexts; using System.Runtime.Remoting.Lifetime; using System.Runtime.Remoting.Messaging; using System.Runtime.Remoting.Metadata; using System.Runtime.Remoting.Proxies; using System.Runtime.Remoting.Services; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Versioning; using System.Security; using System.Security.AccessControl; using System.Security.Claims; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Security.Permissions; using System.Security.Policy; using System.Security.Principal; using System.Security.Util; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Sources; using Internal.Cryptography; using Internal.Runtime.Augments; using Internal.Threading.Tasks.Tracing; using Microsoft.CodeAnalysis; using Microsoft.Win32; using Microsoft.Win32.SafeHandles; using Mono; using Mono.Globalization.Unicode; using Mono.Interop; using Mono.Math; using Mono.Math.Prime; using Mono.Math.Prime.Generator; using Mono.Security; using Mono.Security.Cryptography; using Mono.Xml; using Unity; [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("mscorlib.dll")] [assembly: AssemblyDescription("mscorlib.dll")] [assembly: AssemblyDefaultAlias("mscorlib.dll")] [assembly: AssemblyCompany("Mono development team")] [assembly: AssemblyProduct("Mono Common Language Infrastructure")] [assembly: AssemblyCopyright("(c) Various Mono authors")] [assembly: AssemblyInformationalVersion("4.6.57.0")] [assembly: SatelliteContractVersion("4.0.0.0")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: CLSCompliant(true)] [assembly: AssemblyDelaySign(true)] [assembly: AssemblyKeyFile("../ecma.pub")] [assembly: ComCompatibleVersion(1, 0, 3300, 0)] [assembly: AllowPartiallyTrustedCallers] [assembly: AssemblyFileVersion("4.6.57.0")] [assembly: ComVisible(false)] [assembly: CompilationRelaxations(CompilationRelaxations.NoStringInterning)] [assembly: DefaultDependency(LoadHint.Always)] [assembly: StringFreezing] [assembly: InternalsVisibleTo("System, PublicKey=00000000000000000400000000000000")] [assembly: InternalsVisibleTo("System.Core, PublicKey=00000000000000000400000000000000")] [assembly: InternalsVisibleTo("System.Security, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] [assembly: InternalsVisibleTo("System.Runtime.WindowsRuntime, PublicKey=00000000000000000400000000000000")] [assembly: InternalsVisibleTo("System.Runtime.WindowsRuntime.UI.Xaml, PublicKey=00000000000000000400000000000000")] [assembly: InternalsVisibleTo("System.Net.Http, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] [assembly: Guid("BED7F4EA-1A96-11D2-8F08-00A0C9A6186D")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("4.0.0.0")] [module: UnverifiableCode] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] internal sealed class IsUnmanagedAttribute : Attribute { } } internal static class Interop { internal static class Kernel32 { [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct WIN32_FIND_DATA { internal uint dwFileAttributes; internal FILE_TIME ftCreationTime; internal FILE_TIME ftLastAccessTime; internal FILE_TIME ftLastWriteTime; internal uint nFileSizeHigh; internal uint nFileSizeLow; internal uint dwReserved0; internal uint dwReserved1; private unsafe fixed char _cFileName[260]; private unsafe fixed char _cAlternateFileName[14]; internal unsafe ReadOnlySpan<char> cFileName { get { fixed (char* pointer = _cFileName) { return new ReadOnlySpan<char>(pointer, 260); } } } } internal struct REG_TZI_FORMAT { internal int Bias; internal int StandardBias; internal int DaylightBias; internal SYSTEMTIME StandardDate; internal SYSTEMTIME DaylightDate; internal REG_TZI_FORMAT(in TIME_ZONE_INFORMATION tzi) { Bias = tzi.Bias; StandardDate = tzi.StandardDate; StandardBias = tzi.StandardBias; DaylightDate = tzi.DaylightDate; DaylightBias = tzi.DaylightBias; } } internal struct SYSTEMTIME { internal ushort Year; internal ushort Month; internal ushort DayOfWeek; internal ushort Day; internal ushort Hour; internal ushort Minute; internal ushort Second; internal ushort Milliseconds; internal bool Equals(in SYSTEMTIME other) { if (Year == other.Year && Month == other.Month && DayOfWeek == other.DayOfWeek && Day == other.Day && Hour == other.Hour && Minute == other.Minute && Second == other.Second) { return Milliseconds == other.Milliseconds; } return false; } } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct TIME_DYNAMIC_ZONE_INFORMATION { internal int Bias; internal unsafe fixed char StandardName[32]; internal SYSTEMTIME StandardDate; internal int StandardBias; internal unsafe fixed char DaylightName[32]; internal SYSTEMTIME DaylightDate; internal int DaylightBias; internal unsafe fixed char TimeZoneKeyName[128]; internal byte DynamicDaylightTimeDisabled; internal unsafe string GetTimeZoneKeyName() { fixed (char* value = TimeZoneKeyName) { return new string(value); } } } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct TIME_ZONE_INFORMATION { internal int Bias; internal unsafe fixed char StandardName[32]; internal SYSTEMTIME StandardDate; internal int StandardBias; internal unsafe fixed char DaylightName[32]; internal SYSTEMTIME DaylightDate; internal int DaylightBias; internal unsafe TIME_ZONE_INFORMATION(in TIME_DYNAMIC_ZONE_INFORMATION dtzi) { fixed (TIME_ZONE_INFORMATION* ptr = &this) { fixed (TIME_DYNAMIC_ZONE_INFORMATION* ptr2 = &dtzi) { *ptr = *(TIME_ZONE_INFORMATION*)ptr2; } } } internal unsafe string GetStandardName() { fixed (char* value = StandardName) { return new string(value); } } internal unsafe string GetDaylightName() { fixed (char* value = DaylightName) { return new string(value); } } } internal enum FILE_INFO_BY_HANDLE_CLASS : uint { FileBasicInfo, FileStandardInfo, FileNameInfo, FileRenameInfo, FileDispositionInfo, FileAllocationInfo, FileEndOfFileInfo, FileStreamInfo, FileCompressionInfo, FileAttributeTagInfo, FileIdBothDirectoryInfo, FileIdBothDirectoryRestartInfo, FileIoPriorityHintInfo, FileRemoteProtocolInfo, FileFullDirectoryInfo, FileFullDirectoryRestartInfo } internal struct FILE_TIME { internal uint dwLowDateTime; internal uint dwHighDateTime; internal FILE_TIME(long fileTime) { dwLowDateTime = (uint)fileTime; dwHighDateTime = (uint)(fileTime >> 32); } internal long ToTicks() { return (long)(((ulong)dwHighDateTime << 32) + dwLowDateTime); } internal DateTime ToDateTimeUtc() { return DateTime.FromFileTimeUtc(ToTicks()); } internal DateTimeOffset ToDateTimeOffset() { return DateTimeOffset.FromFileTime(ToTicks()); } } internal enum FINDEX_INFO_LEVELS : uint { FindExInfoStandard, FindExInfoBasic, FindExInfoMaxInfoLevel } internal enum FINDEX_SEARCH_OPS : uint { FindExSearchNameMatch, FindExSearchLimitToDirectories, FindExSearchLimitToDevices, FindExSearchMaxSearchOp } internal class FileAttributes { internal const int FILE_ATTRIBUTE_NORMAL = 128; internal const int FILE_ATTRIBUTE_READONLY = 1; internal const int FILE_ATTRIBUTE_DIRECTORY = 16; internal const int FILE_ATTRIBUTE_REPARSE_POINT = 1024; } internal class IOReparseOptions { internal const uint IO_REPARSE_TAG_FILE_PLACEHOLDER = 2147483669u; internal const uint IO_REPARSE_TAG_MOUNT_POINT = 2684354563u; } internal class FileOperations { internal const int OPEN_EXISTING = 3; internal const int COPY_FILE_FAIL_IF_EXISTS = 1; internal const int FILE_ACTION_ADDED = 1; internal const int FILE_ACTION_REMOVED = 2; internal const int FILE_ACTION_MODIFIED = 3; internal const int FILE_ACTION_RENAMED_OLD_NAME = 4; internal const int FILE_ACTION_RENAMED_NEW_NAME = 5; internal const int FILE_FLAG_BACKUP_SEMANTICS = 33554432; internal const int FILE_FLAG_FIRST_PIPE_INSTANCE = 524288; internal const int FILE_FLAG_OVERLAPPED = 1073741824; internal const int FILE_LIST_DIRECTORY = 1; } internal enum GET_FILEEX_INFO_LEVELS : uint { GetFileExInfoStandard, GetFileExMaxInfoLevel } internal class GenericOperations { internal const int GENERIC_READ = int.MinValue; internal const int GENERIC_WRITE = 1073741824; } internal struct SECURITY_ATTRIBUTES { internal uint nLength; internal IntPtr lpSecurityDescriptor; internal BOOL bInheritHandle; } internal struct FILE_BASIC_INFO { internal long CreationTime; internal long LastAccessTime; internal long LastWriteTime; internal long ChangeTime; internal uint FileAttributes; } internal struct WIN32_FILE_ATTRIBUTE_DATA { internal int dwFileAttributes; internal FILE_TIME ftCreationTime; internal FILE_TIME ftLastAccessTime; internal FILE_TIME ftLastWriteTime; internal uint nFileSizeHigh; internal uint nFileSizeLow; internal void PopulateFrom(ref WIN32_FIND_DATA findData) { dwFileAttributes = (int)findData.dwFileAttributes; ftCreationTime = findData.ftCreationTime; ftLastAccessTime = findData.ftLastAccessTime; ftLastWriteTime = findData.ftLastWriteTime; nFileSizeHigh = findData.nFileSizeHigh; nFileSizeLow = findData.nFileSizeLow; } } internal const int LOAD_LIBRARY_AS_DATAFILE = 2; internal const int MAX_PATH = 260; internal const uint MUI_PREFERRED_UI_LANGUAGES = 16u; internal const uint TIME_ZONE_ID_INVALID = uint.MaxValue; internal const uint SEM_FAILCRITICALERRORS = 1u; private const int FORMAT_MESSAGE_IGNORE_INSERTS = 512; private const int FORMAT_MESSAGE_FROM_HMODULE = 2048; private const int FORMAT_MESSAGE_FROM_SYSTEM = 4096; private const int FORMAT_MESSAGE_ARGUMENT_ARRAY = 8192; private const int ERROR_INSUFFICIENT_BUFFER = 122; private const int InitialBufferSize = 256; private const int BufferSizeIncreaseFactor = 4; private const int MaxAllowedBufferSize = 66560; internal const int REPLACEFILE_IGNORE_MERGE_ERRORS = 2; internal static int CopyFile(string src, string dst, bool failIfExists) { int flags = (failIfExists ? 1 : 0); int cancel = 0; if (!CopyFileEx(src, dst, IntPtr.Zero, IntPtr.Zero, ref cancel, flags)) { return Marshal.GetLastWin32Error(); } return 0; } [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "DeleteVolumeMountPointW", SetLastError = true)] internal static extern bool DeleteVolumeMountPointPrivate(string mountPoint); internal static bool DeleteVolumeMountPoint(string mountPoint) { mountPoint = PathInternal.EnsureExtendedPrefixIfNeeded(mountPoint); return DeleteVolumeMountPointPrivate(mountPoint); } [DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] internal static extern bool FreeLibrary(IntPtr hModule); [DllImport("kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "LoadLibraryExW", SetLastError = true)] internal static extern SafeLibraryHandle LoadLibraryEx(string libFilename, IntPtr reserved, int flags); [DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] internal static extern bool GetFileMUIPath(uint flags, string filePath, [Out] StringBuilder language, ref int languageLength, [Out] StringBuilder fileMuiPath, ref int fileMuiPathLength, ref long enumerator); [DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] internal static extern uint GetDynamicTimeZoneInformation(out TIME_DYNAMIC_ZONE_INFORMATION pTimeZoneInformation); [DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] internal static extern uint GetTimeZoneInformation(out TIME_ZONE_INFORMATION lpTimeZoneInformation); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CloseHandle(IntPtr handle); [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "CopyFileExW", SetLastError = true)] private static extern bool CopyFileExPrivate(string src, string dst, IntPtr progressRoutine, IntPtr progressData, ref int cancel, int flags); internal static bool CopyFileEx(string src, string dst, IntPtr progressRoutine, IntPtr progressData, ref int cancel, int flags) { src = PathInternal.EnsureExtendedPrefixIfNeeded(src); dst = PathInternal.EnsureExtendedPrefixIfNeeded(dst); return CopyFileExPrivate(src, dst, progressRoutine, progressData, ref cancel, flags); } [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "CreateDirectoryW", SetLastError = true)] private static extern bool CreateDirectoryPrivate(string path, ref SECURITY_ATTRIBUTES lpSecurityAttributes); internal static bool CreateDirectory(string path, ref SECURITY_ATTRIBUTES lpSecurityAttributes) { path = PathInternal.EnsureExtendedPrefix(path); return CreateDirectoryPrivate(path, ref lpSecurityAttributes); } [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "CreateFileW", ExactSpelling = true, SetLastError = true)] private unsafe static extern IntPtr CreateFilePrivate(string lpFileName, int dwDesiredAccess, FileShare dwShareMode, SECURITY_ATTRIBUTES* securityAttrs, FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile); internal unsafe static SafeFileHandle CreateFile(string lpFileName, int dwDesiredAccess, FileShare dwShareMode, ref SECURITY_ATTRIBUTES securityAttrs, FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile) { lpFileName = PathInternal.EnsureExtendedPrefixIfNeeded(lpFileName); fixed (SECURITY_ATTRIBUTES* securityAttrs2 = &securityAttrs) { IntPtr intPtr = CreateFilePrivate(lpFileName, dwDesiredAccess, dwShareMode, securityAttrs2, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); try { return new SafeFileHandle(intPtr, ownsHandle: true); } catch { CloseHandle(intPtr); throw; } } } internal static SafeFileHandle CreateFile(string lpFileName, int dwDesiredAccess, FileShare dwShareMode, FileMode dwCreationDisposition, int dwFlagsAndAttributes) { IntPtr intPtr = CreateFile_IntPtr(lpFileName, dwDesiredAccess, dwShareMode, dwCreationDisposition, dwFlagsAndAttributes); try { return new SafeFileHandle(intPtr, ownsHandle: true); } catch { CloseHandle(intPtr); throw; } } internal unsafe static IntPtr CreateFile_IntPtr(string lpFileName, int dwDesiredAccess, FileShare dwShareMode, FileMode dwCreationDisposition, int dwFlagsAndAttributes) { lpFileName = PathInternal.EnsureExtendedPrefixIfNeeded(lpFileName); return CreateFilePrivate(lpFileName, dwDesiredAccess, dwShareMode, null, dwCreationDisposition, dwFlagsAndAttributes, IntPtr.Zero); } [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "DeleteFileW", SetLastError = true)] private static extern bool DeleteFilePrivate(string path); internal static bool DeleteFile(string path) { path = PathInternal.EnsureExtendedPrefixIfNeeded(path); return DeleteFilePrivate(path); } [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "FindFirstFileExW", SetLastError = true)] private static extern SafeFindHandle FindFirstFileExPrivate(string lpFileName, FINDEX_INFO_LEVELS fInfoLevelId, ref WIN32_FIND_DATA lpFindFileData, FINDEX_SEARCH_OPS fSearchOp, IntPtr lpSearchFilter, int dwAdditionalFlags); internal static SafeFindHandle FindFirstFile(string fileName, ref WIN32_FIND_DATA data) { fileName = PathInternal.EnsureExtendedPrefixIfNeeded(fileName); return FindFirstFileExPrivate(fileName, FINDEX_INFO_LEVELS.FindExInfoBasic, ref data, FINDEX_SEARCH_OPS.FindExSearchNameMatch, IntPtr.Zero, 0); } [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "FindNextFileW", SetLastError = true)] internal static extern bool FindNextFile(SafeFindHandle hndFindFile, ref WIN32_FIND_DATA lpFindFileData); [DllImport("kernel32.dll", BestFitMapping = true, CharSet = CharSet.Unicode, EntryPoint = "FormatMessageW", SetLastError = true)] private unsafe static extern int FormatMessage(int dwFlags, IntPtr lpSource, uint dwMessageId, int dwLanguageId, char* lpBuffer, int nSize, IntPtr[] arguments); internal static string GetMessage(int errorCode) { return GetMessage(IntPtr.Zero, errorCode); } internal static string GetMessage(IntPtr moduleHandle, int errorCode) { Span<char> buffer = stackalloc char[256]; do { if (TryGetErrorMessage(moduleHandle, errorCode, buffer, out var errorMsg)) { return errorMsg; } buffer = new char[buffer.Length * 4]; } while (buffer.Length < 66560); return $"Unknown error (0x{errorCode:x})"; } private unsafe static bool TryGetErrorMessage(IntPtr moduleHandle, int errorCode, Span<char> buffer, out string errorMsg) { int num = 12800; if (moduleHandle != IntPtr.Zero) { num |= 0x800; } int num2; fixed (char* lpBuffer = &MemoryMarshal.GetReference(buffer)) { num2 = FormatMessage(num, moduleHandle, (uint)errorCode, 0, lpBuffer, buffer.Length, null); } if (num2 != 0) { int num3; for (num3 = num2; num3 > 0; num3--) { char c = buffer[num3 - 1]; if (c > ' ' && c != '.') { break; } } errorMsg = buffer.Slice(0, num3).ToString(); } else { if (Marshal.GetLastWin32Error() == 122) { errorMsg = ""; return false; } errorMsg = $"Unknown error (0x{errorCode:x})"; } return true; } [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "GetFileAttributesExW", SetLastError = true)] private static extern bool GetFileAttributesExPrivate(string name, GET_FILEEX_INFO_LEVELS fileInfoLevel, ref WIN32_FILE_ATTRIBUTE_DATA lpFileInformation); internal static bool GetFileAttributesEx(string name, GET_FILEEX_INFO_LEVELS fileInfoLevel, ref WIN32_FILE_ATTRIBUTE_DATA lpFileInformation) { name = PathInternal.EnsureExtendedPrefixIfNeeded(name); return GetFileAttributesExPrivate(name, fileInfoLevel, ref lpFileInformation); } [DllImport("kernel32.dll", SetLastError = true)] internal static extern int GetLogicalDrives(); [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "MoveFileExW", SetLastError = true)] private static extern bool MoveFileExPrivate(string src, string dst, uint flags); internal static bool MoveFile(string src, string dst) { src = PathInternal.EnsureExtendedPrefixIfNeeded(src); dst = PathInternal.EnsureExtendedPrefixIfNeeded(dst); return MoveFileExPrivate(src, dst, 2u); } [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RemoveDirectoryW", SetLastError = true)] private static extern bool RemoveDirectoryPrivate(string path); internal static bool RemoveDirectory(string path) { path = PathInternal.EnsureExtendedPrefixIfNeeded(path); return RemoveDirectoryPrivate(path); } [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "ReplaceFileW", SetLastError = true)] private static extern bool ReplaceFilePrivate(string replacedFileName, string replacementFileName, string backupFileName, int dwReplaceFlags, IntPtr lpExclude, IntPtr lpReserved); internal static bool ReplaceFile(string replacedFileName, string replacementFileName, string backupFileName, int dwReplaceFlags, IntPtr lpExclude, IntPtr lpReserved) { replacedFileName = PathInternal.EnsureExtendedPrefixIfNeeded(replacedFileName); replacementFileName = PathInternal.EnsureExtendedPrefixIfNeeded(replacementFileName); backupFileName = PathInternal.EnsureExtendedPrefixIfNeeded(backupFileName); return ReplaceFilePrivate(replacedFileName, replacementFileName, backupFileName, dwReplaceFlags, lpExclude, lpReserved); } [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "SetFileAttributesW", SetLastError = true)] private static extern bool SetFileAttributesPrivate(string name, int attr); internal static bool SetFileAttributes(string name, int attr) { name = PathInternal.EnsureExtendedPrefixIfNeeded(name); return SetFileAttributesPrivate(name, attr); } [DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)] internal static extern bool SetFileInformationByHandle(SafeFileHandle hFile, FILE_INFO_BY_HANDLE_CLASS FileInformationClass, ref FILE_BASIC_INFO lpFileInformation, uint dwBufferSize); internal unsafe static bool SetFileTime(SafeFileHandle hFile, long creationTime = -1L, long lastAccessTime = -1L, long lastWriteTime = -1L, long changeTime = -1L, uint fileAttributes = 0u) { FILE_BASIC_INFO fILE_BASIC_INFO = default(FILE_BASIC_INFO); fILE_BASIC_INFO.CreationTime = creationTime; fILE_BASIC_INFO.LastAccessTime = lastAccessTime; fILE_BASIC_INFO.LastWriteTime = lastWriteTime; fILE_BASIC_INFO.ChangeTime = changeTime; fILE_BASIC_INFO.FileAttributes = fileAttributes; FILE_BASIC_INFO lpFileInformation = fILE_BASIC_INFO; return SetFileInformationByHandle(hFile, FILE_INFO_BY_HANDLE_CLASS.FileBasicInfo, ref lpFileInformation, (uint)sizeof(FILE_BASIC_INFO)); } [DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)] internal static extern bool SetThreadErrorMode(uint dwNewMode, out uint lpOldMode); } internal class BCrypt { internal enum NTSTATUS : uint { STATUS_SUCCESS = 0u, STATUS_NOT_FOUND = 3221226021u, STATUS_INVALID_PARAMETER = 3221225485u, STATUS_NO_MEMORY = 3221225495u } internal const int BCRYPT_USE_SYSTEM_PREFERRED_RNG = 2; [DllImport("BCrypt.dll", CharSet = CharSet.Unicode)] internal unsafe static extern NTSTATUS BCryptGenRandom(IntPtr hAlgorithm, byte* pbBuffer, int cbBuffer, int dwFlags); } internal class User32 { [DllImport("user32.dll", CharSet = CharSet.Unicode, EntryPoint = "LoadStringW", SetLastError = true)] internal static extern int LoadString(SafeLibraryHandle handle, int id, [Out] StringBuilder buffer, int bufferLength); } internal enum BOOL { FALSE, TRUE } internal enum BOOLEAN : byte { FALSE, TRUE } internal class Errors { internal const int ERROR_SUCCESS = 0; internal const int ERROR_INVALID_FUNCTION = 1; internal const int ERROR_FILE_NOT_FOUND = 2; internal const int ERROR_PATH_NOT_FOUND = 3; internal const int ERROR_ACCESS_DENIED = 5; internal const int ERROR_INVALID_HANDLE = 6; internal const int ERROR_NOT_ENOUGH_MEMORY = 8; internal const int ERROR_INVALID_DATA = 13; internal const int ERROR_INVALID_DRIVE = 15; internal const int ERROR_NO_MORE_FILES = 18; internal const int ERROR_NOT_READY = 21; internal const int ERROR_BAD_COMMAND = 22; internal const int ERROR_BAD_LENGTH = 24; internal const int ERROR_SHARING_VIOLATION = 32; internal const int ERROR_LOCK_VIOLATION = 33; internal const int ERROR_HANDLE_EOF = 38; internal const int ERROR_BAD_NETPATH = 53; internal const int ERROR_BAD_NET_NAME = 67; internal const int ERROR_FILE_EXISTS = 80; internal const int ERROR_INVALID_PARAMETER = 87; internal const int ERROR_BROKEN_PIPE = 109; internal const int ERROR_SEM_TIMEOUT = 121; internal const int ERROR_CALL_NOT_IMPLEMENTED = 120; internal const int ERROR_INSUFFICIENT_BUFFER = 122; internal const int ERROR_INVALID_NAME = 123; internal const int ERROR_NEGATIVE_SEEK = 131; internal const int ERROR_DIR_NOT_EMPTY = 145; internal const int ERROR_BAD_PATHNAME = 161; internal const int ERROR_LOCK_FAILED = 167; internal const int ERROR_BUSY = 170; internal const int ERROR_ALREADY_EXISTS = 183; internal const int ERROR_BAD_EXE_FORMAT = 193; internal const int ERROR_ENVVAR_NOT_FOUND = 203; internal const int ERROR_FILENAME_EXCED_RANGE = 206; internal const int ERROR_EXE_MACHINE_TYPE_MISMATCH = 216; internal const int ERROR_PIPE_BUSY = 231; internal const int ERROR_NO_DATA = 232; internal const int ERROR_PIPE_NOT_CONNECTED = 233; internal const int ERROR_MORE_DATA = 234; internal const int ERROR_NO_MORE_ITEMS = 259; internal const int ERROR_DIRECTORY = 267; internal const int ERROR_PARTIAL_COPY = 299; internal const int ERROR_ARITHMETIC_OVERFLOW = 534; internal const int ERROR_PIPE_CONNECTED = 535; internal const int ERROR_PIPE_LISTENING = 536; internal const int ERROR_OPERATION_ABORTED = 995; internal const int ERROR_IO_INCOMPLETE = 996; internal const int ERROR_IO_PENDING = 997; internal const int ERROR_NO_TOKEN = 1008; internal const int ERROR_DLL_INIT_FAILED = 1114; internal const int ERROR_COUNTER_TIMEOUT = 1121; internal const int ERROR_NO_ASSOCIATION = 1155; internal const int ERROR_DDE_FAIL = 1156; internal const int ERROR_DLL_NOT_FOUND = 1157; internal const int ERROR_NOT_FOUND = 1168; internal const int ERROR_NETWORK_UNREACHABLE = 1231; internal const int ERROR_NON_ACCOUNT_SID = 1257; internal const int ERROR_NOT_ALL_ASSIGNED = 1300; internal const int ERROR_UNKNOWN_REVISION = 1305; internal const int ERROR_INVALID_OWNER = 1307; internal const int ERROR_INVALID_PRIMARY_GROUP = 1308; internal const int ERROR_NO_SUCH_PRIVILEGE = 1313; internal const int ERROR_PRIVILEGE_NOT_HELD = 1314; internal const int ERROR_INVALID_ACL = 1336; internal const int ERROR_INVALID_SECURITY_DESCR = 1338; internal const int ERROR_INVALID_SID = 1337; internal const int ERROR_BAD_IMPERSONATION_LEVEL = 1346; internal const int ERROR_CANT_OPEN_ANONYMOUS = 1347; internal const int ERROR_NO_SECURITY_ON_OBJECT = 1350; internal const int ERROR_CLASS_ALREADY_EXISTS = 1410; internal const int ERROR_TRUSTED_RELATIONSHIP_FAILURE = 1789; internal const int ERROR_RESOURCE_LANG_NOT_FOUND = 1815; internal const int EFail = -2147467259; internal const int E_FILENOTFOUND = -2147024894; } internal static class Libraries { internal const string Advapi32 = "advapi32.dll"; internal const string BCrypt = "BCrypt.dll"; internal const string CoreComm_L1_1_1 = "api-ms-win-core-comm-l1-1-1.dll"; internal const string Crypt32 = "crypt32.dll"; internal const string Error_L1 = "api-ms-win-core-winrt-error-l1-1-0.dll"; internal const string HttpApi = "httpapi.dll"; internal const string IpHlpApi = "iphlpapi.dll"; internal const string Kernel32 = "kernel32.dll"; internal const string Memory_L1_3 = "api-ms-win-core-memory-l1-1-3.dll"; internal const string Mswsock = "mswsock.dll"; internal const string NCrypt = "ncrypt.dll"; internal const string NtDll = "ntdll.dll"; internal const string Odbc32 = "odbc32.dll"; internal const string OleAut32 = "oleaut32.dll"; internal const string PerfCounter = "perfcounter.dll"; internal const string RoBuffer = "api-ms-win-core-winrt-robuffer-l1-1-0.dll"; internal const string Secur32 = "secur32.dll"; internal const string Shell32 = "shell32.dll"; internal const string SspiCli = "sspicli.dll"; internal const string User32 = "user32.dll"; internal const string Version = "version.dll"; internal const string WebSocket = "websocket.dll"; internal const string WinHttp = "winhttp.dll"; internal const string Ws2_32 = "ws2_32.dll"; internal const string Wtsapi32 = "wtsapi32.dll"; internal const string CompressionNative = "clrcompression.dll"; internal const string ErrorHandling = "api-ms-win-core-errorhandling-l1-1-0.dll"; internal const string Handle = "api-ms-win-core-handle-l1-1-0.dll"; internal const string IO = "api-ms-win-core-io-l1-1-0.dll"; internal const string Memory = "api-ms-win-core-memory-l1-1-0.dll"; internal const string ProcessEnvironment = "api-ms-win-core-processenvironment-l1-1-0.dll"; internal const string ProcessThreads = "api-ms-win-core-processthreads-l1-1-0.dll"; internal const string RealTime = "api-ms-win-core-realtime-l1-1-0.dll"; internal const string SysInfo = "api-ms-win-core-sysinfo-l1-2-0.dll"; internal const string ThreadPool = "api-ms-win-core-threadpool-l1-2-0.dll"; internal const string Localization = "api-ms-win-core-localization-l1-2-1.dll"; } internal struct LongFileTime { internal long TicksSince1601; internal DateTimeOffset ToDateTimeOffset() { return new DateTimeOffset(DateTime.FromFileTimeUtc(TicksSince1601)); } } internal struct UNICODE_STRING { internal ushort Length; internal ushort MaximumLength; internal IntPtr Buffer; } internal class NtDll { [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct FILE_FULL_DIR_INFORMATION { public uint NextEntryOffset; public uint FileIndex; public LongFileTime CreationTime; public LongFileTime LastAccessTime; public LongFileTime LastWriteTime; public LongFileTime ChangeTime; public long EndOfFile; public long AllocationSize; public FileAttributes FileAttributes; public uint FileNameLength; public uint EaSize; private char _fileName; public unsafe ReadOnlySpan<char> FileName { get { fixed (char* pointer = &_fileName) { return new ReadOnlySpan<char>(pointer, (int)FileNameLength / 2); } } } public unsafe static FILE_FULL_DIR_INFORMATION* GetNextInfo(FILE_FULL_DIR_INFORMATION* info) { if (info == null) { return null; } uint nextEntryOffset = info->NextEntryOffset; if (nextEntryOffset == 0) { return null; } return (FILE_FULL_DIR_INFORMATION*)((byte*)info + nextEntryOffset); } } public enum FILE_INFORMATION_CLASS : uint { FileDirectoryInformation = 1u, FileFullDirectoryInformation, FileBothDirectoryInformation, FileBasicInformation, FileStandardInformation, FileInternalInformation, FileEaInformation, FileAccessInformation, FileNameInformation, FileRenameInformation, FileLinkInformation, FileNamesInformation, FileDispositionInformation, FilePositionInformation, FileFullEaInformation, FileModeInformation, FileAlignmentInformation, FileAllInformation, FileAllocationInformation, FileEndOfFileInformation, FileAlternateNameInformation, FileStreamInformation, FilePipeInformation, FilePipeLocalInformation, FilePipeRemoteInformation, FileMailslotQueryInformation, FileMailslotSetInformation, FileCompressionInformation, FileObjectIdInformation, FileCompletionInformation, FileMoveClusterInformation, FileQuotaInformation, FileReparsePointInformation, FileNetworkOpenInformation, FileAttributeTagInformation, FileTrackingInformation, FileIdBothDirectoryInformation, FileIdFullDirectoryInformation, FileValidDataLengthInformation, FileShortNameInformation, FileIoCompletionNotificationInformation, FileIoStatusBlockRangeInformation, FileIoPriorityHintInformation, FileSfioReserveInformation, FileSfioVolumeInformation, FileHardLinkInformation, FileProcessIdsUsingFileInformation, FileNormalizedNameInformation, FileNetworkPhysicalNameInformation, FileIdGlobalTxDirectoryInformation, FileIsRemoteDeviceInformation, FileUnusedInformation, FileNumaNodeInformation, FileStandardLinkInformation, FileRemoteProtocolInformation, FileRenameInformationBypassAccessCheck, FileLinkInformationBypassAccessCheck, FileVolumeNameInformation, FileIdInformation, FileIdExtdDirectoryInformation, FileReplaceCompletionInformation, FileHardLinkFullIdInformation, FileIdExtdBothDirectoryInformation, FileDispositionInformationEx, FileRenameInformationEx, FileRenameInformationExBypassAccessCheck, FileDesiredStorageClassInformation, FileStatInformation } public struct IO_STATUS_BLOCK { [StructLayout(LayoutKind.Explicit)] public struct IO_STATUS { [FieldOffset(0)] public uint Status; [FieldOffset(0)] public IntPtr Pointer; } public IO_STATUS Status; public IntPtr Information; } public struct OBJECT_ATTRIBUTES { public uint Length; public IntPtr RootDirectory; public unsafe UNICODE_STRING* ObjectName; public ObjectAttributes Attributes; public unsafe void* SecurityDescriptor; public unsafe void* SecurityQualityOfService; public unsafe OBJECT_ATTRIBUTES(UNICODE_STRING* objectName, ObjectAttributes attributes, IntPtr rootDirectory) { Length = (uint)sizeof(OBJECT_ATTRIBUTES); RootDirectory = rootDirectory; ObjectName = objectName; Attributes = attributes; SecurityDescriptor = null; SecurityQualityOfService = null; } } [Flags] public enum ObjectAttributes : uint { OBJ_INHERIT = 2u, OBJ_PERMANENT = 0x10u, OBJ_EXCLUSIVE = 0x20u, OBJ_CASE_INSENSITIVE = 0x40u, OBJ_OPENIF = 0x80u, OBJ_OPENLINK = 0x100u } public enum CreateDisposition : uint { FILE_SUPERSEDE, FILE_OPEN, FILE_CREATE, FILE_OPEN_IF, FILE_OVERWRITE, FILE_OVERWRITE_IF } public enum CreateOptions : uint { FILE_DIRECTORY_FILE = 1u, FILE_WRITE_THROUGH = 2u, FILE_SEQUENTIAL_ONLY = 4u, FILE_NO_INTERMEDIATE_BUFFERING = 8u, FILE_SYNCHRONOUS_IO_ALERT = 0x10u, FILE_SYNCHRONOUS_IO_NONALERT = 0x20u, FILE_NON_DIRECTORY_FILE = 0x40u, FILE_CREATE_TREE_CONNECTION = 0x80u, FILE_COMPLETE_IF_OPLOCKED = 0x100u, FILE_NO_EA_KNOWLEDGE = 0x200u, FILE_RANDOM_ACCESS = 0x800u, FILE_DELETE_ON_CLOSE = 0x1000u, FILE_OPEN_BY_FILE_ID = 0x2000u, FILE_OPEN_FOR_BACKUP_INTENT = 0x4000u, FILE_NO_COMPRESSION = 0x8000u, FILE_OPEN_REQUIRING_OPLOCK = 0x10000u, FILE_DISALLOW_EXCLUSIVE = 0x20000u, FILE_SESSION_AWARE = 0x40000u, FILE_RESERVE_OPFILTER = 0x100000u, FILE_OPEN_REPARSE_POINT = 0x200000u, FILE_OPEN_NO_RECALL = 0x400000u } [Flags] public enum DesiredAccess : uint { FILE_READ_DATA = 1u, FILE_LIST_DIRECTORY = 1u, FILE_WRITE_DATA = 2u, FILE_ADD_FILE = 2u, FILE_APPEND_DATA = 4u, FILE_ADD_SUBDIRECTORY = 4u, FILE_CREATE_PIPE_INSTANCE = 4u, FILE_READ_EA = 8u, FILE_WRITE_EA = 0x10u, FILE_EXECUTE = 0x20u, FILE_TRAVERSE = 0x20u, FILE_DELETE_CHILD = 0x40u, FILE_READ_ATTRIBUTES = 0x80u, FILE_WRITE_ATTRIBUTES = 0x100u, FILE_ALL_ACCESS = 0xF01FFu, DELETE = 0x10000u, READ_CONTROL = 0x20000u, WRITE_DAC = 0x40000u, WRITE_OWNER = 0x80000u, SYNCHRONIZE = 0x100000u, STANDARD_RIGHTS_READ = 0x20000u, STANDARD_RIGHTS_WRITE = 0x20000u, STANDARD_RIGHTS_EXECUTE = 0x20000u, FILE_GENERIC_READ = 0x80000000u, FILE_GENERIC_WRITE = 0x40000000u, FILE_GENERIC_EXECUTE = 0x20000000u } [DllImport("ntdll.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] private unsafe static extern int NtCreateFile(out IntPtr FileHandle, DesiredAccess DesiredAccess, ref OBJECT_ATTRIBUTES ObjectAttributes, out IO_STATUS_BLOCK IoStatusBlock, long* AllocationSize, FileAttributes FileAttributes, FileShare ShareAccess, CreateDisposition CreateDisposition, CreateOptions CreateOptions, void* EaBuffer, uint EaLength); internal unsafe static (int status, IntPtr handle) CreateFile(ReadOnlySpan<char> path, IntPtr rootDirectory, CreateDisposition createDisposition, DesiredAccess desiredAccess = DesiredAccess.SYNCHRONIZE | DesiredAccess.FILE_GENERIC_READ, FileShare shareAccess = FileShare.ReadWrite | FileShare.Delete, FileAttributes fileAttributes = (FileAttributes)0, CreateOptions createOptions = CreateOptions.FILE_SYNCHRONOUS_IO_NONALERT, ObjectAttributes objectAttributes = NtDll.ObjectAttributes.OBJ_CASE_INSENSITIVE) { checked { fixed (char* ptr = &MemoryMarshal.GetReference(path)) { UNICODE_STRING uNICODE_STRING = default(UNICODE_STRING); uNICODE_STRING.Length = (ushort)(path.Length * 2); uNICODE_STRING.MaximumLength = (ushort)(path.Length * 2); uNICODE_STRING.Buffer = (IntPtr)ptr; UNICODE_STRING uNICODE_STRING2 = uNICODE_STRING; OBJECT_ATTRIBUTES ObjectAttributes = new OBJECT_ATTRIBUTES(&uNICODE_STRING2, objectAttributes, rootDirectory); IntPtr FileHandle; IO_STATUS_BLOCK IoStatusBlock; return (NtCreateFile(out FileHandle, desiredAccess, ref ObjectAttributes, out IoStatusBlock, null, fileAttributes, shareAccess, createDisposition, createOptions, null, 0u), FileHandle); } } } [DllImport("ntdll.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] public unsafe static extern int NtQueryDirectoryFile(IntPtr FileHandle, IntPtr Event, IntPtr ApcRoutine, IntPtr ApcContext, out IO_STATUS_BLOCK IoStatusBlock, IntPtr FileInformation, uint Length, FILE_INFORMATION_CLASS FileInformationClass, BOOLEAN ReturnSingleEntry, UNICODE_STRING* FileName, BOOLEAN RestartScan); [DllImport("ntdll.dll", ExactSpelling = true)] public static extern uint RtlNtStatusToDosError(int Status); } internal class StatusOptions { internal const uint STATUS_SUCCESS = 0u; internal const uint STATUS_SOME_NOT_MAPPED = 263u; internal const uint STATUS_NO_MORE_FILES = 2147483654u; internal const uint STATUS_INVALID_PARAMETER = 3221225485u; internal const uint STATUS_NO_MEMORY = 3221225495u; internal const uint STATUS_OBJECT_NAME_NOT_FOUND = 3221225524u; internal const uint STATUS_NONE_MAPPED = 3221225587u; internal const uint STATUS_INSUFFICIENT_RESOURCES = 3221225626u; internal const uint STATUS_ACCESS_DENIED = 3221225506u; internal const uint STATUS_ACCOUNT_RESTRICTION = 3221225582u; } internal class Advapi32 { internal class RegistryOptions { internal const int REG_OPTION_NON_VOLATILE = 0; internal const int REG_OPTION_VOLATILE = 1; internal const int REG_OPTION_CREATE_LINK = 2; internal const int REG_OPTION_BACKUP_RESTORE = 4; } internal class RegistryView { internal const int KEY_WOW64_64KEY = 256; internal const int KEY_WOW64_32KEY = 512; } internal class RegistryOperations { internal const int KEY_QUERY_VALUE = 1; internal const int KEY_SET_VALUE = 2; internal const int KEY_CREATE_SUB_KEY = 4; internal const int KEY_ENUMERATE_SUB_KEYS = 8; internal const int KEY_NOTIFY = 16; internal const int KEY_CREATE_LINK = 32; internal const int KEY_READ = 131097; internal const int KEY_WRITE = 131078; internal const int SYNCHRONIZE = 1048576; internal const int READ_CONTROL = 131072; internal const int STANDARD_RIGHTS_READ = 131072; internal const int STANDARD_RIGHTS_WRITE = 131072; } internal class RegistryValues { internal const int REG_NONE = 0; internal const int REG_SZ = 1; internal const int REG_EXPAND_SZ = 2; internal const int REG_BINARY = 3; internal const int REG_DWORD = 4; internal const int REG_DWORD_LITTLE_ENDIAN = 4; internal const int REG_DWORD_BIG_ENDIAN = 5; internal const int REG_LINK = 6; internal const int REG_MULTI_SZ = 7; internal const int REG_QWORD = 11; } [DllImport("advapi32.dll")] internal static extern int RegCloseKey(IntPtr hKey); [DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegConnectRegistryW")] internal static extern int RegConnectRegistry(string machineName, SafeRegistryHandle key, out SafeRegistryHandle result); [DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegCreateKeyExW")] internal static extern int RegCreateKeyEx(SafeRegistryHandle hKey, string lpSubKey, int Reserved, string lpClass, int dwOptions, int samDesired, ref Kernel32.SECURITY_ATTRIBUTES secAttrs, out SafeRegistryHandle hkResult, out int lpdwDisposition); [DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegDeleteKeyExW")] internal static extern int RegDeleteKeyEx(SafeRegistryHandle hKey, string lpSubKey, int samDesired, int Reserved); [DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegDeleteValueW")] internal static extern int RegDeleteValue(SafeRegistryHandle hKey, string lpValueName); [DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegEnumKeyExW")] internal static extern int RegEnumKeyEx(SafeRegistryHandle hKey, int dwIndex, char[] lpName, ref int lpcbName, int[] lpReserved, [Out] StringBuilder lpClass, int[] lpcbClass, long[] lpftLastWriteTime); [DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegEnumValueW")] internal static extern int RegEnumValue(SafeRegistryHandle hKey, int dwIndex, char[] lpValueName, ref int lpcbValueName, IntPtr lpReserved_MustBeZero, int[] lpType, byte[] lpData, int[] lpcbData); [DllImport("advapi32.dll")] internal static extern int RegFlushKey(SafeRegistryHandle hKey); [DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegOpenKeyExW")] internal static extern int RegOpenKeyEx(SafeRegistryHandle hKey, string lpSubKey, int ulOptions, int samDesired, out SafeRegistryHandle hkResult); [DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegOpenKeyExW")] internal static extern int RegOpenKeyEx(IntPtr hKey, string lpSubKey, int ulOptions, int samDesired, out SafeRegistryHandle hkResult); [DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegQueryInfoKeyW")] internal static extern int RegQueryInfoKey(SafeRegistryHandle hKey, [Out] StringBuilder lpClass, int[] lpcbClass, IntPtr lpReserved_MustBeZero, ref int lpcSubKeys, int[] lpcbMaxSubKeyLen, int[] lpcbMaxClassLen, ref int lpcValues, int[] lpcbMaxValueNameLen, int[] lpcbMaxValueLen, int[] lpcbSecurityDescriptor, int[] lpftLastWriteTime); [DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegQueryValueExW")] internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, string lpValueName, int[] lpReserved, ref int lpType, [Out] byte[] lpData, ref int lpcbData); [DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegQueryValueExW")] internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, string lpValueName, int[] lpReserved, ref int lpType, ref int lpData, ref int lpcbData); [DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegQueryValueExW")] internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, string lpValueName, int[] lpReserved, ref int lpType, ref long lpData, ref int lpcbData); [DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegQueryValueExW")] internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, string lpValueName, int[] lpReserved, ref int lpType, [Out] char[] lpData, ref int lpcbData); [DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegQueryValueExW")] internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, string lpValueName, int[] lpReserved, ref int lpType, [Out] StringBuilder lpData, ref int lpcbData); [DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegSetValueExW")] internal static extern int RegSetValueEx(SafeRegistryHandle hKey, string lpValueName, int Reserved, RegistryValueKind dwType, byte[] lpData, int cbData); [DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegSetValueExW")] internal static extern int RegSetValueEx(SafeRegistryHandle hKey, string lpValueName, int Reserved, RegistryValueKind dwType, char[] lpData, int cbData); [DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegSetValueExW")] internal static extern int RegSetValueEx(SafeRegistryHandle hKey, string lpValueName, int Reserved, RegistryValueKind dwType, ref int lpData, int cbData); [DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegSetValueExW")] internal static extern int RegSetValueEx(SafeRegistryHandle hKey, string lpValueName, int Reserved, RegistryValueKind dwType, ref long lpData, int cbData); [DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegSetValueExW")] internal static extern int RegSetValueEx(SafeRegistryHandle hKey, string lpValueName, int Reserved, RegistryValueKind dwType, string lpData, int cbData); [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern IntPtr RegisterServiceCtrlHandler(string serviceName, Delegate callback); [DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)] public static extern IntPtr RegisterServiceCtrlHandlerEx(string serviceName, Delegate callback, IntPtr userData); } internal static class mincore { [DllImport("api-ms-win-core-heap-l1-1-0.dll")] internal static extern IntPtr GetProcessHeap(); [DllImport("api-ms-win-core-heap-l1-1-0.dll")] internal static extern IntPtr HeapAlloc(IntPtr hHeap, uint dwFlags, UIntPtr dwBytes); [DllImport("api-ms-win-core-heap-l1-1-0.dll")] internal static extern int HeapFree(IntPtr hHeap, uint dwFlags, IntPtr lpMem); [DllImport("api-ms-win-core-threadpool-l1-2-0.dll", SetLastError = true)] internal static extern SafeThreadPoolIOHandle CreateThreadpoolIo(SafeHandle fl, IntPtr pfnio, IntPtr context, IntPtr pcbe); [DllImport("api-ms-win-core-threadpool-l1-2-0.dll")] internal static extern void CloseThreadpoolIo(IntPtr pio); [DllImport("api-ms-win-core-threadpool-l1-2-0.dll")] internal static extern void StartThreadpoolIo(SafeThreadPoolIOHandle pio); [DllImport("api-ms-win-core-threadpool-l1-2-0.dll")] internal static extern void CancelThreadpoolIo(SafeThreadPoolIOHandle pio); } internal delegate void NativeIoCompletionCallback(IntPtr instance, IntPtr context, IntPtr overlapped, uint ioResult, UIntPtr numberOfBytesTransferred, IntPtr io); internal unsafe static void GetRandomBytes(byte* buffer, int length) { switch (BCrypt.BCryptGenRandom(IntPtr.Zero, buffer, length, 2)) { case BCrypt.NTSTATUS.STATUS_NO_MEMORY: throw new OutOfMemoryException(); default: throw new InvalidOperationException(); case BCrypt.NTSTATUS.STATUS_SUCCESS: break; } } internal static IntPtr MemAlloc(UIntPtr sizeInBytes) { IntPtr intPtr = mincore.HeapAlloc(mincore.GetProcessHeap(), 0u, sizeInBytes); if (intPtr == IntPtr.Zero) { throw new OutOfMemoryException(); } return intPtr; } internal static void MemFree(IntPtr allocatedMemory) { mincore.HeapFree(mincore.GetProcessHeap(), 0u, allocatedMemory); } } internal static class AssemblyRef { internal const string SystemConfiguration = "System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; internal const string System = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string EcmaPublicKey = "b77a5c561934e089"; public const string FrameworkPublicKeyFull = "00000000000000000400000000000000"; public const string FrameworkPublicKeyFull2 = "00000000000000000400000000000000"; public const string MicrosoftPublicKey = "b03f5f7f11d50a3a"; public const string MicrosoftJScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string MicrosoftVSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string SystemData = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string SystemDesign = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string SystemDrawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string SystemWeb = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string SystemWebExtensions = "System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string SystemWindowsForms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; } internal static class Consts { public const string MonoCorlibVersion = "1A5E0066-58DC-428A-B21C-0AD6CDAE2789"; public const string MonoVersion = "6.13.0.0"; public const string MonoCompany = "Mono development team"; public const string MonoProduct = "Mono Common Language Infrastructure"; public const string MonoCopyright = "(c) Various Mono authors"; public const string FxVersion = "4.0.0.0"; public const string FxFileVersion = "4.6.57.0"; public const string EnvironmentVersion = "4.0.30319.42000"; public const string VsVersion = "0.0.0.0"; public const string VsFileVersion = "11.0.0.0"; private const string PublicKeyToken = "b77a5c561934e089"; public const string AssemblyI18N = "I18N, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMicrosoft_JScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VisualStudio = "Microsoft.VisualStudio, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VisualStudio_Web = "Microsoft.VisualStudio.Web, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMono_Http = "Mono.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Posix = "Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Security = "Mono.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Messaging_RabbitMQ = "Mono.Messaging.RabbitMQ, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyCorlib = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Data = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Design = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_DirectoryServices = "System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Drawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Drawing_Design = "System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Messaging = "System.Messaging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Security = "System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_ServiceProcess = "System.ServiceProcess, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Web = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_2_0 = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystemCore_3_5 = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Core = "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string WindowsBase_3_0 = "WindowsBase, Version=3.0.0.0, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyWindowsBase = "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationCore_3_5 = "PresentationCore, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationCore_4_0 = "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationFramework_3_5 = "PresentationFramework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblySystemServiceModel_3_0 = "System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; } internal sealed class Locale { private Locale() { } public static string GetText(string msg) { return msg; } public static string GetText(string fmt, params object[] args) { return string.Format(fmt, args); } } internal static class SR { public const string RTL = "RTL_False"; public const string ContinueButtonText = "Continue"; public const string DebugMessageTruncated = "{0}...\n<truncated>"; public const string DebugAssertTitleShort = "Assertion Failed"; public const string DebugAssertTitle = "Assertion Failed: Cancel=Debug, OK=Continue"; public const string NotSupported = "This operation is not supported."; public const string DebugLaunchFailed = "Cannot launch the debugger. Make sure that a Microsoft (R) .NET Framework debugger is properly installed."; public const string DebugLaunchFailedTitle = "Microsoft .NET Framework Debug Launch Failure"; public const string ObjectDisposed = "Object {0} has been disposed and can no longer be used."; public const string ExceptionOccurred = "An exception occurred writing trace output to log file '{0}'. {1}"; public const string MustAddListener = "Only TraceListeners can be added to a TraceListenerCollection."; public const string ToStringNull = "(null)"; public const string EnumConverterInvalidValue = "The value '{0}' is not a valid value for the enum '{1}'."; public const string ConvertFromException = "{0} cannot convert from {1}."; public const string ConvertToException = "'{0}' is unable to convert '{1}' to '{2}'."; public const string ConvertInvalidPrimitive = "{0} is not a valid value for {1}."; public const string ErrorMissingPropertyAccessors = "Accessor methods for the {0} property are missing."; public const string ErrorInvalidPropertyType = "Invalid type for the {0} property."; public const string ErrorMissingEventAccessors = "Accessor methods for the {0} event are missing."; public const string ErrorInvalidEventHandler = "Invalid event handler for the {0} event."; public const string ErrorInvalidEventType = "Invalid type for the {0} event."; public const string InvalidMemberName = "Invalid member name."; public const string ErrorBadExtenderType = "The {0} extender provider is not compatible with the {1} type."; public const string NullableConverterBadCtorArg = "The specified type is not a nullable type."; public const string TypeDescriptorExpectedElementType = "Expected types in the collection to be of type {0}."; public const string TypeDescriptorSameAssociation = "Cannot create an association when the primary and secondary objects are the same."; public const string TypeDescriptorAlreadyAssociated = "The primary and secondary objects are already associated with each other."; public const string TypeDescriptorProviderError = "The type description provider {0} has returned null from {1} which is illegal."; public const string TypeDescriptorUnsupportedRemoteObject = "The object {0} is being remoted by a proxy that does not support interface discovery. This type of remoted object is not supported."; public const string TypeDescriptorArgsCountMismatch = "The number of elements in the Type and Object arrays must match."; public const string ErrorCreateSystemEvents = "Failed to create system events window thread."; public const string ErrorCreateTimer = "Cannot create timer."; public const string ErrorKillTimer = "Cannot end timer."; public const string ErrorSystemEventsNotSupported = "System event notifications are not supported under the current context. Server processes, for example, may not support global system event notifications."; public const string ErrorGetTempPath = "Cannot get temporary file name"; public const string CHECKOUTCanceled = "The checkout was canceled by the user."; public const string ErrorInvalidServiceInstance = "The service instance must derive from or implement {0}."; public const string ErrorServiceExists = "The service {0} already exists in the service container."; public const string Argument_InvalidNumberStyles = "An undefined NumberStyles value is being used."; public const string Argument_InvalidHexStyle = "With the AllowHexSpecifier bit set in the enum bit field, the only other valid bits that can be combined into the enum value must be a subset of those in HexNumber."; public const string Argument_ByteArrayLengthMustBeAMultipleOf4 = "The Byte[] length must be a multiple of 4."; public const string Argument_InvalidCharactersInString = "The string contained an invalid character."; public const string Argument_ParsedStringWasInvalid = "The parsed string was invalid."; public const string Argument_MustBeBigInt = "The parameter must be a BigInteger."; public const string Format_InvalidFormatSpecifier = "Format specifier was invalid."; public const string Format_TooLarge = "The value is too large to be represented by this format specifier."; public const string ArgumentOutOfRange_MustBeLessThanUInt32MaxValue = "The value must be less than UInt32.MaxValue (2^32)."; public const string ArgumentOutOfRange_MustBeNonNeg = "The number must be greater than or equal to zero."; public const string NotSupported_NumberStyle = "The NumberStyle option is not supported."; public const string Overflow_BigIntInfinity = "BigInteger cannot represent infinity."; public const string Overflow_NotANumber = "The value is not a number."; public const string Overflow_ParseBigInteger = "The value could not be parsed."; public const string Overflow_Int32 = "Value was either too large or too small for an Int32."; public const string Overflow_Int64 = "Value was either too large or too small for an Int64."; public const string Overflow_UInt32 = "Value was either too large or too small for a UInt32."; public const string Overflow_UInt64 = "Value was either too large or too small for a UInt64."; public const string Overflow_Decimal = "Value was either too large or too small for a Decimal."; public const string Argument_FrameworkNameTooShort = "FrameworkName cannot have less than two components or more than three components."; public const string Argument_FrameworkNameInvalid = "FrameworkName is invalid."; public const string Argument_FrameworkNameInvalidVersion = "FrameworkName version component is invalid."; public const string Argument_FrameworkNameMissingVersion = "FrameworkName version component is missing."; public const string ArgumentNull_Key = "Key cannot be null."; public const string Argument_InvalidValue = "Argument {0} should be larger than {1}."; public const string Arg_MultiRank = "Multi dimension array is not supported on this operation."; public const string Barrier_ctor_ArgumentOutOfRange = "The participantCount argument must be non-negative and less than or equal to 32767."; public const string Barrier_AddParticipants_NonPositive_ArgumentOutOfRange = "The participantCount argument must be a positive value."; public const string Barrier_AddParticipants_Overflow_ArgumentOutOfRange = "Adding participantCount participants would result in the number of participants exceeding the maximum number allowed."; public const string Barrier_InvalidOperation_CalledFromPHA = "This method may not be called from within the postPhaseAction."; public const string Barrier_RemoveParticipants_NonPositive_ArgumentOutOfRange = "The participantCount argument must be a positive value."; public const string Barrier_RemoveParticipants_ArgumentOutOfRange = "The participantCount argument must be less than or equal the number of participants."; public const string Barrier_RemoveParticipants_InvalidOperation = "The participantCount argument is greater than the number of participants that haven't yet arrived at the barrier in this phase."; public const string Barrier_SignalAndWait_ArgumentOutOfRange = "The specified timeout must represent a value between -1 and Int32.MaxValue, inclusive."; public const string Barrier_SignalAndWait_InvalidOperation_ZeroTotal = "The barrier has no registered participants."; public const string Barrier_SignalAndWait_InvalidOperation_ThreadsExceeded = "The number of threads using the barrier exceeded the total number of registered participants."; public const string Barrier_Dispose = "The barrier has been disposed."; public const string BarrierPostPhaseException = "The postPhaseAction failed with an exception."; public const string UriTypeConverter_ConvertFrom_CannotConvert = "{0} cannot convert from {1}."; public const string UriTypeConverter_ConvertTo_CannotConvert = "{0} cannot convert {1} to {2}."; public const string ISupportInitializeDescr = "Specifies support for transacted initialization."; public const string CantModifyListSortDescriptionCollection = "Once a ListSortDescriptionCollection has been created it can't be modified."; public const string Argument_NullComment = "The 'Comment' property of the CodeCommentStatement '{0}' cannot be null."; public const string InvalidPrimitiveType = "Invalid Primitive Type: {0}. Consider using CodeObjectCreateExpression."; public const string Cannot_Specify_Both_Compiler_Path_And_Version = "Cannot specify both the '{0}' and '{1}' CodeDom provider options to choose a compiler. Please remove one of them."; public const string CodeGenOutputWriter = "The output writer for code generation and the writer supplied don't match and cannot be used. This is generally caused by a bad implementation of a CodeGenerator derived class."; public const string CodeGenReentrance = "This code generation API cannot be called while the generator is being used to generate something else."; public const string InvalidLanguageIdentifier = "The identifier:\"{0}\" on the property:\"{1}\" of type:\"{2}\" is not a valid language-independent identifier name. Check to see if CodeGenerator.IsValidLanguageIndependentIdentifier allows the identifier name."; public const string InvalidTypeName = "The type name:\"{0}\" on the property:\"{1}\" of type:\"{2}\" is not a valid language-independent type name."; public const string Empty_attribute = "The '{0}' attribute cannot be an empty string."; public const string Invalid_nonnegative_integer_attribute = "The '{0}' attribute must be a non-negative integer."; public const string CodeDomProvider_NotDefined = "There is no CodeDom provider defined for the language."; public const string Language_Names_Cannot_Be_Empty = "You need to specify a non-empty String for a language name in the CodeDom configuration section."; public const string Extension_Names_Cannot_Be_Empty_Or_Non_Period_Based = "An extension name in the CodeDom configuration section must be a non-empty string which starts with a period."; public const string Unable_To_Locate_Type = "The CodeDom provider type \"{0}\" could not be located."; public const string NotSupported_CodeDomAPI = "This CodeDomProvider does not support this method."; public const string ArityDoesntMatch = "The total arity specified in '{0}' does not match the number of TypeArguments supplied. There were '{1}' TypeArguments supplied."; public const string PartialTrustErrorTextReplacement = "<The original value of this property potentially contains file system information and has been suppressed.>"; public const string PartialTrustIllegalProvider = "When used in partial trust, langID must be C#, VB, J#, or JScript, and the language provider must be in the global assembly cache."; public const string IllegalAssemblyReference = "Assembly references cannot begin with '-', or contain a '/' or '\\'."; public const string NullOrEmpty_Value_in_Property = "The '{0}' property cannot contain null or empty strings."; public const string AutoGen_Comment_Line1 = "auto-generated>"; public const string AutoGen_Comment_Line2 = "This code was generated by a tool."; public const string AutoGen_Comment_Line3 = "Runtime Version:"; public const string AutoGen_Comment_Line4 = "Changes to this file may cause incorrect behavior and will be lost if"; public const string AutoGen_Comment_Line5 = "the code is regenerated."; public const string CantContainNullEntries = "Array '{0}' cannot contain null entries."; public const string InvalidPathCharsInChecksum = "The CodeChecksumPragma file name '{0}' contains invalid path characters."; public const string InvalidRegion = "The region directive '{0}' contains invalid characters. RegionText cannot contain any new line characters."; public const string Provider_does_not_support_options = "This CodeDomProvider type does not have a constructor that takes providerOptions - \"{0}\""; public const string MetaExtenderName = "{0} on {1}"; public const string InvalidEnumArgument = "The value of argument '{0}' ({1}) is invalid for Enum type '{2}'."; public const string InvalidArgument = "'{1}' is not a valid value for '{0}'."; public const string InvalidNullArgument = "Null is not a valid value for {0}."; public const string LicExceptionTypeOnly = "A valid license cannot be granted for the type {0}. Contact the manufacturer of the component for more information."; public const string LicExceptionTypeAndInstance = "An instance of type '{1}' was being created, and a valid license could not be granted for the type '{0}'. Please, contact the manufacturer of the component for more information."; public const string LicMgrContextCannotBeChanged = "The CurrentContext property of the LicenseManager is currently locked and cannot be changed."; public const string LicMgrAlreadyLocked = "The CurrentContext property of the LicenseManager is already locked by another user."; public const string LicMgrDifferentUser = "The CurrentContext property of the LicenseManager can only be unlocked with the same contextUser."; public const string InvalidElementType = "Element type {0} is not supported."; public const string InvalidIdentifier = "Identifier '{0}' is not valid."; public const string ExecFailedToCreate = "Failed to create file {0}."; public const string ExecTimeout = "Timed out waiting for a program to execute. The command being executed was {0}."; public const string ExecBadreturn = "An invalid return code was encountered waiting for a program to execute. The command being executed was {0}."; public const string ExecCantGetRetCode = "Unable to get the return code for a program being executed. The command that was being executed was '{0}'."; public const string ExecCantExec = "Cannot execute a program. The command being executed was {0}."; public const string ExecCantRevert = "Cannot execute a program. Impersonation failed."; public const string CompilerNotFound = "Compiler executable file {0} cannot be found."; public const string DuplicateFileName = "The file name '{0}' was already in the collection."; public const string CollectionReadOnly = "Collection is read-only."; public const string BitVectorFull = "Bit vector is full."; public const string ArrayConverterText = "{0} Array"; public const string CollectionConverterText = "(Collection)"; public const string MultilineStringConverterText = "(Text)"; public const string CultureInfoConverterDefaultCultureString = "(Default)"; public const string CultureInfoConverterInvalidCulture = "The {0} culture cannot be converted to a CultureInfo object on this computer."; public const string InvalidPrimitive = "The text {0} is not a valid {1}."; public const string TimerInvalidInterval = "'{0}' is not a valid value for 'Interval'. 'Interval' must be greater than {1}."; public const string TraceSwitchLevelTooHigh = "Attempted to set {0} to a value that is too high. Setting level to TraceLevel.Verbose"; public const string TraceSwitchLevelTooLow = "Attempted to set {0} to a value that is too low. Setting level to TraceLevel.Off"; public const string TraceSwitchInvalidLevel = "The Level must be set to a value in the enumeration TraceLevel."; public const string TraceListenerIndentSize = "The IndentSize property must be non-negative."; public const string TraceListenerFail = "Fail:"; public const string TraceAsTraceSource = "Trace"; public const string InvalidLowBoundArgument = "'{1}' is not a valid value for '{0}'. '{0}' must be greater than {2}."; public const string DuplicateComponentName = "Duplicate component name '{0}'. Component names must be unique and case-insensitive."; public const string NotImplemented = "{0}: Not implemented"; public const string OutOfMemory = "Could not allocate needed memory."; public const string EOF = "End of data stream encountered."; public const string IOError = "Unknown input/output failure."; public const string BadChar = "Unexpected Character: '{0}'."; public const string toStringNone = "(none)"; public const string toStringUnknown = "(unknown)"; public const string InvalidEnum = "{0} is not a valid {1} value."; public const string IndexOutOfRange = "Index {0} is out of range."; public const string ErrorPropertyAccessorException = "Property accessor '{0}' on object '{1}' threw the following exception:'{2}'"; public const string InvalidOperation = "Invalid operation."; public const string EmptyStack = "Stack has no items in it."; public const string PerformanceCounterDesc = "Represents a Windows performance counter component."; public const string PCCategoryName = "Category name of the performance counter object."; public const string PCCounterName = "Counter name of the performance counter object."; public const string PCInstanceName = "Instance name of the performance counter object."; public const string PCMachineName = "Specifies the machine from where to read the performance data."; public const string PCInstanceLifetime = "Specifies the lifetime of the instance."; public const string PropertyCategoryAction = "Action"; public const string PropertyCategoryAppearance = "Appearance"; public const string PropertyCategoryAsynchronous = "Asynchronous"; public const string PropertyCategoryBehavior = "Behavior"; public const string PropertyCategoryData = "Data"; public const string PropertyCategoryDDE = "DDE"; public const string PropertyCategoryDesign = "Design"; public const string PropertyCategoryDragDrop = "Drag Drop"; public const string PropertyCategoryFocus = "Focus"; public const string PropertyCategoryFont = "Font"; public const string PropertyCategoryFormat = "Format"; public const string PropertyCategoryKey = "Key"; public const string PropertyCategoryList = "List"; public const string PropertyCategoryLayout = "Layout"; public const string PropertyCategoryDefault = "Misc"; public const string PropertyCategoryMouse = "Mouse"; public const string PropertyCategoryPosition = "Position"; public const string PropertyCategoryText = "Text"; public const string PropertyCategoryScale = "Scale"; public const string PropertyCategoryWindowStyle = "Window Style"; public const string PropertyCategoryConfig = "Configurations"; public const string ArgumentNull_ArrayWithNullElements = "The array cannot contain null elements."; public const string OnlyAllowedOnce = "This operation is only allowed once per object."; public const string BeginIndexNotNegative = "Start index cannot be less than 0 or greater than input length."; public const string LengthNotNegative = "Length cannot be less than 0 or exceed input length."; public const string UnimplementedState = "Unimplemented state."; public const string UnexpectedOpcode = "Unexpected opcode in regular expression generation: {0}."; public const string NoResultOnFailed = "Result cannot be called on a failed Match."; public const string UnterminatedBracket = "Unterminated [] set."; public const string TooManyParens = "Too many )'s."; public const string NestedQuantify = "Nested quantifier {0}."; public const string QuantifyAfterNothing = "Quantifier {x,y} following nothing."; public const string InternalError = "Internal error in ScanRegex."; public const string IllegalRange = "Illegal {x,y} with x > y."; public const string NotEnoughParens = "Not enough )'s."; public const string BadClassInCharRange = "Cannot include class \\{0} in character range."; public const string ReversedCharRange = "[x-y] range in reverse order."; public const string UndefinedReference = "(?({0}) ) reference to undefined group."; public const string MalformedReference = "(?({0}) ) malformed."; public const string UnrecognizedGrouping = "Unrecognized grouping construct."; public const string UnterminatedComment = "Unterminated (?#...) comment."; public const string IllegalEndEscape = "Illegal \\ at end of pattern."; public const string MalformedNameRef = "Malformed \\k<...> named back reference."; public const string UndefinedBackref = "Reference to undefined group number {0}."; public const string UndefinedNameRef = "Reference to undefined group name {0}."; public const string TooFewHex = "Insufficient hexadecimal digits."; public const string MissingControl = "Missing control character."; public const string UnrecognizedControl = "Unrecognized control character."; public const string UnrecognizedEscape = "Unrecognized escape sequence \\{0}."; public const string IllegalCondition = "Illegal conditional (?(...)) expression."; public const string TooManyAlternates = "Too many | in (?()|)."; public const string MakeException = "parsing \"{0}\" - {1}"; public const string IncompleteSlashP = "Incomplete \\p{X} character escape."; public const string MalformedSlashP = "Malformed \\p{X} character escape."; public const string InvalidGroupName = "Invalid group name: Group names must begin with a word character."; public const string CapnumNotZero = "Capture number cannot be zero."; public const string AlternationCantCapture = "Alternation conditions do not capture and cannot be named."; public const string AlternationCantHaveComment = "Alternation conditions cannot be comments."; public const string CaptureGroupOutOfRange = "Capture group numbers must be less than or equal to Int32.MaxValue."; public const string SubtractionMustBeLast = "A subtraction must be the last element in a character class."; public const string UnknownProperty = "Unknown property '{0}'."; public const string ReplacementError = "Replacement pattern error."; public const string CountTooSmall = "Count cannot be less than -1."; public const string EnumNotStarted = "Enumeration has either not started or has already finished."; public const string Arg_InvalidArrayType = "Target array type is not compatible with the type of items in the collection."; public const string RegexMatchTimeoutException_Occurred = "The RegEx engine has timed out while trying to match a pattern to an input string. This can occur for many reasons, including very large inputs or excessive backtracking caused by nested quantifiers, back-references and other factors."; public const string IllegalDefaultRegexMatchTimeoutInAppDomain = "AppDomain data '{0}' contains an invalid value or object for specifying a default matching timeout for System.Text.RegularExpressions.Regex."; public const string FileObject_AlreadyOpen = "The file is already open. Call Close before trying to open the FileObject again."; public const string FileObject_Closed = "The FileObject is currently closed. Try opening it."; public const string FileObject_NotWhileWriting = "File information cannot be queried while open for writing."; public const string FileObject_FileDoesNotExist = "File information cannot be queried if the file does not exist."; public const string FileObject_MustBeClosed = "This operation can only be done when the FileObject is closed."; public const string FileObject_MustBeFileName = "You must specify a file name, not a relative or absolute path."; public const string FileObject_InvalidInternalState = "FileObject's open mode wasn't set to a valid value. This FileObject is corrupt."; public const string FileObject_PathNotSet = "The path has not been set, or is an empty string. Please ensure you specify some path."; public const string FileObject_Reading = "The file is currently open for reading. Close the file and reopen it before attempting this."; public const string FileObject_Writing = "The file is currently open for writing. Close the file and reopen it before attempting this."; public const string FileObject_InvalidEnumeration = "Enumerator is positioned before the first line or after the last line of the file."; public const string FileObject_NoReset = "Reset is not supported on a FileLineEnumerator."; public const string DirectoryObject_MustBeDirName = "You must specify a directory name, not a relative or absolute path."; public const string DirectoryObjectPathDescr = "The fully qualified, or relative path to the directory you wish to read from. E.g., \"c:\\temp\"."; public const string FileObjectDetectEncodingDescr = "Determines whether the file will be parsed to see if it has a byte order mark indicating its encoding. If it does, this will be used rather than the current specified encoding."; public const string FileObjectEncodingDescr = "The encoding to use when reading the file. UTF-8 is the default."; public const string FileObjectPathDescr = "The fully qualified, or relative path to the file you wish to read from. E.g., \"myfile.txt\"."; public const string Arg_EnumIllegalVal = "Illegal enum value: {0}."; public const string Arg_OutOfRange_NeedNonNegNum = "Non-negative number required."; public const string Argument_InvalidPermissionState = "Invalid permission state."; public const string Argument_InvalidOidValue = "The OID value was invalid."; public const string Argument_WrongType = "Operation on type '{0}' attempted with target of incorrect type."; public const string Arg_EmptyOrNullString = "String cannot be empty or null."; public const string Arg_EmptyOrNullArray = "Array cannot be empty or null."; public const string Argument_InvalidClassAttribute = "The value of \"class\" attribute is invalid."; public const string Argument_InvalidNameType = "The value of \"nameType\" is invalid."; public const string InvalidOperation_DuplicateItemNotAllowed = "Duplicate items are not allowed in the collection."; public const string Cryptography_Asn_MismatchedOidInCollection = "The AsnEncodedData object does not have the same OID for the collection."; public const string Cryptography_Cms_Envelope_Empty_Content = "Cannot create CMS enveloped for empty content."; public const string Cryptography_Cms_Invalid_Recipient_Info_Type = "The recipient info type {0} is not valid."; public const string Cryptography_Cms_Invalid_Subject_Identifier_Type = "The subject identifier type {0} is not valid."; public const string Cryptography_Cms_Invalid_Subject_Identifier_Type_Value_Mismatch = "The subject identifier type {0} does not match the value data type {1}."; public const string Cryptography_Cms_Key_Agree_Date_Not_Available = "The Date property is not available for none KID key agree recipient."; public const string Cryptography_Cms_Key_Agree_Other_Key_Attribute_Not_Available = "The OtherKeyAttribute property is not available for none KID key agree recipient."; public const string Cryptography_Cms_MessageNotSigned = "The CMS message is not signed."; public const string Cryptography_Cms_MessageNotSignedByNoSignature = "The CMS message is not signed by NoSignature."; public const string Cryptography_Cms_MessageNotEncrypted = "The CMS message is not encrypted."; public const string Cryptography_Cms_Not_Supported = "The Cryptographic Message Standard (CMS) is not supported on this platform."; public const string Cryptography_Cms_RecipientCertificateNotFound = "The recipient certificate is not specified."; public const string Cryptography_Cms_Sign_Empty_Content = "Cannot create CMS signature for empty content."; public const string Cryptography_Cms_Sign_No_Signature_First_Signer = "CmsSigner has to be the first signer with NoSignature."; public const string Cryptography_DpApi_InvalidMemoryLength = "The length of the data should be a multiple of 16 bytes."; public const string Cryptography_InvalidHandle = "{0} is an invalid handle."; public const string Cryptography_InvalidContextHandle = "The chain context handle is invalid."; public const string Cryptography_InvalidStoreHandle = "The store handle is invalid."; public const string Cryptography_Oid_InvalidValue = "The OID value is invalid."; public const string Cryptography_Pkcs9_ExplicitAddNotAllowed = "The PKCS 9 attribute cannot be explicitly added to the collection."; public const string Cryptography_Pkcs9_InvalidOid = "The OID does not represent a valid PKCS 9 attribute."; public const string Cryptography_Pkcs9_MultipleSigningTimeNotAllowed = "Cannot add multiple PKCS 9 signing time attributes."; public const string Cryptography_Pkcs9_AttributeMismatch = "The parameter should be a PKCS 9 attribute."; public const string Cryptography_X509_AddFailed = "Adding certificate with index '{0}' failed."; public const string Cryptography_X509_BadEncoding = "Input data cannot be coded as a valid certificate."; public const string Cryptography_X509_ExportFailed = "The certificate export operation failed."; public const string Cryptography_X509_ExtensionMismatch = "The parameter should be an X509Extension."; public const string Cryptography_X509_InvalidFindType = "Invalid find type."; public const string Cryptography_X509_InvalidFindValue = "Invalid find value."; public const string Cryptography_X509_InvalidEncodingFormat = "Invalid encoding format."; public const string Cryptography_X509_InvalidContentType = "Invalid content type."; public const string Cryptography_X509_KeyMismatch = "The public key of the certificate does not match the value specified."; public const string Cryptography_X509_RemoveFailed = "Removing certificate with index '{0}' failed."; public const string Cryptography_X509_StoreNotOpen = "The X509 certificate store has not been opened."; public const string Environment_NotInteractive = "The current session is not interactive."; public const string NotSupported_InvalidKeyImpl = "Only asymmetric keys that implement ICspAsymmetricAlgorithm are supported."; public const string NotSupported_KeyAlgorithm = "The certificate key algorithm is not supported."; public const string NotSupported_PlatformRequiresNT = "This operation is only supported on Windows 2000, Windows XP, and higher."; public const string NotSupported_UnreadableStream = "Stream does not support reading."; public const string Security_InvalidValue = "The {0} value was invalid."; public const string Unknown_Error = "Unknown error."; public const string security_ServiceNameCollection_EmptyServiceName = "A service name must not be null or empty."; public const string security_ExtendedProtectionPolicy_UseDifferentConstructorForNever = "To construct a policy with PolicyEnforcement.Never, the single-parameter constructor must be used."; public const string security_ExtendedProtectionPolicy_NoEmptyServiceNameCollection = "The ServiceNameCollection must contain at least one service name."; public const string security_ExtendedProtection_NoOSSupport = "This operation requires OS support for extended protection."; public const string net_nonClsCompliantException = "A non-CLS Compliant Exception (i.e. an object that does not derive from System.Exception) was thrown."; public const string net_illegalConfigWith = "The '{0}' attribute cannot appear when '{1}' is present."; public const string net_illegalConfigWithout = "The '{0}' attribute can only appear when '{1}' is present."; public const string net_resubmitcanceled = "An error occurred on an automatic resubmission of the request."; public const string net_redirect_perm = "WebPermission demand failed for redirect URI."; public const string net_resubmitprotofailed = "Cannot handle redirect from HTTP/HTTPS protocols to other dissimilar ones."; public const string net_invalidversion = "This protocol version is not supported."; public const string net_toolong = "The size of {0} is too long. It cannot be longer than {1} characters."; public const string net_connclosed = "The underlying connection was closed: {0}."; public const string net_mutualauthfailed = "The requirement for mutual authentication was not met by the remote server."; public const string net_invasync = "Cannot block a call on this socket while an earlier asynchronous call is in progress."; public const string net_inasync = "An asynchronous call is already in progress. It must be completed or canceled before you can call this method."; public const string net_mustbeuri = "The {0} parameter must represent a valid Uri (see inner exception)."; public const string net_format_shexp = "The shell expression '{0}' could not be parsed because it is formatted incorrectly."; public const string net_cannot_load_proxy_helper = "Failed to load the proxy script runtime environment from the Microsoft.JScript assembly."; public const string net_io_no_0timeouts = "NetworkStream does not support a 0 millisecond timeout, use a value greater than zero for the timeout instead."; public const string net_tooManyRedirections = "Too many automatic redirections were attempted."; public const string net_authmodulenotregistered = "The supplied authentication module is not registered."; public const string net_authschemenotregistered = "There is no registered module for this authentication scheme."; public const string net_proxyschemenotsupported = "The ServicePointManager does not support proxies with the {0} scheme."; public const string net_maxsrvpoints = "The maximum number of service points was exceeded."; public const string net_notconnected = "The operation is not allowed on non-connected sockets."; public const string net_notstream = "The operation is not allowed on non-stream oriented sockets."; public const string net_nocontentlengthonget = "Content-Length or Chunked Encoding cannot be set for an operation that does not write data."; public const string net_contentlengthmissing = "When performing a write operation with AllowWriteStreamBuffering set to false, you must either set ContentLength to a non-negative number or set SendChunked to true."; public const string net_nonhttpproxynotallowed = "The URI scheme for the supplied IWebProxy has the illegal value '{0}'. Only 'http' is supported."; public const string net_need_writebuffering = "This request requires buffering data to succeed."; public const string net_nodefaultcreds = "Default credentials cannot be supplied for the {0} authentication scheme."; public const string net_stopped = "Not listening. You must call the Start() method before calling this method."; public const string net_udpconnected = "Cannot send packets to an arbitrary host while connected."; public const string net_no_concurrent_io_allowed = "The stream does not support concurrent IO read or write operations."; public const string net_needmorethreads = "There were not enough free threads in the ThreadPool to complete the operation."; public const string net_MethodNotSupportedException = "This method is not supported by this class."; public const string net_ProtocolNotSupportedException = "The '{0}' protocol is not supported by this class."; public const string net_SelectModeNotSupportedException = "The '{0}' select mode is not supported by this class."; public const string net_InvalidSocketHandle = "The socket handle is not valid."; public const string net_InvalidAddressFamily = "The AddressFamily {0} is not valid for the {1} end point, use {2} instead."; public const string net_InvalidEndPointAddressFamily = "The supplied EndPoint of AddressFamily {0} is not valid for this Socket, use {1} instead."; public const string net_InvalidSocketAddressSize = "The supplied {0} is an invalid size for the {1} end point."; public const string net_invalidAddressList = "None of the discovered or specified addresses match the socket address family."; public const string net_invalidPingBufferSize = "The buffer length must not exceed 65500 bytes."; public const string net_cant_perform_during_shutdown = "This operation cannot be performed while the AppDomain is shutting down."; public const string net_cant_create_environment = "Unable to create another web proxy script environment at this time."; public const string net_protocol_invalid_family = "'{0}' Client can only accept InterNetwork or InterNetworkV6 addresses."; public const string net_protocol_invalid_multicast_family = "Multicast family is not the same as the family of the '{0}' Client."; public const string net_empty_osinstalltype = "The Registry value '{0}' was either empty or not a string type."; public const string net_unknown_osinstalltype = "Unknown Windows installation type '{0}'."; public const string net_cant_determine_osinstalltype = "Can't determine OS installation type: Can't read key '{0}'. Exception message: {1}"; public const string net_osinstalltype = "Current OS installation type is '{0}'."; public const string net_entire_body_not_written = "You must write ContentLength bytes to the request stream before calling [Begin]GetResponse."; public const string net_must_provide_request_body = "You must provide a request body if you set ContentLength>0 or SendChunked==true. Do this by calling [Begin]GetRequestStream before [Begin]GetResponse."; public const string net_sockets_zerolist = "The parameter {0} must contain one or more elements."; public const string net_sockets_blocking = "The operation is not allowed on a non-blocking Socket."; public const string net_sockets_useblocking = "Use the Blocking property to change the status of the Socket."; public const string net_sockets_select = "The operation is not allowed on objects of type {0}. Use only objects of type {1}."; public const string net_sockets_toolarge_select = "The {0} list contains too many items; a maximum of {1} is allowed."; public const string net_sockets_empty_select = "All lists are either null or empty."; public const string net_sockets_mustbind = "You must call the Bind method before performing this operation."; public const string net_sockets_mustlisten = "You must call the Listen method before performing this operation."; public const string net_sockets_mustnotlisten = "You may not perform this operation after calling the Listen method."; public const string net_sockets_mustnotbebound = "The socket must not be bound or connected."; public const string net_sockets_namedmustnotbebound = "{0}: The socket must not be bound or connected."; public const string net_sockets_invalid_socketinformation = "The specified value for the socket information is invalid."; public const string net_sockets_invalid_ipaddress_length = "The number of specified IP addresses has to be greater than 0."; public const string net_sockets_invalid_optionValue = "The specified value is not a valid '{0}'."; public const string net_sockets_invalid_optionValue_all = "The specified value is not valid."; public const string net_sockets_invalid_dnsendpoint = "The parameter {0} must not be of type DnsEndPoint."; public const string net_sockets_disconnectedConnect = "Once the socket has been disconnected, you can only reconnect again asynchronously, and only to a different EndPoint. BeginConnect must be called on a thread that won't exit until the operation has been completed."; public const string net_sockets_disconnectedAccept = "Once the socket has been disconnected, you can only accept again asynchronously. BeginAccept must be called on a thread that won't exit until the operation has been completed."; public const string net_tcplistener_mustbestopped = "The TcpListener must not be listening before performing this operation."; public const string net_sockets_no_duplicate_async = "BeginConnect cannot be called while another asynchronous operation is in progress on the same Socket."; public const string net_socketopinprogress = "An asynchronous socket operation is already in progress using this SocketAsyncEventArgs instance."; public const string net_buffercounttoosmall = "The Buffer space specified by the Count property is insufficient for the AcceptAsync method."; public const string net_multibuffernotsupported = "Multiple buffers cannot be used with this method."; public const string net_ambiguousbuffers = "Buffer and BufferList properties cannot both be non-null."; public const string net_sockets_ipv6only = "This operation is only valid for IPv6 Sockets."; public const string net_perfcounter_initialized_success = "System.Net performance counters initialization completed successful."; public const string net_perfcounter_initialized_error = "System.Net performance counters initialization completed with errors. See System.Net trace file for more information."; public const string net_perfcounter_nocategory = "Performance counter category '{0}' doesn't exist. No System.Net performance counter values available."; public const string net_perfcounter_initialization_started = "System.Net performance counter initialization started."; public const string net_perfcounter_cant_queue_workitem = "Can't queue counter initialization logic on a thread pool thread. System.Net performance counters will not be available."; public const string net_config_proxy = "Error creating the Web Proxy specified in the 'system.net/defaultProxy' configuration section."; public const string net_config_proxy_module_not_public = "The specified proxy module type is not public."; public const string net_config_authenticationmodules = "Error creating the modules specified in the 'system.net/authenticationModules' configuration section."; public const string net_config_webrequestmodules = "Error creating the modules specified in the 'system.net/webRequestModules' configuration section."; public const string net_config_requestcaching = "Error creating the Web Request caching policy specified in the 'system.net/requestCaching' configuration section."; public const string net_config_section_permission = "Insufficient permissions for setting the configuration section '{0}'."; public const string net_config_element_permission = "Insufficient permissions for setting the configuration element '{0}'."; public const string net_config_property_permission = "Insufficient permissions for setting the configuration property '{0}'."; public const string net_WebResponseParseError_InvalidHeaderName = "Header name is invalid"; public const string net_WebResponseParseError_InvalidContentLength = "'Content-Length' header value is invalid"; public const string net_WebResponseParseError_IncompleteHeaderLine = "Invalid header name"; public const string net_WebResponseParseError_CrLfError = "CR must be followed by LF"; public const string net_WebResponseParseError_InvalidChunkFormat = "Response chunk format is invalid"; public const string net_WebResponseParseError_UnexpectedServerResponse = "Unexpected server response received"; public const string net_webstatus_Success = "Status success"; public const string net_webstatus_ReceiveFailure = "An unexpected error occurred on a receive"; public const string net_webstatus_SendFailure = "An unexpected error occurred on a send"; public const string net_webstatus_PipelineFailure = "A pipeline failure occurred"; public const string net_webstatus_RequestCanceled = "The request was canceled"; public const string net_webstatus_ConnectionClosed = "The connection was closed unexpectedly"; public const string net_webstatus_TrustFailure = "Could not establish trust relationship for the SSL/TLS secure channel"; public const string net_webstatus_SecureChannelFailure = "Could not create SSL/TLS secure channel"; public const string net_webstatus_ServerProtocolViolation = "The server committed a protocol violation"; public const string net_webstatus_KeepAliveFailure = "A connection that was expected to be kept alive was closed by the server"; public const string net_webstatus_ProxyNameResolutionFailure = "The proxy name could not be resolved"; public const string net_webstatus_MessageLengthLimitExceeded = "The message length limit was exceeded"; public const string net_webstatus_CacheEntryNotFound = "The request cache-only policy does not allow a network request and the response is not found in cache"; public const string net_webstatus_RequestProhibitedByCachePolicy = "The request could not be satisfied using a cache-only policy"; public const string net_webstatus_RequestProhibitedByProxy = "The IWebProxy object associated with the request did not allow the request to proceed"; public const string net_httpstatuscode_NoContent = "No Content"; public const string net_httpstatuscode_NonAuthoritativeInformation = "Non Authoritative Information"; public const string net_httpstatuscode_ResetContent = "Reset Content"; public const string net_httpstatuscode_PartialContent = "Partial Content"; public const string net_httpstatuscode_MultipleChoices = "Multiple Choices Redirect"; public const string net_httpstatuscode_Ambiguous = "Ambiguous Redirect"; public const string net_httpstatuscode_MovedPermanently = "Moved Permanently Redirect"; public const string net_httpstatuscode_Moved = "Moved Redirect"; public const string net_httpstatuscode_Found = "Found Redirect"; public const string net_httpstatuscode_Redirect = "Redirect"; public const string net_httpstatuscode_SeeOther = "See Other"; public const string net_httpstatuscode_RedirectMethod = "Redirect Method"; public const string net_httpstatuscode_NotModified = "Not Modified"; public const string net_httpstatuscode_UseProxy = "Use Proxy Redirect"; public const string net_httpstatuscode_TemporaryRedirect = "Temporary Redirect"; public const string net_httpstatuscode_RedirectKeepVerb = "Redirect Keep Verb"; public const string net_httpstatuscode_BadRequest = "Bad Request"; public const string net_httpstatuscode_Unauthorized = "Unauthorized"; public const string net_httpstatuscode_PaymentRequired = "Payment Required"; public const string net_httpstatuscode_Forbidden = "Forbidden"; public const string net_httpstatuscode_NotFound = "Not Found"; public const string net_httpstatuscode_MethodNotAllowed = "Method Not Allowed"; public const string ne
BepInExPack\unstripped_corlib\netstandard.dll
Decompiled 2 months ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers; using System.Buffers.Binary; using System.Buffers.Text; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.ComponentModel.Design; using System.ComponentModel.Design.Serialization; using System.Configuration.Assemblies; using System.Data; using System.Data.Common; using System.Data.SqlTypes; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Diagnostics.SymbolStore; using System.Diagnostics.Tracing; using System.Drawing; using System.Dynamic; using System.Globalization; using System.IO; using System.IO.Compression; using System.IO.Enumeration; using System.IO.IsolatedStorage; using System.IO.MemoryMappedFiles; using System.IO.Pipes; using System.Linq; using System.Linq.Expressions; using System.Net; using System.Net.Cache; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Mail; using System.Net.Mime; using System.Net.NetworkInformation; using System.Net.Security; using System.Net.Sockets; using System.Net.WebSockets; using System.Numerics; using System.Reflection; using System.Reflection.Emit; using System.Resources; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization.Json; using System.Runtime.Versioning; using System.Security; using System.Security.Authentication; using System.Security.Authentication.ExtendedProtection; using System.Security.Claims; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Security.Permissions; using System.Security.Principal; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Sources; using System.Timers; using System.Transactions; using System.Web; using System.Windows.Input; using System.Xml; using System.Xml.Linq; using System.Xml.Resolvers; using System.Xml.Schema; using System.Xml.Serialization; using System.Xml.XPath; using System.Xml.Xsl; using Microsoft.Win32.SafeHandles; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("netstandard")] [assembly: AssemblyDescription("netstandard")] [assembly: AssemblyDefaultAlias("netstandard")] [assembly: AssemblyCompany("Mono development team")] [assembly: AssemblyProduct("Mono Common Language Infrastructure")] [assembly: AssemblyCopyright("(c) Various Mono authors")] [assembly: AssemblyInformationalVersion("2.1.0.0")] [assembly: AssemblyFileVersion("2.1.0.0")] [assembly: AssemblyVersion("2.1.0.0")] [assembly: TypeForwardedTo(typeof(CriticalHandleMinusOneIsInvalid))] [assembly: TypeForwardedTo(typeof(CriticalHandleZeroOrMinusOneIsInvalid))] [assembly: TypeForwardedTo(typeof(SafeFileHandle))] [assembly: TypeForwardedTo(typeof(SafeHandleMinusOneIsInvalid))] [assembly: TypeForwardedTo(typeof(SafeHandleZeroOrMinusOneIsInvalid))] [assembly: TypeForwardedTo(typeof(SafeMemoryMappedFileHandle))] [assembly: TypeForwardedTo(typeof(SafeMemoryMappedViewHandle))] [assembly: TypeForwardedTo(typeof(SafePipeHandle))] [assembly: TypeForwardedTo(typeof(SafeProcessHandle))] [assembly: TypeForwardedTo(typeof(SafeWaitHandle))] [assembly: TypeForwardedTo(typeof(SafeX509ChainHandle))] [assembly: TypeForwardedTo(typeof(AccessViolationException))] [assembly: TypeForwardedTo(typeof(Action))] [assembly: TypeForwardedTo(typeof(Action<>))] [assembly: TypeForwardedTo(typeof(Action<, , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(Action<, , , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(Action<, , , , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(Action<, , , , , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(Action<, , , , , , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(Action<, , , , , , , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(Action<, , , , , , , , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(Action<, >))] [assembly: TypeForwardedTo(typeof(Action<, , >))] [assembly: TypeForwardedTo(typeof(Action<, , , >))] [assembly: TypeForwardedTo(typeof(Action<, , , , >))] [assembly: TypeForwardedTo(typeof(Action<, , , , , >))] [assembly: TypeForwardedTo(typeof(Action<, , , , , , >))] [assembly: TypeForwardedTo(typeof(Action<, , , , , , , >))] [assembly: TypeForwardedTo(typeof(Action<, , , , , , , , >))] [assembly: TypeForwardedTo(typeof(Activator))] [assembly: TypeForwardedTo(typeof(AggregateException))] [assembly: TypeForwardedTo(typeof(AppContext))] [assembly: TypeForwardedTo(typeof(AppDomain))] [assembly: TypeForwardedTo(typeof(AppDomainUnloadedException))] [assembly: TypeForwardedTo(typeof(ApplicationException))] [assembly: TypeForwardedTo(typeof(ApplicationId))] [assembly: TypeForwardedTo(typeof(ArgumentException))] [assembly: TypeForwardedTo(typeof(ArgumentNullException))] [assembly: TypeForwardedTo(typeof(ArgumentOutOfRangeException))] [assembly: TypeForwardedTo(typeof(ArithmeticException))] [assembly: TypeForwardedTo(typeof(Array))] [assembly: TypeForwardedTo(typeof(ArraySegment<>))] [assembly: TypeForwardedTo(typeof(ArrayTypeMismatchException))] [assembly: TypeForwardedTo(typeof(AssemblyLoadEventArgs))] [assembly: TypeForwardedTo(typeof(AssemblyLoadEventHandler))] [assembly: TypeForwardedTo(typeof(AsyncCallback))] [assembly: TypeForwardedTo(typeof(Attribute))] [assembly: TypeForwardedTo(typeof(AttributeTargets))] [assembly: TypeForwardedTo(typeof(AttributeUsageAttribute))] [assembly: TypeForwardedTo(typeof(BadImageFormatException))] [assembly: TypeForwardedTo(typeof(Base64FormattingOptions))] [assembly: TypeForwardedTo(typeof(BitConverter))] [assembly: TypeForwardedTo(typeof(bool))] [assembly: TypeForwardedTo(typeof(Buffer))] [assembly: TypeForwardedTo(typeof(ArrayBufferWriter<>))] [assembly: TypeForwardedTo(typeof(ArrayPool<>))] [assembly: TypeForwardedTo(typeof(BinaryPrimitives))] [assembly: TypeForwardedTo(typeof(BuffersExtensions))] [assembly: TypeForwardedTo(typeof(IBufferWriter<>))] [assembly: TypeForwardedTo(typeof(IMemoryOwner<>))] [assembly: TypeForwardedTo(typeof(IPinnable))] [assembly: TypeForwardedTo(typeof(MemoryHandle))] [assembly: TypeForwardedTo(typeof(MemoryManager<>))] [assembly: TypeForwardedTo(typeof(MemoryPool<>))] [assembly: TypeForwardedTo(typeof(OperationStatus))] [assembly: TypeForwardedTo(typeof(ReadOnlySequence<>))] [assembly: TypeForwardedTo(typeof(ReadOnlySequenceSegment<>))] [assembly: TypeForwardedTo(typeof(ReadOnlySpanAction<, >))] [assembly: TypeForwardedTo(typeof(SequenceReader<>))] [assembly: TypeForwardedTo(typeof(SequenceReaderExtensions))] [assembly: TypeForwardedTo(typeof(SpanAction<, >))] [assembly: TypeForwardedTo(typeof(StandardFormat))] [assembly: TypeForwardedTo(typeof(Base64))] [assembly: TypeForwardedTo(typeof(Utf8Formatter))] [assembly: TypeForwardedTo(typeof(Utf8Parser))] [assembly: TypeForwardedTo(typeof(byte))] [assembly: TypeForwardedTo(typeof(CannotUnloadAppDomainException))] [assembly: TypeForwardedTo(typeof(char))] [assembly: TypeForwardedTo(typeof(CharEnumerator))] [assembly: TypeForwardedTo(typeof(CLSCompliantAttribute))] [assembly: TypeForwardedTo(typeof(GeneratedCodeAttribute))] [assembly: TypeForwardedTo(typeof(IndentedTextWriter))] [assembly: TypeForwardedTo(typeof(ArrayList))] [assembly: TypeForwardedTo(typeof(BitArray))] [assembly: TypeForwardedTo(typeof(CaseInsensitiveComparer))] [assembly: TypeForwardedTo(typeof(CaseInsensitiveHashCodeProvider))] [assembly: TypeForwardedTo(typeof(CollectionBase))] [assembly: TypeForwardedTo(typeof(Comparer))] [assembly: TypeForwardedTo(typeof(BlockingCollection<>))] [assembly: TypeForwardedTo(typeof(ConcurrentBag<>))] [assembly: TypeForwardedTo(typeof(ConcurrentDictionary<, >))] [assembly: TypeForwardedTo(typeof(ConcurrentQueue<>))] [assembly: TypeForwardedTo(typeof(ConcurrentStack<>))] [assembly: TypeForwardedTo(typeof(EnumerablePartitionerOptions))] [assembly: TypeForwardedTo(typeof(IProducerConsumerCollection<>))] [assembly: TypeForwardedTo(typeof(OrderablePartitioner<>))] [assembly: TypeForwardedTo(typeof(Partitioner))] [assembly: TypeForwardedTo(typeof(Partitioner<>))] [assembly: TypeForwardedTo(typeof(DictionaryBase))] [assembly: TypeForwardedTo(typeof(DictionaryEntry))] [assembly: TypeForwardedTo(typeof(CollectionExtensions))] [assembly: TypeForwardedTo(typeof(Comparer<>))] [assembly: TypeForwardedTo(typeof(Dictionary<, >))] [assembly: TypeForwardedTo(typeof(EqualityComparer<>))] [assembly: TypeForwardedTo(typeof(HashSet<>))] [assembly: TypeForwardedTo(typeof(IAsyncEnumerable<>))] [assembly: TypeForwardedTo(typeof(IAsyncEnumerator<>))] [assembly: TypeForwardedTo(typeof(ICollection<>))] [assembly: TypeForwardedTo(typeof(IComparer<>))] [assembly: TypeForwardedTo(typeof(IDictionary<, >))] [assembly: TypeForwardedTo(typeof(IEnumerable<>))] [assembly: TypeForwardedTo(typeof(IEnumerator<>))] [assembly: TypeForwardedTo(typeof(IEqualityComparer<>))] [assembly: TypeForwardedTo(typeof(IList<>))] [assembly: TypeForwardedTo(typeof(IReadOnlyCollection<>))] [assembly: TypeForwardedTo(typeof(IReadOnlyDictionary<, >))] [assembly: TypeForwardedTo(typeof(IReadOnlyList<>))] [assembly: TypeForwardedTo(typeof(ISet<>))] [assembly: TypeForwardedTo(typeof(KeyNotFoundException))] [assembly: TypeForwardedTo(typeof(KeyValuePair))] [assembly: TypeForwardedTo(typeof(KeyValuePair<, >))] [assembly: TypeForwardedTo(typeof(LinkedList<>))] [assembly: TypeForwardedTo(typeof(LinkedListNode<>))] [assembly: TypeForwardedTo(typeof(List<>))] [assembly: TypeForwardedTo(typeof(Queue<>))] [assembly: TypeForwardedTo(typeof(SortedDictionary<, >))] [assembly: TypeForwardedTo(typeof(SortedList<, >))] [assembly: TypeForwardedTo(typeof(SortedSet<>))] [assembly: TypeForwardedTo(typeof(Stack<>))] [assembly: TypeForwardedTo(typeof(Hashtable))] [assembly: TypeForwardedTo(typeof(ICollection))] [assembly: TypeForwardedTo(typeof(IComparer))] [assembly: TypeForwardedTo(typeof(IDictionary))] [assembly: TypeForwardedTo(typeof(IDictionaryEnumerator))] [assembly: TypeForwardedTo(typeof(IEnumerable))] [assembly: TypeForwardedTo(typeof(IEnumerator))] [assembly: TypeForwardedTo(typeof(IEqualityComparer))] [assembly: TypeForwardedTo(typeof(IHashCodeProvider))] [assembly: TypeForwardedTo(typeof(IList))] [assembly: TypeForwardedTo(typeof(IStructuralComparable))] [assembly: TypeForwardedTo(typeof(IStructuralEquatable))] [assembly: TypeForwardedTo(typeof(Collection<>))] [assembly: TypeForwardedTo(typeof(KeyedCollection<, >))] [assembly: TypeForwardedTo(typeof(ObservableCollection<>))] [assembly: TypeForwardedTo(typeof(ReadOnlyCollection<>))] [assembly: TypeForwardedTo(typeof(ReadOnlyDictionary<, >))] [assembly: TypeForwardedTo(typeof(ReadOnlyObservableCollection<>))] [assembly: TypeForwardedTo(typeof(Queue))] [assembly: TypeForwardedTo(typeof(ReadOnlyCollectionBase))] [assembly: TypeForwardedTo(typeof(SortedList))] [assembly: TypeForwardedTo(typeof(BitVector32))] [assembly: TypeForwardedTo(typeof(CollectionsUtil))] [assembly: TypeForwardedTo(typeof(HybridDictionary))] [assembly: TypeForwardedTo(typeof(INotifyCollectionChanged))] [assembly: TypeForwardedTo(typeof(IOrderedDictionary))] [assembly: TypeForwardedTo(typeof(ListDictionary))] [assembly: TypeForwardedTo(typeof(NameObjectCollectionBase))] [assembly: TypeForwardedTo(typeof(NameValueCollection))] [assembly: TypeForwardedTo(typeof(NotifyCollectionChangedAction))] [assembly: TypeForwardedTo(typeof(NotifyCollectionChangedEventArgs))] [assembly: TypeForwardedTo(typeof(NotifyCollectionChangedEventHandler))] [assembly: TypeForwardedTo(typeof(OrderedDictionary))] [assembly: TypeForwardedTo(typeof(StringCollection))] [assembly: TypeForwardedTo(typeof(StringDictionary))] [assembly: TypeForwardedTo(typeof(StringEnumerator))] [assembly: TypeForwardedTo(typeof(Stack))] [assembly: TypeForwardedTo(typeof(StructuralComparisons))] [assembly: TypeForwardedTo(typeof(Comparison<>))] [assembly: TypeForwardedTo(typeof(AddingNewEventArgs))] [assembly: TypeForwardedTo(typeof(AddingNewEventHandler))] [assembly: TypeForwardedTo(typeof(AmbientValueAttribute))] [assembly: TypeForwardedTo(typeof(ArrayConverter))] [assembly: TypeForwardedTo(typeof(AsyncCompletedEventArgs))] [assembly: TypeForwardedTo(typeof(AsyncCompletedEventHandler))] [assembly: TypeForwardedTo(typeof(AsyncOperation))] [assembly: TypeForwardedTo(typeof(AsyncOperationManager))] [assembly: TypeForwardedTo(typeof(AttributeCollection))] [assembly: TypeForwardedTo(typeof(AttributeProviderAttribute))] [assembly: TypeForwardedTo(typeof(BackgroundWorker))] [assembly: TypeForwardedTo(typeof(BaseNumberConverter))] [assembly: TypeForwardedTo(typeof(BindableAttribute))] [assembly: TypeForwardedTo(typeof(BindableSupport))] [assembly: TypeForwardedTo(typeof(BindingDirection))] [assembly: TypeForwardedTo(typeof(BindingList<>))] [assembly: TypeForwardedTo(typeof(BooleanConverter))] [assembly: TypeForwardedTo(typeof(BrowsableAttribute))] [assembly: TypeForwardedTo(typeof(ByteConverter))] [assembly: TypeForwardedTo(typeof(CancelEventArgs))] [assembly: TypeForwardedTo(typeof(CancelEventHandler))] [assembly: TypeForwardedTo(typeof(CategoryAttribute))] [assembly: TypeForwardedTo(typeof(CharConverter))] [assembly: TypeForwardedTo(typeof(CollectionChangeAction))] [assembly: TypeForwardedTo(typeof(CollectionChangeEventArgs))] [assembly: TypeForwardedTo(typeof(CollectionChangeEventHandler))] [assembly: TypeForwardedTo(typeof(CollectionConverter))] [assembly: TypeForwardedTo(typeof(ComplexBindingPropertiesAttribute))] [assembly: TypeForwardedTo(typeof(Component))] [assembly: TypeForwardedTo(typeof(ComponentCollection))] [assembly: TypeForwardedTo(typeof(ComponentConverter))] [assembly: TypeForwardedTo(typeof(ComponentEditor))] [assembly: TypeForwardedTo(typeof(ComponentResourceManager))] [assembly: TypeForwardedTo(typeof(Container))] [assembly: TypeForwardedTo(typeof(ContainerFilterService))] [assembly: TypeForwardedTo(typeof(CultureInfoConverter))] [assembly: TypeForwardedTo(typeof(CustomTypeDescriptor))] [assembly: TypeForwardedTo(typeof(DataErrorsChangedEventArgs))] [assembly: TypeForwardedTo(typeof(DataObjectAttribute))] [assembly: TypeForwardedTo(typeof(DataObjectFieldAttribute))] [assembly: TypeForwardedTo(typeof(DataObjectMethodAttribute))] [assembly: TypeForwardedTo(typeof(DataObjectMethodType))] [assembly: TypeForwardedTo(typeof(DateTimeConverter))] [assembly: TypeForwardedTo(typeof(DateTimeOffsetConverter))] [assembly: TypeForwardedTo(typeof(DecimalConverter))] [assembly: TypeForwardedTo(typeof(DefaultBindingPropertyAttribute))] [assembly: TypeForwardedTo(typeof(DefaultEventAttribute))] [assembly: TypeForwardedTo(typeof(DefaultPropertyAttribute))] [assembly: TypeForwardedTo(typeof(DefaultValueAttribute))] [assembly: TypeForwardedTo(typeof(DescriptionAttribute))] [assembly: TypeForwardedTo(typeof(ActiveDesignerEventArgs))] [assembly: TypeForwardedTo(typeof(ActiveDesignerEventHandler))] [assembly: TypeForwardedTo(typeof(CheckoutException))] [assembly: TypeForwardedTo(typeof(CommandID))] [assembly: TypeForwardedTo(typeof(ComponentChangedEventArgs))] [assembly: TypeForwardedTo(typeof(ComponentChangedEventHandler))] [assembly: TypeForwardedTo(typeof(ComponentChangingEventArgs))] [assembly: TypeForwardedTo(typeof(ComponentChangingEventHandler))] [assembly: TypeForwardedTo(typeof(ComponentEventArgs))] [assembly: TypeForwardedTo(typeof(ComponentEventHandler))] [assembly: TypeForwardedTo(typeof(ComponentRenameEventArgs))] [assembly: TypeForwardedTo(typeof(ComponentRenameEventHandler))] [assembly: TypeForwardedTo(typeof(DesignerCollection))] [assembly: TypeForwardedTo(typeof(DesignerEventArgs))] [assembly: TypeForwardedTo(typeof(DesignerEventHandler))] [assembly: TypeForwardedTo(typeof(DesignerOptionService))] [assembly: TypeForwardedTo(typeof(DesignerTransaction))] [assembly: TypeForwardedTo(typeof(DesignerTransactionCloseEventArgs))] [assembly: TypeForwardedTo(typeof(DesignerTransactionCloseEventHandler))] [assembly: TypeForwardedTo(typeof(DesignerVerb))] [assembly: TypeForwardedTo(typeof(DesignerVerbCollection))] [assembly: TypeForwardedTo(typeof(DesigntimeLicenseContext))] [assembly: TypeForwardedTo(typeof(DesigntimeLicenseContextSerializer))] [assembly: TypeForwardedTo(typeof(HelpContextType))] [assembly: TypeForwardedTo(typeof(HelpKeywordAttribute))] [assembly: TypeForwardedTo(typeof(HelpKeywordType))] [assembly: TypeForwardedTo(typeof(IComponentChangeService))] [assembly: TypeForwardedTo(typeof(IComponentDiscoveryService))] [assembly: TypeForwardedTo(typeof(IComponentInitializer))] [assembly: TypeForwardedTo(typeof(IDesigner))] [assembly: TypeForwardedTo(typeof(IDesignerEventService))] [assembly: TypeForwardedTo(typeof(IDesignerFilter))] [assembly: TypeForwardedTo(typeof(IDesignerHost))] [assembly: TypeForwardedTo(typeof(IDesignerHostTransactionState))] [assembly: TypeForwardedTo(typeof(IDesignerOptionService))] [assembly: TypeForwardedTo(typeof(IDictionaryService))] [assembly: TypeForwardedTo(typeof(IEventBindingService))] [assembly: TypeForwardedTo(typeof(IExtenderListService))] [assembly: TypeForwardedTo(typeof(IExtenderProviderService))] [assembly: TypeForwardedTo(typeof(IHelpService))] [assembly: TypeForwardedTo(typeof(IInheritanceService))] [assembly: TypeForwardedTo(typeof(IMenuCommandService))] [assembly: TypeForwardedTo(typeof(IReferenceService))] [assembly: TypeForwardedTo(typeof(IResourceService))] [assembly: TypeForwardedTo(typeof(IRootDesigner))] [assembly: TypeForwardedTo(typeof(ISelectionService))] [assembly: TypeForwardedTo(typeof(IServiceContainer))] [assembly: TypeForwardedTo(typeof(ITreeDesigner))] [assembly: TypeForwardedTo(typeof(ITypeDescriptorFilterService))] [assembly: TypeForwardedTo(typeof(ITypeDiscoveryService))] [assembly: TypeForwardedTo(typeof(ITypeResolutionService))] [assembly: TypeForwardedTo(typeof(MenuCommand))] [assembly: TypeForwardedTo(typeof(SelectionTypes))] [assembly: TypeForwardedTo(typeof(ComponentSerializationService))] [assembly: TypeForwardedTo(typeof(ContextStack))] [assembly: TypeForwardedTo(typeof(DefaultSerializationProviderAttribute))] [assembly: TypeForwardedTo(typeof(DesignerLoader))] [assembly: TypeForwardedTo(typeof(DesignerSerializerAttribute))] [assembly: TypeForwardedTo(typeof(IDesignerLoaderHost))] [assembly: TypeForwardedTo(typeof(IDesignerLoaderHost2))] [assembly: TypeForwardedTo(typeof(IDesignerLoaderService))] [assembly: TypeForwardedTo(typeof(IDesignerSerializationManager))] [assembly: TypeForwardedTo(typeof(IDesignerSerializationProvider))] [assembly: TypeForwardedTo(typeof(IDesignerSerializationService))] [assembly: TypeForwardedTo(typeof(INameCreationService))] [assembly: TypeForwardedTo(typeof(InstanceDescriptor))] [assembly: TypeForwardedTo(typeof(MemberRelationship))] [assembly: TypeForwardedTo(typeof(MemberRelationshipService))] [assembly: TypeForwardedTo(typeof(ResolveNameEventArgs))] [assembly: TypeForwardedTo(typeof(ResolveNameEventHandler))] [assembly: TypeForwardedTo(typeof(RootDesignerSerializerAttribute))] [assembly: TypeForwardedTo(typeof(SerializationStore))] [assembly: TypeForwardedTo(typeof(ServiceContainer))] [assembly: TypeForwardedTo(typeof(ServiceCreatorCallback))] [assembly: TypeForwardedTo(typeof(StandardCommands))] [assembly: TypeForwardedTo(typeof(StandardToolWindows))] [assembly: TypeForwardedTo(typeof(TypeDescriptionProviderService))] [assembly: TypeForwardedTo(typeof(ViewTechnology))] [assembly: TypeForwardedTo(typeof(DesignerAttribute))] [assembly: TypeForwardedTo(typeof(DesignerCategoryAttribute))] [assembly: TypeForwardedTo(typeof(DesignerSerializationVisibility))] [assembly: TypeForwardedTo(typeof(DesignerSerializationVisibilityAttribute))] [assembly: TypeForwardedTo(typeof(DesignOnlyAttribute))] [assembly: TypeForwardedTo(typeof(DesignTimeVisibleAttribute))] [assembly: TypeForwardedTo(typeof(DisplayNameAttribute))] [assembly: TypeForwardedTo(typeof(DoubleConverter))] [assembly: TypeForwardedTo(typeof(DoWorkEventArgs))] [assembly: TypeForwardedTo(typeof(DoWorkEventHandler))] [assembly: TypeForwardedTo(typeof(EditorAttribute))] [assembly: TypeForwardedTo(typeof(EditorBrowsableAttribute))] [assembly: TypeForwardedTo(typeof(EditorBrowsableState))] [assembly: TypeForwardedTo(typeof(EnumConverter))] [assembly: TypeForwardedTo(typeof(EventDescriptor))] [assembly: TypeForwardedTo(typeof(EventDescriptorCollection))] [assembly: TypeForwardedTo(typeof(EventHandlerList))] [assembly: TypeForwardedTo(typeof(ExpandableObjectConverter))] [assembly: TypeForwardedTo(typeof(ExtenderProvidedPropertyAttribute))] [assembly: TypeForwardedTo(typeof(GuidConverter))] [assembly: TypeForwardedTo(typeof(HandledEventArgs))] [assembly: TypeForwardedTo(typeof(HandledEventHandler))] [assembly: TypeForwardedTo(typeof(IBindingList))] [assembly: TypeForwardedTo(typeof(IBindingListView))] [assembly: TypeForwardedTo(typeof(ICancelAddNew))] [assembly: TypeForwardedTo(typeof(IChangeTracking))] [assembly: TypeForwardedTo(typeof(IComNativeDescriptorHandler))] [assembly: TypeForwardedTo(typeof(IComponent))] [assembly: TypeForwardedTo(typeof(IContainer))] [assembly: TypeForwardedTo(typeof(ICustomTypeDescriptor))] [assembly: TypeForwardedTo(typeof(IDataErrorInfo))] [assembly: TypeForwardedTo(typeof(IEditableObject))] [assembly: TypeForwardedTo(typeof(IExtenderProvider))] [assembly: TypeForwardedTo(typeof(IIntellisenseBuilder))] [assembly: TypeForwardedTo(typeof(IListSource))] [assembly: TypeForwardedTo(typeof(ImmutableObjectAttribute))] [assembly: TypeForwardedTo(typeof(INestedContainer))] [assembly: TypeForwardedTo(typeof(INestedSite))] [assembly: TypeForwardedTo(typeof(InheritanceAttribute))] [assembly: TypeForwardedTo(typeof(InheritanceLevel))] [assembly: TypeForwardedTo(typeof(InitializationEventAttribute))] [assembly: TypeForwardedTo(typeof(INotifyDataErrorInfo))] [assembly: TypeForwardedTo(typeof(INotifyPropertyChanged))] [assembly: TypeForwardedTo(typeof(INotifyPropertyChanging))] [assembly: TypeForwardedTo(typeof(InstallerTypeAttribute))] [assembly: TypeForwardedTo(typeof(InstanceCreationEditor))] [assembly: TypeForwardedTo(typeof(Int16Converter))] [assembly: TypeForwardedTo(typeof(Int32Converter))] [assembly: TypeForwardedTo(typeof(Int64Converter))] [assembly: TypeForwardedTo(typeof(InvalidAsynchronousStateException))] [assembly: TypeForwardedTo(typeof(InvalidEnumArgumentException))] [assembly: TypeForwardedTo(typeof(IRaiseItemChangedEvents))] [assembly: TypeForwardedTo(typeof(IRevertibleChangeTracking))] [assembly: TypeForwardedTo(typeof(ISite))] [assembly: TypeForwardedTo(typeof(ISupportInitialize))] [assembly: TypeForwardedTo(typeof(ISupportInitializeNotification))] [assembly: TypeForwardedTo(typeof(ISynchronizeInvoke))] [assembly: TypeForwardedTo(typeof(ITypeDescriptorContext))] [assembly: TypeForwardedTo(typeof(ITypedList))] [assembly: TypeForwardedTo(typeof(License))] [assembly: TypeForwardedTo(typeof(LicenseContext))] [assembly: TypeForwardedTo(typeof(LicenseException))] [assembly: TypeForwardedTo(typeof(LicenseManager))] [assembly: TypeForwardedTo(typeof(LicenseProvider))] [assembly: TypeForwardedTo(typeof(LicenseProviderAttribute))] [assembly: TypeForwardedTo(typeof(LicenseUsageMode))] [assembly: TypeForwardedTo(typeof(LicFileLicenseProvider))] [assembly: TypeForwardedTo(typeof(ListBindableAttribute))] [assembly: TypeForwardedTo(typeof(ListChangedEventArgs))] [assembly: TypeForwardedTo(typeof(ListChangedEventHandler))] [assembly: TypeForwardedTo(typeof(ListChangedType))] [assembly: TypeForwardedTo(typeof(ListSortDescription))] [assembly: TypeForwardedTo(typeof(ListSortDescriptionCollection))] [assembly: TypeForwardedTo(typeof(ListSortDirection))] [assembly: TypeForwardedTo(typeof(LocalizableAttribute))] [assembly: TypeForwardedTo(typeof(LookupBindingPropertiesAttribute))] [assembly: TypeForwardedTo(typeof(MarshalByValueComponent))] [assembly: TypeForwardedTo(typeof(MaskedTextProvider))] [assembly: TypeForwardedTo(typeof(MaskedTextResultHint))] [assembly: TypeForwardedTo(typeof(MemberDescriptor))] [assembly: TypeForwardedTo(typeof(MergablePropertyAttribute))] [assembly: TypeForwardedTo(typeof(MultilineStringConverter))] [assembly: TypeForwardedTo(typeof(NestedContainer))] [assembly: TypeForwardedTo(typeof(NotifyParentPropertyAttribute))] [assembly: TypeForwardedTo(typeof(NullableConverter))] [assembly: TypeForwardedTo(typeof(ParenthesizePropertyNameAttribute))] [assembly: TypeForwardedTo(typeof(PasswordPropertyTextAttribute))] [assembly: TypeForwardedTo(typeof(ProgressChangedEventArgs))] [assembly: TypeForwardedTo(typeof(ProgressChangedEventHandler))] [assembly: TypeForwardedTo(typeof(PropertyChangedEventArgs))] [assembly: TypeForwardedTo(typeof(PropertyChangedEventHandler))] [assembly: TypeForwardedTo(typeof(PropertyChangingEventArgs))] [assembly: TypeForwardedTo(typeof(PropertyChangingEventHandler))] [assembly: TypeForwardedTo(typeof(PropertyDescriptor))] [assembly: TypeForwardedTo(typeof(PropertyDescriptorCollection))] [assembly: TypeForwardedTo(typeof(PropertyTabAttribute))] [assembly: TypeForwardedTo(typeof(PropertyTabScope))] [assembly: TypeForwardedTo(typeof(ProvidePropertyAttribute))] [assembly: TypeForwardedTo(typeof(ReadOnlyAttribute))] [assembly: TypeForwardedTo(typeof(RecommendedAsConfigurableAttribute))] [assembly: TypeForwardedTo(typeof(ReferenceConverter))] [assembly: TypeForwardedTo(typeof(RefreshEventArgs))] [assembly: TypeForwardedTo(typeof(RefreshEventHandler))] [assembly: TypeForwardedTo(typeof(RefreshProperties))] [assembly: TypeForwardedTo(typeof(RefreshPropertiesAttribute))] [assembly: TypeForwardedTo(typeof(RunInstallerAttribute))] [assembly: TypeForwardedTo(typeof(RunWorkerCompletedEventArgs))] [assembly: TypeForwardedTo(typeof(RunWorkerCompletedEventHandler))] [assembly: TypeForwardedTo(typeof(SByteConverter))] [assembly: TypeForwardedTo(typeof(SettingsBindableAttribute))] [assembly: TypeForwardedTo(typeof(SingleConverter))] [assembly: TypeForwardedTo(typeof(StringConverter))] [assembly: TypeForwardedTo(typeof(SyntaxCheck))] [assembly: TypeForwardedTo(typeof(TimeSpanConverter))] [assembly: TypeForwardedTo(typeof(ToolboxItemAttribute))] [assembly: TypeForwardedTo(typeof(ToolboxItemFilterAttribute))] [assembly: TypeForwardedTo(typeof(ToolboxItemFilterType))] [assembly: TypeForwardedTo(typeof(TypeConverter))] [assembly: TypeForwardedTo(typeof(TypeConverterAttribute))] [assembly: TypeForwardedTo(typeof(TypeDescriptionProvider))] [assembly: TypeForwardedTo(typeof(TypeDescriptionProviderAttribute))] [assembly: TypeForwardedTo(typeof(TypeDescriptor))] [assembly: TypeForwardedTo(typeof(TypeListConverter))] [assembly: TypeForwardedTo(typeof(UInt16Converter))] [assembly: TypeForwardedTo(typeof(UInt32Converter))] [assembly: TypeForwardedTo(typeof(UInt64Converter))] [assembly: TypeForwardedTo(typeof(WarningException))] [assembly: TypeForwardedTo(typeof(Win32Exception))] [assembly: TypeForwardedTo(typeof(AssemblyHashAlgorithm))] [assembly: TypeForwardedTo(typeof(AssemblyVersionCompatibility))] [assembly: TypeForwardedTo(typeof(Console))] [assembly: TypeForwardedTo(typeof(ConsoleCancelEventArgs))] [assembly: TypeForwardedTo(typeof(ConsoleCancelEventHandler))] [assembly: TypeForwardedTo(typeof(ConsoleColor))] [assembly: TypeForwardedTo(typeof(ConsoleKey))] [assembly: TypeForwardedTo(typeof(ConsoleKeyInfo))] [assembly: TypeForwardedTo(typeof(ConsoleModifiers))] [assembly: TypeForwardedTo(typeof(ConsoleSpecialKey))] [assembly: TypeForwardedTo(typeof(ContextBoundObject))] [assembly: TypeForwardedTo(typeof(ContextMarshalException))] [assembly: TypeForwardedTo(typeof(ContextStaticAttribute))] [assembly: TypeForwardedTo(typeof(Convert))] [assembly: TypeForwardedTo(typeof(Converter<, >))] [assembly: TypeForwardedTo(typeof(AcceptRejectRule))] [assembly: TypeForwardedTo(typeof(CommandBehavior))] [assembly: TypeForwardedTo(typeof(CommandType))] [assembly: TypeForwardedTo(typeof(CatalogLocation))] [assembly: TypeForwardedTo(typeof(DataAdapter))] [assembly: TypeForwardedTo(typeof(DataColumnMapping))] [assembly: TypeForwardedTo(typeof(DataColumnMappingCollection))] [assembly: TypeForwardedTo(typeof(DataTableMapping))] [assembly: TypeForwardedTo(typeof(DataTableMappingCollection))] [assembly: TypeForwardedTo(typeof(DbColumn))] [assembly: TypeForwardedTo(typeof(DbCommand))] [assembly: TypeForwardedTo(typeof(DbCommandBuilder))] [assembly: TypeForwardedTo(typeof(DbConnection))] [assembly: TypeForwardedTo(typeof(DbConnectionStringBuilder))] [assembly: TypeForwardedTo(typeof(DbDataAdapter))] [assembly: TypeForwardedTo(typeof(DbDataReader))] [assembly: TypeForwardedTo(typeof(DbDataReaderExtensions))] [assembly: TypeForwardedTo(typeof(DbDataRecord))] [assembly: TypeForwardedTo(typeof(DbDataSourceEnumerator))] [assembly: TypeForwardedTo(typeof(DbEnumerator))] [assembly: TypeForwardedTo(typeof(DbException))] [assembly: TypeForwardedTo(typeof(DbMetaDataCollectionNames))] [assembly: TypeForwardedTo(typeof(DbMetaDataColumnNames))] [assembly: TypeForwardedTo(typeof(DbParameter))] [assembly: TypeForwardedTo(typeof(DbParameterCollection))] [assembly: TypeForwardedTo(typeof(DbProviderFactories))] [assembly: TypeForwardedTo(typeof(DbProviderFactory))] [assembly: TypeForwardedTo(typeof(DbProviderSpecificTypePropertyAttribute))] [assembly: TypeForwardedTo(typeof(DbTransaction))] [assembly: TypeForwardedTo(typeof(GroupByBehavior))] [assembly: TypeForwardedTo(typeof(IDbColumnSchemaGenerator))] [assembly: TypeForwardedTo(typeof(IdentifierCase))] [assembly: TypeForwardedTo(typeof(RowUpdatedEventArgs))] [assembly: TypeForwardedTo(typeof(RowUpdatingEventArgs))] [assembly: TypeForwardedTo(typeof(SchemaTableColumn))] [assembly: TypeForwardedTo(typeof(SchemaTableOptionalColumn))] [assembly: TypeForwardedTo(typeof(SupportedJoinOperators))] [assembly: TypeForwardedTo(typeof(ConflictOption))] [assembly: TypeForwardedTo(typeof(ConnectionState))] [assembly: TypeForwardedTo(typeof(Constraint))] [assembly: TypeForwardedTo(typeof(ConstraintCollection))] [assembly: TypeForwardedTo(typeof(ConstraintException))] [assembly: TypeForwardedTo(typeof(DataColumn))] [assembly: TypeForwardedTo(typeof(DataColumnChangeEventArgs))] [assembly: TypeForwardedTo(typeof(DataColumnChangeEventHandler))] [assembly: TypeForwardedTo(typeof(DataColumnCollection))] [assembly: TypeForwardedTo(typeof(DataException))] [assembly: TypeForwardedTo(typeof(DataReaderExtensions))] [assembly: TypeForwardedTo(typeof(DataRelation))] [assembly: TypeForwardedTo(typeof(DataRelationCollection))] [assembly: TypeForwardedTo(typeof(DataRow))] [assembly: TypeForwardedTo(typeof(DataRowAction))] [assembly: TypeForwardedTo(typeof(DataRowBuilder))] [assembly: TypeForwardedTo(typeof(DataRowChangeEventArgs))] [assembly: TypeForwardedTo(typeof(DataRowChangeEventHandler))] [assembly: TypeForwardedTo(typeof(DataRowCollection))] [assembly: TypeForwardedTo(typeof(DataRowComparer))] [assembly: TypeForwardedTo(typeof(DataRowComparer<>))] [assembly: TypeForwardedTo(typeof(DataRowExtensions))] [assembly: TypeForwardedTo(typeof(DataRowState))] [assembly: TypeForwardedTo(typeof(DataRowVersion))] [assembly: TypeForwardedTo(typeof(DataRowView))] [assembly: TypeForwardedTo(typeof(DataSet))] [assembly: TypeForwardedTo(typeof(DataSetDateTime))] [assembly: TypeForwardedTo(typeof(DataSysDescriptionAttribute))] [assembly: TypeForwardedTo(typeof(DataTable))] [assembly: TypeForwardedTo(typeof(DataTableClearEventArgs))] [assembly: TypeForwardedTo(typeof(DataTableClearEventHandler))] [assembly: TypeForwardedTo(typeof(DataTableCollection))] [assembly: TypeForwardedTo(typeof(DataTableExtensions))] [assembly: TypeForwardedTo(typeof(DataTableNewRowEventArgs))] [assembly: TypeForwardedTo(typeof(DataTableNewRowEventHandler))] [assembly: TypeForwardedTo(typeof(DataTableReader))] [assembly: TypeForwardedTo(typeof(DataView))] [assembly: TypeForwardedTo(typeof(DataViewManager))] [assembly: TypeForwardedTo(typeof(DataViewRowState))] [assembly: TypeForwardedTo(typeof(DataViewSetting))] [assembly: TypeForwardedTo(typeof(DataViewSettingCollection))] [assembly: TypeForwardedTo(typeof(DBConcurrencyException))] [assembly: TypeForwardedTo(typeof(DbType))] [assembly: TypeForwardedTo(typeof(DeletedRowInaccessibleException))] [assembly: TypeForwardedTo(typeof(DuplicateNameException))] [assembly: TypeForwardedTo(typeof(EnumerableRowCollection))] [assembly: TypeForwardedTo(typeof(EnumerableRowCollection<>))] [assembly: TypeForwardedTo(typeof(EnumerableRowCollectionExtensions))] [assembly: TypeForwardedTo(typeof(EvaluateException))] [assembly: TypeForwardedTo(typeof(FillErrorEventArgs))] [assembly: TypeForwardedTo(typeof(FillErrorEventHandler))] [assembly: TypeForwardedTo(typeof(ForeignKeyConstraint))] [assembly: TypeForwardedTo(typeof(IColumnMapping))] [assembly: TypeForwardedTo(typeof(IColumnMappingCollection))] [assembly: TypeForwardedTo(typeof(IDataAdapter))] [assembly: TypeForwardedTo(typeof(IDataParameter))] [assembly: TypeForwardedTo(typeof(IDataParameterCollection))] [assembly: TypeForwardedTo(typeof(IDataReader))] [assembly: TypeForwardedTo(typeof(IDataRecord))] [assembly: TypeForwardedTo(typeof(IDbCommand))] [assembly: TypeForwardedTo(typeof(IDbConnection))] [assembly: TypeForwardedTo(typeof(IDbDataAdapter))] [assembly: TypeForwardedTo(typeof(IDbDataParameter))] [assembly: TypeForwardedTo(typeof(IDbTransaction))] [assembly: TypeForwardedTo(typeof(InRowChangingEventException))] [assembly: TypeForwardedTo(typeof(InternalDataCollectionBase))] [assembly: TypeForwardedTo(typeof(InvalidConstraintException))] [assembly: TypeForwardedTo(typeof(InvalidExpressionException))] [assembly: TypeForwardedTo(typeof(System.Data.IsolationLevel))] [assembly: TypeForwardedTo(typeof(ITableMapping))] [assembly: TypeForwardedTo(typeof(ITableMappingCollection))] [assembly: TypeForwardedTo(typeof(KeyRestrictionBehavior))] [assembly: TypeForwardedTo(typeof(LoadOption))] [assembly: TypeForwardedTo(typeof(MappingType))] [assembly: TypeForwardedTo(typeof(MergeFailedEventArgs))] [assembly: TypeForwardedTo(typeof(MergeFailedEventHandler))] [assembly: TypeForwardedTo(typeof(MissingMappingAction))] [assembly: TypeForwardedTo(typeof(MissingPrimaryKeyException))] [assembly: TypeForwardedTo(typeof(MissingSchemaAction))] [assembly: TypeForwardedTo(typeof(NoNullAllowedException))] [assembly: TypeForwardedTo(typeof(OrderedEnumerableRowCollection<>))] [assembly: TypeForwardedTo(typeof(ParameterDirection))] [assembly: TypeForwardedTo(typeof(PropertyCollection))] [assembly: TypeForwardedTo(typeof(ReadOnlyException))] [assembly: TypeForwardedTo(typeof(RowNotInTableException))] [assembly: TypeForwardedTo(typeof(Rule))] [assembly: TypeForwardedTo(typeof(SchemaSerializationMode))] [assembly: TypeForwardedTo(typeof(SchemaType))] [assembly: TypeForwardedTo(typeof(SerializationFormat))] [assembly: TypeForwardedTo(typeof(SqlDbType))] [assembly: TypeForwardedTo(typeof(INullable))] [assembly: TypeForwardedTo(typeof(SqlAlreadyFilledException))] [assembly: TypeForwardedTo(typeof(SqlBinary))] [assembly: TypeForwardedTo(typeof(SqlBoolean))] [assembly: TypeForwardedTo(typeof(SqlByte))] [assembly: TypeForwardedTo(typeof(SqlBytes))] [assembly: TypeForwardedTo(typeof(SqlChars))] [assembly: TypeForwardedTo(typeof(SqlCompareOptions))] [assembly: TypeForwardedTo(typeof(SqlDateTime))] [assembly: TypeForwardedTo(typeof(SqlDecimal))] [assembly: TypeForwardedTo(typeof(SqlDouble))] [assembly: TypeForwardedTo(typeof(SqlGuid))] [assembly: TypeForwardedTo(typeof(SqlInt16))] [assembly: TypeForwardedTo(typeof(SqlInt32))] [assembly: TypeForwardedTo(typeof(SqlInt64))] [assembly: TypeForwardedTo(typeof(SqlMoney))] [assembly: TypeForwardedTo(typeof(SqlNotFilledException))] [assembly: TypeForwardedTo(typeof(SqlNullValueException))] [assembly: TypeForwardedTo(typeof(SqlSingle))] [assembly: TypeForwardedTo(typeof(SqlString))] [assembly: TypeForwardedTo(typeof(SqlTruncateException))] [assembly: TypeForwardedTo(typeof(SqlTypeException))] [assembly: TypeForwardedTo(typeof(SqlXml))] [assembly: TypeForwardedTo(typeof(StorageState))] [assembly: TypeForwardedTo(typeof(StateChangeEventArgs))] [assembly: TypeForwardedTo(typeof(StateChangeEventHandler))] [assembly: TypeForwardedTo(typeof(StatementCompletedEventArgs))] [assembly: TypeForwardedTo(typeof(StatementCompletedEventHandler))] [assembly: TypeForwardedTo(typeof(StatementType))] [assembly: TypeForwardedTo(typeof(StrongTypingException))] [assembly: TypeForwardedTo(typeof(SyntaxErrorException))] [assembly: TypeForwardedTo(typeof(TypedTableBase<>))] [assembly: TypeForwardedTo(typeof(TypedTableBaseExtensions))] [assembly: TypeForwardedTo(typeof(UniqueConstraint))] [assembly: TypeForwardedTo(typeof(UpdateRowSource))] [assembly: TypeForwardedTo(typeof(UpdateStatus))] [assembly: TypeForwardedTo(typeof(VersionNotFoundException))] [assembly: TypeForwardedTo(typeof(XmlReadMode))] [assembly: TypeForwardedTo(typeof(XmlWriteMode))] [assembly: TypeForwardedTo(typeof(DataMisalignedException))] [assembly: TypeForwardedTo(typeof(DateTime))] [assembly: TypeForwardedTo(typeof(DateTimeKind))] [assembly: TypeForwardedTo(typeof(DateTimeOffset))] [assembly: TypeForwardedTo(typeof(DayOfWeek))] [assembly: TypeForwardedTo(typeof(DBNull))] [assembly: TypeForwardedTo(typeof(decimal))] [assembly: TypeForwardedTo(typeof(Delegate))] [assembly: TypeForwardedTo(typeof(BooleanSwitch))] [assembly: TypeForwardedTo(typeof(AllowNullAttribute))] [assembly: TypeForwardedTo(typeof(DisallowNullAttribute))] [assembly: TypeForwardedTo(typeof(DoesNotReturnAttribute))] [assembly: TypeForwardedTo(typeof(DoesNotReturnIfAttribute))] [assembly: TypeForwardedTo(typeof(ExcludeFromCodeCoverageAttribute))] [assembly: TypeForwardedTo(typeof(MaybeNullAttribute))] [assembly: TypeForwardedTo(typeof(MaybeNullWhenAttribute))] [assembly: TypeForwardedTo(typeof(NotNullAttribute))] [assembly: TypeForwardedTo(typeof(NotNullIfNotNullAttribute))] [assembly: TypeForwardedTo(typeof(NotNullWhenAttribute))] [assembly: TypeForwardedTo(typeof(SuppressMessageAttribute))] [assembly: TypeForwardedTo(typeof(ConditionalAttribute))] [assembly: TypeForwardedTo(typeof(Contract))] [assembly: TypeForwardedTo(typeof(ContractAbbreviatorAttribute))] [assembly: TypeForwardedTo(typeof(ContractArgumentValidatorAttribute))] [assembly: TypeForwardedTo(typeof(ContractClassAttribute))] [assembly: TypeForwardedTo(typeof(ContractClassForAttribute))] [assembly: TypeForwardedTo(typeof(ContractFailedEventArgs))] [assembly: TypeForwardedTo(typeof(ContractFailureKind))] [assembly: TypeForwardedTo(typeof(ContractInvariantMethodAttribute))] [assembly: TypeForwardedTo(typeof(ContractOptionAttribute))] [assembly: TypeForwardedTo(typeof(ContractPublicPropertyNameAttribute))] [assembly: TypeForwardedTo(typeof(ContractReferenceAssemblyAttribute))] [assembly: TypeForwardedTo(typeof(ContractRuntimeIgnoredAttribute))] [assembly: TypeForwardedTo(typeof(ContractVerificationAttribute))] [assembly: TypeForwardedTo(typeof(PureAttribute))] [assembly: TypeForwardedTo(typeof(CorrelationManager))] [assembly: TypeForwardedTo(typeof(DataReceivedEventArgs))] [assembly: TypeForwardedTo(typeof(DataReceivedEventHandler))] [assembly: TypeForwardedTo(typeof(Debug))] [assembly: TypeForwardedTo(typeof(DebuggableAttribute))] [assembly: TypeForwardedTo(typeof(Debugger))] [assembly: TypeForwardedTo(typeof(DebuggerBrowsableAttribute))] [assembly: TypeForwardedTo(typeof(DebuggerBrowsableState))] [assembly: TypeForwardedTo(typeof(DebuggerDisplayAttribute))] [assembly: TypeForwardedTo(typeof(DebuggerHiddenAttribute))] [assembly: TypeForwardedTo(typeof(DebuggerNonUserCodeAttribute))] [assembly: TypeForwardedTo(typeof(DebuggerStepperBoundaryAttribute))] [assembly: TypeForwardedTo(typeof(DebuggerStepThroughAttribute))] [assembly: TypeForwardedTo(typeof(DebuggerTypeProxyAttribute))] [assembly: TypeForwardedTo(typeof(DebuggerVisualizerAttribute))] [assembly: TypeForwardedTo(typeof(DefaultTraceListener))] [assembly: TypeForwardedTo(typeof(DelimitedListTraceListener))] [assembly: TypeForwardedTo(typeof(EventTypeFilter))] [assembly: TypeForwardedTo(typeof(FileVersionInfo))] [assembly: TypeForwardedTo(typeof(MonitoringDescriptionAttribute))] [assembly: TypeForwardedTo(typeof(Process))] [assembly: TypeForwardedTo(typeof(ProcessModule))] [assembly: TypeForwardedTo(typeof(ProcessModuleCollection))] [assembly: TypeForwardedTo(typeof(ProcessPriorityClass))] [assembly: TypeForwardedTo(typeof(ProcessStartInfo))] [assembly: TypeForwardedTo(typeof(ProcessThread))] [assembly: TypeForwardedTo(typeof(ProcessThreadCollection))] [assembly: TypeForwardedTo(typeof(ProcessWindowStyle))] [assembly: TypeForwardedTo(typeof(SourceFilter))] [assembly: TypeForwardedTo(typeof(SourceLevels))] [assembly: TypeForwardedTo(typeof(SourceSwitch))] [assembly: TypeForwardedTo(typeof(StackFrame))] [assembly: TypeForwardedTo(typeof(StackFrameExtensions))] [assembly: TypeForwardedTo(typeof(StackTrace))] [assembly: TypeForwardedTo(typeof(Stopwatch))] [assembly: TypeForwardedTo(typeof(Switch))] [assembly: TypeForwardedTo(typeof(SwitchAttribute))] [assembly: TypeForwardedTo(typeof(SwitchLevelAttribute))] [assembly: TypeForwardedTo(typeof(ISymbolBinder))] [assembly: TypeForwardedTo(typeof(ISymbolBinder1))] [assembly: TypeForwardedTo(typeof(ISymbolDocument))] [assembly: TypeForwardedTo(typeof(ISymbolDocumentWriter))] [assembly: TypeForwardedTo(typeof(ISymbolMethod))] [assembly: TypeForwardedTo(typeof(ISymbolNamespace))] [assembly: TypeForwardedTo(typeof(ISymbolReader))] [assembly: TypeForwardedTo(typeof(ISymbolScope))] [assembly: TypeForwardedTo(typeof(ISymbolVariable))] [assembly: TypeForwardedTo(typeof(ISymbolWriter))] [assembly: TypeForwardedTo(typeof(SymAddressKind))] [assembly: TypeForwardedTo(typeof(SymbolToken))] [assembly: TypeForwardedTo(typeof(SymDocumentType))] [assembly: TypeForwardedTo(typeof(SymLanguageType))] [assembly: TypeForwardedTo(typeof(SymLanguageVendor))] [assembly: TypeForwardedTo(typeof(TextWriterTraceListener))] [assembly: TypeForwardedTo(typeof(ThreadPriorityLevel))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.ThreadState))] [assembly: TypeForwardedTo(typeof(ThreadWaitReason))] [assembly: TypeForwardedTo(typeof(Trace))] [assembly: TypeForwardedTo(typeof(TraceEventCache))] [assembly: TypeForwardedTo(typeof(TraceEventType))] [assembly: TypeForwardedTo(typeof(TraceFilter))] [assembly: TypeForwardedTo(typeof(TraceLevel))] [assembly: TypeForwardedTo(typeof(TraceListener))] [assembly: TypeForwardedTo(typeof(TraceListenerCollection))] [assembly: TypeForwardedTo(typeof(TraceOptions))] [assembly: TypeForwardedTo(typeof(TraceSource))] [assembly: TypeForwardedTo(typeof(TraceSwitch))] [assembly: TypeForwardedTo(typeof(DiagnosticCounter))] [assembly: TypeForwardedTo(typeof(EventActivityOptions))] [assembly: TypeForwardedTo(typeof(EventAttribute))] [assembly: TypeForwardedTo(typeof(EventChannel))] [assembly: TypeForwardedTo(typeof(EventCommand))] [assembly: TypeForwardedTo(typeof(EventCommandEventArgs))] [assembly: TypeForwardedTo(typeof(EventCounter))] [assembly: TypeForwardedTo(typeof(EventDataAttribute))] [assembly: TypeForwardedTo(typeof(EventFieldAttribute))] [assembly: TypeForwardedTo(typeof(EventFieldFormat))] [assembly: TypeForwardedTo(typeof(EventFieldTags))] [assembly: TypeForwardedTo(typeof(EventIgnoreAttribute))] [assembly: TypeForwardedTo(typeof(EventKeywords))] [assembly: TypeForwardedTo(typeof(EventLevel))] [assembly: TypeForwardedTo(typeof(EventListener))] [assembly: TypeForwardedTo(typeof(EventManifestOptions))] [assembly: TypeForwardedTo(typeof(EventOpcode))] [assembly: TypeForwardedTo(typeof(EventSource))] [assembly: TypeForwardedTo(typeof(EventSourceAttribute))] [assembly: TypeForwardedTo(typeof(EventSourceCreatedEventArgs))] [assembly: TypeForwardedTo(typeof(EventSourceException))] [assembly: TypeForwardedTo(typeof(EventSourceOptions))] [assembly: TypeForwardedTo(typeof(EventSourceSettings))] [assembly: TypeForwardedTo(typeof(EventTags))] [assembly: TypeForwardedTo(typeof(EventTask))] [assembly: TypeForwardedTo(typeof(EventWrittenEventArgs))] [assembly: TypeForwardedTo(typeof(IncrementingEventCounter))] [assembly: TypeForwardedTo(typeof(IncrementingPollingCounter))] [assembly: TypeForwardedTo(typeof(NonEventAttribute))] [assembly: TypeForwardedTo(typeof(PollingCounter))] [assembly: TypeForwardedTo(typeof(DivideByZeroException))] [assembly: TypeForwardedTo(typeof(DllNotFoundException))] [assembly: TypeForwardedTo(typeof(double))] [assembly: TypeForwardedTo(typeof(Color))] [assembly: TypeForwardedTo(typeof(ColorConverter))] [assembly: TypeForwardedTo(typeof(KnownColor))] [assembly: TypeForwardedTo(typeof(Point))] [assembly: TypeForwardedTo(typeof(PointConverter))] [assembly: TypeForwardedTo(typeof(PointF))] [assembly: TypeForwardedTo(typeof(Rectangle))] [assembly: TypeForwardedTo(typeof(RectangleConverter))] [assembly: TypeForwardedTo(typeof(RectangleF))] [assembly: TypeForwardedTo(typeof(Size))] [assembly: TypeForwardedTo(typeof(SizeConverter))] [assembly: TypeForwardedTo(typeof(SizeF))] [assembly: TypeForwardedTo(typeof(SizeFConverter))] [assembly: TypeForwardedTo(typeof(DuplicateWaitObjectException))] [assembly: TypeForwardedTo(typeof(BinaryOperationBinder))] [assembly: TypeForwardedTo(typeof(BindingRestrictions))] [assembly: TypeForwardedTo(typeof(CallInfo))] [assembly: TypeForwardedTo(typeof(ConvertBinder))] [assembly: TypeForwardedTo(typeof(CreateInstanceBinder))] [assembly: TypeForwardedTo(typeof(DeleteIndexBinder))] [assembly: TypeForwardedTo(typeof(DeleteMemberBinder))] [assembly: TypeForwardedTo(typeof(DynamicMetaObject))] [assembly: TypeForwardedTo(typeof(DynamicMetaObjectBinder))] [assembly: TypeForwardedTo(typeof(DynamicObject))] [assembly: TypeForwardedTo(typeof(ExpandoObject))] [assembly: TypeForwardedTo(typeof(GetIndexBinder))] [assembly: TypeForwardedTo(typeof(GetMemberBinder))] [assembly: TypeForwardedTo(typeof(IDynamicMetaObjectProvider))] [assembly: TypeForwardedTo(typeof(IInvokeOnGetBinder))] [assembly: TypeForwardedTo(typeof(InvokeBinder))] [assembly: TypeForwardedTo(typeof(InvokeMemberBinder))] [assembly: TypeForwardedTo(typeof(SetIndexBinder))] [assembly: TypeForwardedTo(typeof(SetMemberBinder))] [assembly: TypeForwardedTo(typeof(UnaryOperationBinder))] [assembly: TypeForwardedTo(typeof(EntryPointNotFoundException))] [assembly: TypeForwardedTo(typeof(Enum))] [assembly: TypeForwardedTo(typeof(Environment))] [assembly: TypeForwardedTo(typeof(EnvironmentVariableTarget))] [assembly: TypeForwardedTo(typeof(EventArgs))] [assembly: TypeForwardedTo(typeof(EventHandler))] [assembly: TypeForwardedTo(typeof(EventHandler<>))] [assembly: TypeForwardedTo(typeof(Exception))] [assembly: TypeForwardedTo(typeof(ExecutionEngineException))] [assembly: TypeForwardedTo(typeof(FieldAccessException))] [assembly: TypeForwardedTo(typeof(FileStyleUriParser))] [assembly: TypeForwardedTo(typeof(FlagsAttribute))] [assembly: TypeForwardedTo(typeof(FormatException))] [assembly: TypeForwardedTo(typeof(FormattableString))] [assembly: TypeForwardedTo(typeof(FtpStyleUriParser))] [assembly: TypeForwardedTo(typeof(Func<>))] [assembly: TypeForwardedTo(typeof(Func<, , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(Func<, , , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(Func<, , , , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(Func<, , , , , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(Func<, , , , , , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(Func<, , , , , , , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(Func<, , , , , , , , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(Func<, , , , , , , , , , , , , , , , >))] [assembly: TypeForwardedTo(typeof(Func<, >))] [assembly: TypeForwardedTo(typeof(Func<, , >))] [assembly: TypeForwardedTo(typeof(Func<, , , >))] [assembly: TypeForwardedTo(typeof(Func<, , , , >))] [assembly: TypeForwardedTo(typeof(Func<, , , , , >))] [assembly: TypeForwardedTo(typeof(Func<, , , , , , >))] [assembly: TypeForwardedTo(typeof(Func<, , , , , , , >))] [assembly: TypeForwardedTo(typeof(Func<, , , , , , , , >))] [assembly: TypeForwardedTo(typeof(GC))] [assembly: TypeForwardedTo(typeof(GCCollectionMode))] [assembly: TypeForwardedTo(typeof(GCNotificationStatus))] [assembly: TypeForwardedTo(typeof(GenericUriParser))] [assembly: TypeForwardedTo(typeof(GenericUriParserOptions))] [assembly: TypeForwardedTo(typeof(Calendar))] [assembly: TypeForwardedTo(typeof(CalendarAlgorithmType))] [assembly: TypeForwardedTo(typeof(CalendarWeekRule))] [assembly: TypeForwardedTo(typeof(CharUnicodeInfo))] [assembly: TypeForwardedTo(typeof(ChineseLunisolarCalendar))] [assembly: TypeForwardedTo(typeof(CompareInfo))] [assembly: TypeForwardedTo(typeof(CompareOptions))] [assembly: TypeForwardedTo(typeof(CultureInfo))] [assembly: TypeForwardedTo(typeof(CultureNotFoundException))] [assembly: TypeForwardedTo(typeof(CultureTypes))] [assembly: TypeForwardedTo(typeof(DateTimeFormatInfo))] [assembly: TypeForwardedTo(typeof(DateTimeStyles))] [assembly: TypeForwardedTo(typeof(DaylightTime))] [assembly: TypeForwardedTo(typeof(DigitShapes))] [assembly: TypeForwardedTo(typeof(EastAsianLunisolarCalendar))] [assembly: TypeForwardedTo(typeof(GlobalizationExtensions))] [assembly: TypeForwardedTo(typeof(GregorianCalendar))] [assembly: TypeForwardedTo(typeof(GregorianCalendarTypes))] [assembly: TypeForwardedTo(typeof(HebrewCalendar))] [assembly: TypeForwardedTo(typeof(HijriCalendar))] [assembly: TypeForwardedTo(typeof(IdnMapping))] [assembly: TypeForwardedTo(typeof(ISOWeek))] [assembly: TypeForwardedTo(typeof(JapaneseCalendar))] [assembly: TypeForwardedTo(typeof(JapaneseLunisolarCalendar))] [assembly: TypeForwardedTo(typeof(JulianCalendar))] [assembly: TypeForwardedTo(typeof(KoreanCalendar))] [assembly: TypeForwardedTo(typeof(KoreanLunisolarCalendar))] [assembly: TypeForwardedTo(typeof(NumberFormatInfo))] [assembly: TypeForwardedTo(typeof(NumberStyles))] [assembly: TypeForwardedTo(typeof(PersianCalendar))] [assembly: TypeForwardedTo(typeof(RegionInfo))] [assembly: TypeForwardedTo(typeof(SortKey))] [assembly: TypeForwardedTo(typeof(SortVersion))] [assembly: TypeForwardedTo(typeof(StringInfo))] [assembly: TypeForwardedTo(typeof(TaiwanCalendar))] [assembly: TypeForwardedTo(typeof(TaiwanLunisolarCalendar))] [assembly: TypeForwardedTo(typeof(TextElementEnumerator))] [assembly: TypeForwardedTo(typeof(TextInfo))] [assembly: TypeForwardedTo(typeof(ThaiBuddhistCalendar))] [assembly: TypeForwardedTo(typeof(TimeSpanStyles))] [assembly: TypeForwardedTo(typeof(UmAlQuraCalendar))] [assembly: TypeForwardedTo(typeof(UnicodeCategory))] [assembly: TypeForwardedTo(typeof(GopherStyleUriParser))] [assembly: TypeForwardedTo(typeof(Guid))] [assembly: TypeForwardedTo(typeof(HashCode))] [assembly: TypeForwardedTo(typeof(HttpStyleUriParser))] [assembly: TypeForwardedTo(typeof(IAsyncDisposable))] [assembly: TypeForwardedTo(typeof(IAsyncResult))] [assembly: TypeForwardedTo(typeof(ICloneable))] [assembly: TypeForwardedTo(typeof(IComparable))] [assembly: TypeForwardedTo(typeof(IComparable<>))] [assembly: TypeForwardedTo(typeof(IConvertible))] [assembly: TypeForwardedTo(typeof(ICustomFormatter))] [assembly: TypeForwardedTo(typeof(IDisposable))] [assembly: TypeForwardedTo(typeof(IEquatable<>))] [assembly: TypeForwardedTo(typeof(IFormatProvider))] [assembly: TypeForwardedTo(typeof(IFormattable))] [assembly: TypeForwardedTo(typeof(Index))] [assembly: TypeForwardedTo(typeof(IndexOutOfRangeException))] [assembly: TypeForwardedTo(typeof(InsufficientExecutionStackException))] [assembly: TypeForwardedTo(typeof(InsufficientMemoryException))] [assembly: TypeForwardedTo(typeof(short))] [assembly: TypeForwardedTo(typeof(int))] [assembly: TypeForwardedTo(typeof(long))] [assembly: TypeForwardedTo(typeof(IntPtr))] [assembly: TypeForwardedTo(typeof(InvalidCastException))] [assembly: TypeForwardedTo(typeof(InvalidOperationException))] [assembly: TypeForwardedTo(typeof(InvalidProgramException))] [assembly: TypeForwardedTo(typeof(InvalidTimeZoneException))] [assembly: TypeForwardedTo(typeof(BinaryReader))] [assembly: TypeForwardedTo(typeof(BinaryWriter))] [assembly: TypeForwardedTo(typeof(BufferedStream))] [assembly: TypeForwardedTo(typeof(BrotliDecoder))] [assembly: TypeForwardedTo(typeof(BrotliEncoder))] [assembly: TypeForwardedTo(typeof(BrotliStream))] [assembly: TypeForwardedTo(typeof(CompressionLevel))] [assembly: TypeForwardedTo(typeof(CompressionMode))] [assembly: TypeForwardedTo(typeof(DeflateStream))] [assembly: TypeForwardedTo(typeof(GZipStream))] [assembly: TypeForwardedTo(typeof(ZipArchive))] [assembly: TypeForwardedTo(typeof(ZipArchiveEntry))] [assembly: TypeForwardedTo(typeof(ZipArchiveMode))] [assembly: TypeForwardedTo(typeof(ZipFile))] [assembly: TypeForwardedTo(typeof(ZipFileExtensions))] [assembly: TypeForwardedTo(typeof(Directory))] [assembly: TypeForwardedTo(typeof(DirectoryInfo))] [assembly: TypeForwardedTo(typeof(DirectoryNotFoundException))] [assembly: TypeForwardedTo(typeof(DriveInfo))] [assembly: TypeForwardedTo(typeof(DriveNotFoundException))] [assembly: TypeForwardedTo(typeof(DriveType))] [assembly: TypeForwardedTo(typeof(EndOfStreamException))] [assembly: TypeForwardedTo(typeof(FileSystemEntry))] [assembly: TypeForwardedTo(typeof(FileSystemEnumerable<>))] [assembly: TypeForwardedTo(typeof(FileSystemEnumerator<>))] [assembly: TypeForwardedTo(typeof(FileSystemName))] [assembly: TypeForwardedTo(typeof(EnumerationOptions))] [assembly: TypeForwardedTo(typeof(ErrorEventArgs))] [assembly: TypeForwardedTo(typeof(ErrorEventHandler))] [assembly: TypeForwardedTo(typeof(File))] [assembly: TypeForwardedTo(typeof(FileAccess))] [assembly: TypeForwardedTo(typeof(FileAttributes))] [assembly: TypeForwardedTo(typeof(FileInfo))] [assembly: TypeForwardedTo(typeof(FileLoadException))] [assembly: TypeForwardedTo(typeof(FileMode))] [assembly: TypeForwardedTo(typeof(FileNotFoundException))] [assembly: TypeForwardedTo(typeof(FileOptions))] [assembly: TypeForwardedTo(typeof(FileShare))] [assembly: TypeForwardedTo(typeof(FileStream))] [assembly: TypeForwardedTo(typeof(FileSystemEventArgs))] [assembly: TypeForwardedTo(typeof(FileSystemEventHandler))] [assembly: TypeForwardedTo(typeof(FileSystemInfo))] [assembly: TypeForwardedTo(typeof(FileSystemWatcher))] [assembly: TypeForwardedTo(typeof(HandleInheritability))] [assembly: TypeForwardedTo(typeof(InternalBufferOverflowException))] [assembly: TypeForwardedTo(typeof(InvalidDataException))] [assembly: TypeForwardedTo(typeof(IOException))] [assembly: TypeForwardedTo(typeof(INormalizeForIsolatedStorage))] [assembly: TypeForwardedTo(typeof(IsolatedStorage))] [assembly: TypeForwardedTo(typeof(IsolatedStorageException))] [assembly: TypeForwardedTo(typeof(IsolatedStorageFile))] [assembly: TypeForwardedTo(typeof(IsolatedStorageFileStream))] [assembly: TypeForwardedTo(typeof(IsolatedStorageScope))] [assembly: TypeForwardedTo(typeof(MatchCasing))] [assembly: TypeForwardedTo(typeof(MatchType))] [assembly: TypeForwardedTo(typeof(MemoryMappedFile))] [assembly: TypeForwardedTo(typeof(MemoryMappedFileAccess))] [assembly: TypeForwardedTo(typeof(MemoryMappedFileOptions))] [assembly: TypeForwardedTo(typeof(MemoryMappedFileRights))] [assembly: TypeForwardedTo(typeof(MemoryMappedViewAccessor))] [assembly: TypeForwardedTo(typeof(MemoryMappedViewStream))] [assembly: TypeForwardedTo(typeof(MemoryStream))] [assembly: TypeForwardedTo(typeof(NotifyFilters))] [assembly: TypeForwardedTo(typeof(Path))] [assembly: TypeForwardedTo(typeof(PathTooLongException))] [assembly: TypeForwardedTo(typeof(AnonymousPipeClientStream))] [assembly: TypeForwardedTo(typeof(AnonymousPipeServerStream))] [assembly: TypeForwardedTo(typeof(NamedPipeClientStream))] [assembly: TypeForwardedTo(typeof(NamedPipeServerStream))] [assembly: TypeForwardedTo(typeof(PipeDirection))] [assembly: TypeForwardedTo(typeof(PipeOptions))] [assembly: TypeForwardedTo(typeof(PipeStream))] [assembly: TypeForwardedTo(typeof(PipeStreamImpersonationWorker))] [assembly: TypeForwardedTo(typeof(PipeTransmissionMode))] [assembly: TypeForwardedTo(typeof(RenamedEventArgs))] [assembly: TypeForwardedTo(typeof(RenamedEventHandler))] [assembly: TypeForwardedTo(typeof(SearchOption))] [assembly: TypeForwardedTo(typeof(SeekOrigin))] [assembly: TypeForwardedTo(typeof(Stream))] [assembly: TypeForwardedTo(typeof(StreamReader))] [assembly: TypeForwardedTo(typeof(StreamWriter))] [assembly: TypeForwardedTo(typeof(StringReader))] [assembly: TypeForwardedTo(typeof(StringWriter))] [assembly: TypeForwardedTo(typeof(TextReader))] [assembly: TypeForwardedTo(typeof(TextWriter))] [assembly: TypeForwardedTo(typeof(UnmanagedMemoryAccessor))] [assembly: TypeForwardedTo(typeof(UnmanagedMemoryStream))] [assembly: TypeForwardedTo(typeof(WaitForChangedResult))] [assembly: TypeForwardedTo(typeof(WatcherChangeTypes))] [assembly: TypeForwardedTo(typeof(IObservable<>))] [assembly: TypeForwardedTo(typeof(IObserver<>))] [assembly: TypeForwardedTo(typeof(IProgress<>))] [assembly: TypeForwardedTo(typeof(IServiceProvider))] [assembly: TypeForwardedTo(typeof(Lazy<>))] [assembly: TypeForwardedTo(typeof(Lazy<, >))] [assembly: TypeForwardedTo(typeof(LdapStyleUriParser))] [assembly: TypeForwardedTo(typeof(Enumerable))] [assembly: TypeForwardedTo(typeof(EnumerableExecutor))] [assembly: TypeForwardedTo(typeof(EnumerableExecutor<>))] [assembly: TypeForwardedTo(typeof(EnumerableQuery))] [assembly: TypeForwardedTo(typeof(EnumerableQuery<>))] [assembly: TypeForwardedTo(typeof(BinaryExpression))] [assembly: TypeForwardedTo(typeof(BlockExpression))] [assembly: TypeForwardedTo(typeof(CatchBlock))] [assembly: TypeForwardedTo(typeof(ConditionalExpression))] [assembly: TypeForwardedTo(typeof(ConstantExpression))] [assembly: TypeForwardedTo(typeof(DebugInfoExpression))] [assembly: TypeForwardedTo(typeof(DefaultExpression))] [assembly: TypeForwardedTo(typeof(DynamicExpression))] [assembly: TypeForwardedTo(typeof(DynamicExpressionVisitor))] [assembly: TypeForwardedTo(typeof(ElementInit))] [assembly: TypeForwardedTo(typeof(Expression))] [assembly: TypeForwardedTo(typeof(Expression<>))] [assembly: TypeForwardedTo(typeof(ExpressionType))] [assembly: TypeForwardedTo(typeof(ExpressionVisitor))] [assembly: TypeForwardedTo(typeof(GotoExpression))] [assembly: TypeForwardedTo(typeof(GotoExpressionKind))] [assembly: TypeForwardedTo(typeof(IArgumentProvider))] [assembly: TypeForwardedTo(typeof(IDynamicExpression))] [assembly: TypeForwardedTo(typeof(IndexExpression))] [assembly: TypeForwardedTo(typeof(InvocationExpression))] [assembly: TypeForwardedTo(typeof(LabelExpression))] [assembly: TypeForwardedTo(typeof(LabelTarget))] [assembly: TypeForwardedTo(typeof(LambdaExpression))] [assembly: TypeForwardedTo(typeof(ListInitExpression))] [assembly: TypeForwardedTo(typeof(LoopExpression))] [assembly: TypeForwardedTo(typeof(MemberAssignment))] [assembly: TypeForwardedTo(typeof(MemberBinding))] [assembly: TypeForwardedTo(typeof(MemberBindingType))] [assembly: TypeForwardedTo(typeof(MemberExpression))] [assembly: TypeForwardedTo(typeof(MemberInitExpression))] [assembly: TypeForwardedTo(typeof(MemberListBinding))] [assembly: TypeForwardedTo(typeof(MemberMemberBinding))] [assembly: TypeForwardedTo(typeof(MethodCallExpression))] [assembly: TypeForwardedTo(typeof(NewArrayExpression))] [assembly: TypeForwardedTo(typeof(NewExpression))] [assembly: TypeForwardedTo(typeof(ParameterExpression))] [assembly: TypeForwardedTo(typeof(RuntimeVariablesExpression))] [assembly: TypeForwardedTo(typeof(SwitchCase))] [assembly: TypeForwardedTo(typeof(SwitchExpression))] [assembly: TypeForwardedTo(typeof(SymbolDocumentInfo))] [assembly: TypeForwardedTo(typeof(TryExpression))] [assembly: TypeForwardedTo(typeof(TypeBinaryExpression))] [assembly: TypeForwardedTo(typeof(UnaryExpression))] [assembly: TypeForwardedTo(typeof(IGrouping<, >))] [assembly: TypeForwardedTo(typeof(ILookup<, >))] [assembly: TypeForwardedTo(typeof(IOrderedEnumerable<>))] [assembly: TypeForwardedTo(typeof(IOrderedQueryable))] [assembly: TypeForwardedTo(typeof(IOrderedQueryable<>))] [assembly: TypeForwardedTo(typeof(IQueryable))] [assembly: TypeForwardedTo(typeof(IQueryable<>))] [assembly: TypeForwardedTo(typeof(IQueryProvider))] [assembly: TypeForwardedTo(typeof(Lookup<, >))] [assembly: TypeForwardedTo(typeof(OrderedParallelQuery<>))] [assembly: TypeForwardedTo(typeof(ParallelEnumerable))] [assembly: TypeForwardedTo(typeof(ParallelExecutionMode))] [assembly: TypeForwardedTo(typeof(ParallelMergeOptions))] [assembly: TypeForwardedTo(typeof(ParallelQuery))] [assembly: TypeForwardedTo(typeof(ParallelQuery<>))] [assembly: TypeForwardedTo(typeof(Queryable))] [assembly: TypeForwardedTo(typeof(LoaderOptimization))] [assembly: TypeForwardedTo(typeof(LoaderOptimizationAttribute))] [assembly: TypeForwardedTo(typeof(LocalDataStoreSlot))] [assembly: TypeForwardedTo(typeof(MarshalByRefObject))] [assembly: TypeForwardedTo(typeof(Math))] [assembly: TypeForwardedTo(typeof(MathF))] [assembly: TypeForwardedTo(typeof(MemberAccessException))] [assembly: TypeForwardedTo(typeof(Memory<>))] [assembly: TypeForwardedTo(typeof(MemoryExtensions))] [assembly: TypeForwardedTo(typeof(MethodAccessException))] [assembly: TypeForwardedTo(typeof(MidpointRounding))] [assembly: TypeForwardedTo(typeof(MissingFieldException))] [assembly: TypeForwardedTo(typeof(MissingMemberException))] [assembly: TypeForwardedTo(typeof(MissingMethodException))] [assembly: TypeForwardedTo(typeof(ModuleHandle))] [assembly: TypeForwardedTo(typeof(MTAThreadAttribute))] [assembly: TypeForwardedTo(typeof(MulticastDelegate))] [assembly: TypeForwardedTo(typeof(MulticastNotSupportedException))] [assembly: TypeForwardedTo(typeof(AuthenticationManager))] [assembly: TypeForwardedTo(typeof(AuthenticationSchemes))] [assembly: TypeForwardedTo(typeof(AuthenticationSchemeSelector))] [assembly: TypeForwardedTo(typeof(Authorization))] [assembly: TypeForwardedTo(typeof(BindIPEndPoint))] [assembly: TypeForwardedTo(typeof(HttpCacheAgeControl))] [assembly: TypeForwardedTo(typeof(HttpRequestCacheLevel))] [assembly: TypeForwardedTo(typeof(HttpRequestCachePolicy))] [assembly: TypeForwardedTo(typeof(RequestCacheLevel))] [assembly: TypeForwardedTo(typeof(RequestCachePolicy))] [assembly: TypeForwardedTo(typeof(Cookie))] [assembly: TypeForwardedTo(typeof(CookieCollection))] [assembly: TypeForwardedTo(typeof(CookieContainer))] [assembly: TypeForwardedTo(typeof(CookieException))] [assembly: TypeForwardedTo(typeof(CredentialCache))] [assembly: TypeForwardedTo(typeof(DecompressionMethods))] [assembly: TypeForwardedTo(typeof(Dns))] [assembly: TypeForwardedTo(typeof(DnsEndPoint))] [assembly: TypeForwardedTo(typeof(DownloadDataCompletedEventArgs))] [assembly: TypeForwardedTo(typeof(DownloadDataCompletedEventHandler))] [assembly: TypeForwardedTo(typeof(DownloadProgressChangedEventArgs))] [assembly: TypeForwardedTo(typeof(DownloadProgressChangedEventHandler))] [assembly: TypeForwardedTo(typeof(DownloadStringCompletedEventArgs))] [assembly: TypeForwardedTo(typeof(DownloadStringCompletedEventHandler))] [assembly: TypeForwardedTo(typeof(EndPoint))] [assembly: TypeForwardedTo(typeof(FileWebRequest))] [assembly: TypeForwardedTo(typeof(FileWebResponse))] [assembly: TypeForwardedTo(typeof(FtpStatusCode))] [assembly: TypeForwardedTo(typeof(FtpWebRequest))] [assembly: TypeForwardedTo(typeof(FtpWebResponse))] [assembly: TypeForwardedTo(typeof(GlobalProxySelection))] [assembly: TypeForwardedTo(typeof(ByteArrayContent))] [assembly: TypeForwardedTo(typeof(ClientCertificateOption))] [assembly: TypeForwardedTo(typeof(DelegatingHandler))] [assembly: TypeForwardedTo(typeof(FormUrlEncodedContent))] [assembly: TypeForwardedTo(typeof(AuthenticationHeaderValue))] [assembly: TypeForwardedTo(typeof(CacheControlHeaderValue))] [assembly: TypeForwardedTo(typeof(ContentDispositionHeaderValue))] [assembly: TypeForwardedTo(typeof(ContentRangeHeaderValue))] [assembly: TypeForwardedTo(typeof(EntityTagHeaderValue))] [assembly: TypeForwardedTo(typeof(HttpContentHeaders))] [assembly: TypeForwardedTo(typeof(HttpHeaders))] [assembly: TypeForwardedTo(typeof(HttpHeaderValueCollection<>))] [assembly: TypeForwardedTo(typeof(HttpRequestHeaders))] [assembly: TypeForwardedTo(typeof(HttpResponseHeaders))] [assembly: TypeForwardedTo(typeof(MediaTypeHeaderValue))] [assembly: TypeForwardedTo(typeof(MediaTypeWithQualityHeaderValue))] [assembly: TypeForwardedTo(typeof(NameValueHeaderValue))] [assembly: TypeForwardedTo(typeof(NameValueWithParametersHeaderValue))] [assembly: TypeForwardedTo(typeof(ProductHeaderValue))] [assembly: TypeForwardedTo(typeof(ProductInfoHeaderValue))] [assembly: TypeForwardedTo(typeof(RangeConditionHeaderValue))] [assembly: TypeForwardedTo(typeof(RangeHeaderValue))] [assembly: TypeForwardedTo(typeof(RangeItemHeaderValue))] [assembly: TypeForwardedTo(typeof(RetryConditionHeaderValue))] [assembly: TypeForwardedTo(typeof(StringWithQualityHeaderValue))] [assembly: TypeForwardedTo(typeof(TransferCodingHeaderValue))] [assembly: TypeForwardedTo(typeof(TransferCodingWithQualityHeaderValue))] [assembly: TypeForwardedTo(typeof(ViaHeaderValue))] [assembly: TypeForwardedTo(typeof(WarningHeaderValue))] [assembly: TypeForwardedTo(typeof(HttpClient))] [assembly: TypeForwardedTo(typeof(HttpClientHandler))] [assembly: TypeForwardedTo(typeof(HttpCompletionOption))] [assembly: TypeForwardedTo(typeof(HttpContent))] [assembly: TypeForwardedTo(typeof(HttpMessageHandler))] [assembly: TypeForwardedTo(typeof(HttpMessageInvoker))] [assembly: TypeForwardedTo(typeof(HttpMethod))] [assembly: TypeForwardedTo(typeof(HttpRequestException))] [assembly: TypeForwardedTo(typeof(HttpRequestMessage))] [assembly: TypeForwardedTo(typeof(HttpResponseMessage))] [assembly: TypeForwardedTo(typeof(MessageProcessingHandler))] [assembly: TypeForwardedTo(typeof(MultipartContent))] [assembly: TypeForwardedTo(typeof(MultipartFormDataContent))] [assembly: TypeForwardedTo(typeof(ReadOnlyMemoryContent))] [assembly: TypeForwardedTo(typeof(StreamContent))] [assembly: TypeForwardedTo(typeof(StringContent))] [assembly: TypeForwardedTo(typeof(HttpContinueDelegate))] [assembly: TypeForwardedTo(typeof(HttpListener))] [assembly: TypeForwardedTo(typeof(HttpListenerBasicIdentity))] [assembly: TypeForwardedTo(typeof(HttpListenerContext))] [assembly: TypeForwardedTo(typeof(HttpListenerException))] [assembly: TypeForwardedTo(typeof(HttpListenerPrefixCollection))] [assembly: TypeForwardedTo(typeof(HttpListenerRequest))] [assembly: TypeForwardedTo(typeof(HttpListenerResponse))] [assembly: TypeForwardedTo(typeof(HttpListenerTimeoutManager))] [assembly: TypeForwardedTo(typeof(HttpRequestHeader))] [assembly: TypeForwardedTo(typeof(HttpResponseHeader))] [assembly: TypeForwardedTo(typeof(HttpStatusCode))] [assembly: TypeForwardedTo(typeof(HttpVersion))] [assembly: TypeForwardedTo(typeof(HttpWebRequest))] [assembly: TypeForwardedTo(typeof(HttpWebResponse))] [assembly: TypeForwardedTo(typeof(IAuthenticationModule))] [assembly: TypeForwardedTo(typeof(ICredentialPolicy))] [assembly: TypeForwardedTo(typeof(ICredentials))] [assembly: TypeForwardedTo(typeof(ICredentialsByHost))] [assembly: TypeForwardedTo(typeof(IPAddress))] [assembly: TypeForwardedTo(typeof(IPEndPoint))] [assembly: TypeForwardedTo(typeof(IPHostEntry))] [assembly: TypeForwardedTo(typeof(IWebProxy))] [assembly: TypeForwardedTo(typeof(IWebProxyScript))] [assembly: TypeForwardedTo(typeof(IWebRequestCreate))] [assembly: TypeForwardedTo(typeof(AlternateView))] [assembly: TypeForwardedTo(typeof(AlternateViewCollection))] [assembly: TypeForwardedTo(typeof(Attachment))] [assembly: TypeForwardedTo(typeof(AttachmentBase))] [assembly: TypeForwardedTo(typeof(AttachmentCollection))] [assembly: TypeForwardedTo(typeof(DeliveryNotificationOptions))] [assembly: TypeForwardedTo(typeof(LinkedResource))] [assembly: TypeForwardedTo(typeof(LinkedResourceCollection))] [assembly: TypeForwardedTo(typeof(MailAddress))] [assembly: TypeForwardedTo(typeof(MailAddressCollection))] [assembly: TypeForwardedTo(typeof(MailMessage))] [assembly: TypeForwardedTo(typeof(MailPriority))] [assembly: TypeForwardedTo(typeof(SendCompletedEventHandler))] [assembly: TypeForwardedTo(typeof(SmtpClient))] [assembly: TypeForwardedTo(typeof(SmtpDeliveryFormat))] [assembly: TypeForwardedTo(typeof(SmtpDeliveryMethod))] [assembly: TypeForwardedTo(typeof(SmtpException))] [assembly: TypeForwardedTo(typeof(SmtpFailedRecipientException))] [assembly: TypeForwardedTo(typeof(SmtpFailedRecipientsException))] [assembly: TypeForwardedTo(typeof(SmtpStatusCode))] [assembly: TypeForwardedTo(typeof(ContentDisposition))] [assembly: TypeForwardedTo(typeof(ContentType))] [assembly: TypeForwardedTo(typeof(DispositionTypeNames))] [assembly: TypeForwardedTo(typeof(MediaTypeNames))] [assembly: TypeForwardedTo(typeof(TransferEncoding))] [assembly: TypeForwardedTo(typeof(NetworkCredential))] [assembly: TypeForwardedTo(typeof(DuplicateAddressDetectionState))] [assembly: TypeForwardedTo(typeof(GatewayIPAddressInformation))] [assembly: TypeForwardedTo(typeof(GatewayIPAddressInformationCollection))] [assembly: TypeForwardedTo(typeof(IcmpV4Statistics))] [assembly: TypeForwardedTo(typeof(IcmpV6Statistics))] [assembly: TypeForwardedTo(typeof(IPAddressCollection))] [assembly: TypeForwardedTo(typeof(IPAddressInformation))] [assembly: TypeForwardedTo(typeof(IPAddressInformationCollection))] [assembly: TypeForwardedTo(typeof(IPGlobalProperties))] [assembly: TypeForwardedTo(typeof(IPGlobalStatistics))] [assembly: TypeForwardedTo(typeof(IPInterfaceProperties))] [assembly: TypeForwardedTo(typeof(IPInterfaceStatistics))] [assembly: TypeForwardedTo(typeof(IPStatus))] [assembly: TypeForwardedTo(typeof(IPv4InterfaceProperties))] [assembly: TypeForwardedTo(typeof(IPv4InterfaceStatistics))] [assembly: TypeForwardedTo(typeof(IPv6InterfaceProperties))] [assembly: TypeForwardedTo(typeof(MulticastIPAddressInformation))] [assembly: TypeForwardedTo(typeof(MulticastIPAddressInformationCollection))] [assembly: TypeForwardedTo(typeof(NetBiosNodeType))] [assembly: TypeForwardedTo(typeof(NetworkAddressChangedEventHandler))] [assembly: TypeForwardedTo(typeof(NetworkAvailabilityChangedEventHandler))] [assembly: TypeForwardedTo(typeof(NetworkAvailabilityEventArgs))] [assembly: TypeForwardedTo(typeof(NetworkChange))] [assembly: TypeForwardedTo(typeof(NetworkInformationException))] [assembly: TypeForwardedTo(typeof(NetworkInterface))] [assembly: TypeForwardedTo(typeof(NetworkInterfaceComponent))] [assembly: TypeForwardedTo(typeof(NetworkInterfaceType))] [assembly: TypeForwardedTo(typeof(OperationalStatus))] [assembly: TypeForwardedTo(typeof(PhysicalAddress))] [assembly: TypeForwardedTo(typeof(Ping))] [assembly: TypeForwardedTo(typeof(PingCompletedEventArgs))] [assembly: TypeForwardedTo(typeof(PingCompletedEventHandler))] [assembly: TypeForwardedTo(typeof(PingException))] [assembly: TypeForwardedTo(typeof(PingOptions))] [assembly: TypeForwardedTo(typeof(PingReply))] [assembly: TypeForwardedTo(typeof(PrefixOrigin))] [assembly: TypeForwardedTo(typeof(ScopeLevel))] [assembly: TypeForwardedTo(typeof(SuffixOrigin))] [assembly: TypeForwardedTo(typeof(TcpConnectionInformation))] [assembly: TypeForwardedTo(typeof(TcpState))] [assembly: TypeForwardedTo(typeof(TcpStatistics))] [assembly: TypeForwardedTo(typeof(UdpStatistics))] [assembly: TypeForwardedTo(typeof(UnicastIPAddressInformation))] [assembly: TypeForwardedTo(typeof(UnicastIPAddressInformationCollection))] [assembly: TypeForwardedTo(typeof(OpenReadCompletedEventArgs))] [assembly: TypeForwardedTo(typeof(OpenReadCompletedEventHandler))] [assembly: TypeForwardedTo(typeof(OpenWriteCompletedEventArgs))] [assembly: TypeForwardedTo(typeof(OpenWriteCompletedEventHandler))] [assembly: TypeForwardedTo(typeof(ProtocolViolationException))] [assembly: TypeForwardedTo(typeof(AuthenticatedStream))] [assembly: TypeForwardedTo(typeof(AuthenticationLevel))] [assembly: TypeForwardedTo(typeof(EncryptionPolicy))] [assembly: TypeForwardedTo(typeof(LocalCertificateSelectionCallback))] [assembly: TypeForwardedTo(typeof(NegotiateStream))] [assembly: TypeForwardedTo(typeof(ProtectionLevel))] [assembly: TypeForwardedTo(typeof(RemoteCertificateValidationCallback))] [assembly: TypeForwardedTo(typeof(ServerCertificateSelectionCallback))] [assembly: TypeForwardedTo(typeof(SslApplicationProtocol))] [assembly: TypeForwardedTo(typeof(SslClientAuthenticationOptions))] [assembly: TypeForwardedTo(typeof(SslPolicyErrors))] [assembly: TypeForwardedTo(typeof(SslServerAuthenticationOptions))] [assembly: TypeForwardedTo(typeof(SslStream))] [assembly: TypeForwardedTo(typeof(SecurityProtocolType))] [assembly: TypeForwardedTo(typeof(ServicePoint))] [assembly: TypeForwardedTo(typeof(ServicePointManager))] [assembly: TypeForwardedTo(typeof(SocketAddress))] [assembly: TypeForwardedTo(typeof(AddressFamily))] [assembly: TypeForwardedTo(typeof(IOControlCode))] [assembly: TypeForwardedTo(typeof(IPPacketInformation))] [assembly: TypeForwardedTo(typeof(IPProtectionLevel))] [assembly: TypeForwardedTo(typeof(IPv6MulticastOption))] [assembly: TypeForwardedTo(typeof(LingerOption))] [assembly: TypeForwardedTo(typeof(MulticastOption))] [assembly: TypeForwardedTo(typeof(NetworkStream))] [assembly: TypeForwardedTo(typeof(ProtocolFamily))] [assembly: TypeForwardedTo(typeof(ProtocolType))] [assembly: TypeForwardedTo(typeof(SelectMode))] [assembly: TypeForwardedTo(typeof(SendPacketsElement))] [assembly: TypeForwardedTo(typeof(Socket))] [assembly: TypeForwardedTo(typeof(SocketAsyncEventArgs))] [assembly: TypeForwardedTo(typeof(SocketAsyncOperation))] [assembly: TypeForwardedTo(typeof(SocketError))] [assembly: TypeForwardedTo(typeof(SocketException))] [assembly: TypeForwardedTo(typeof(SocketFlags))] [assembly: TypeForwardedTo(typeof(SocketInformation))] [assembly: TypeForwardedTo(typeof(SocketInformationOptions))] [assembly: TypeForwardedTo(typeof(SocketOptionLevel))] [assembly: TypeForwardedTo(typeof(SocketOptionName))] [assembly: TypeForwardedTo(typeof(SocketReceiveFromResult))] [assembly: TypeForwardedTo(typeof(SocketReceiveMessageFromResult))] [assembly: TypeForwardedTo(typeof(SocketShutdown))] [assembly: TypeForwardedTo(typeof(SocketTaskExtensions))] [assembly: TypeForwardedTo(typeof(SocketType))] [assembly: TypeForwardedTo(typeof(TcpClient))] [assembly: TypeForwardedTo(typeof(TcpListener))] [assembly: TypeForwardedTo(typeof(TransmitFileOptions))] [assembly: TypeForwardedTo(typeof(UdpClient))] [assembly: TypeForwardedTo(typeof(UdpReceiveResult))] [assembly: TypeForwardedTo(typeof(UnixDomainSocketEndPoint))] [assembly: TypeForwardedTo(typeof(TransportContext))] [assembly: TypeForwardedTo(typeof(UploadDataCompletedEventArgs))] [assembly: TypeForwardedTo(typeof(UploadDataCompletedEventHandler))] [assembly: TypeForwardedTo(typeof(UploadFileCompletedEventArgs))] [assembly: TypeForwardedTo(typeof(UploadFileCompletedEventHandler))] [assembly: TypeForwardedTo(typeof(UploadProgressChangedEventArgs))] [assembly: TypeForwardedTo(typeof(UploadProgressChangedEventHandler))] [assembly: TypeForwardedTo(typeof(UploadStringCompletedEventArgs))] [assembly: TypeForwardedTo(typeof(UploadStringCompletedEventHandler))] [assembly: TypeForwardedTo(typeof(UploadValuesCompletedEventArgs))] [assembly: TypeForwardedTo(typeof(UploadValuesCompletedEventHandler))] [assembly: TypeForwardedTo(typeof(WebClient))] [assembly: TypeForwardedTo(typeof(WebException))] [assembly: TypeForwardedTo(typeof(WebExceptionStatus))] [assembly: TypeForwardedTo(typeof(WebHeaderCollection))] [assembly: TypeForwardedTo(typeof(WebProxy))] [assembly: TypeForwardedTo(typeof(WebRequest))] [assembly: TypeForwardedTo(typeof(WebRequestMethods))] [assembly: TypeForwardedTo(typeof(WebResponse))] [assembly: TypeForwardedTo(typeof(ClientWebSocket))] [assembly: TypeForwardedTo(typeof(ClientWebSocketOptions))] [assembly: TypeForwardedTo(typeof(HttpListenerWebSocketContext))] [assembly: TypeForwardedTo(typeof(ValueWebSocketReceiveResult))] [assembly: TypeForwardedTo(typeof(WebSocket))] [assembly: TypeForwardedTo(typeof(WebSocketCloseStatus))] [assembly: TypeForwardedTo(typeof(WebSocketContext))] [assembly: TypeForwardedTo(typeof(WebSocketError))] [assembly: TypeForwardedTo(typeof(WebSocketException))] [assembly: TypeForwardedTo(typeof(WebSocketMessageType))] [assembly: TypeForwardedTo(typeof(WebSocketReceiveResult))] [assembly: TypeForwardedTo(typeof(WebSocketState))] [assembly: TypeForwardedTo(typeof(WebUtility))] [assembly: TypeForwardedTo(typeof(NetPipeStyleUriParser))] [assembly: TypeForwardedTo(typeof(NetTcpStyleUriParser))] [assembly: TypeForwardedTo(typeof(NewsStyleUriParser))] [assembly: TypeForwardedTo(typeof(NonSerializedAttribute))] [assembly: TypeForwardedTo(typeof(NotFiniteNumberException))] [assembly: TypeForwardedTo(typeof(NotImplementedException))] [assembly: TypeForwardedTo(typeof(NotSupportedException))] [assembly: TypeForwardedTo(typeof(Nullable))] [assembly: TypeForwardedTo(typeof(Nullable<>))] [assembly: TypeForwardedTo(typeof(NullReferenceException))] [assembly: TypeForwardedTo(typeof(BigInteger))] [assembly: TypeForwardedTo(typeof(Complex))] [assembly: TypeForwardedTo(typeof(Matrix3x2))] [assembly: TypeForwardedTo(typeof(Matrix4x4))] [assembly: TypeForwardedTo(typeof(Plane))] [assembly: TypeForwardedTo(typeof(Quaternion))] [assembly: TypeForwardedTo(typeof(Vector))] [assembly: TypeForwardedTo(typeof(Vector<>))] [assembly: TypeForwardedTo(typeof(Vector2))] [assembly: TypeForwardedTo(typeof(Vector3))] [assembly: TypeForwardedTo(typeof(Vector4))] [assembly: TypeForwardedTo(typeof(object))] [assembly: TypeForwardedTo(typeof(ObjectDisposedException))] [assembly: TypeForwardedTo(typeof(ObsoleteAttribute))] [assembly: TypeForwardedTo(typeof(OperatingSystem))] [assembly: TypeForwardedTo(typeof(OperationCanceledException))] [assembly: TypeForwardedTo(typeof(OutOfMemoryException))] [assembly: TypeForwardedTo(typeof(OverflowException))] [assembly: TypeForwardedTo(typeof(ParamArrayAttribute))] [assembly: TypeForwardedTo(typeof(PlatformID))] [assembly: TypeForwardedTo(typeof(PlatformNotSupportedException))] [assembly: TypeForwardedTo(typeof(Predicate<>))] [assembly: TypeForwardedTo(typeof(Progress<>))] [assembly: TypeForwardedTo(typeof(Random))] [assembly: TypeForwardedTo(typeof(Range))] [assembly: TypeForwardedTo(typeof(RankException))] [assembly: TypeForwardedTo(typeof(ReadOnlyMemory<>))] [assembly: TypeForwardedTo(typeof(ReadOnlySpan<>))] [assembly: TypeForwardedTo(typeof(AmbiguousMatchException))] [assembly: TypeForwardedTo(typeof(Assembly))] [assembly: TypeForwardedTo(typeof(AssemblyAlgorithmIdAttribute))] [assembly: TypeForwardedTo(typeof(AssemblyCompanyAttribute))] [assembly: TypeForwardedTo(typeof(AssemblyConfigurationAttribute))] [assembly: TypeForwardedTo(typeof(AssemblyContentType))] [assembly: TypeForwardedTo(typeof(AssemblyCopyrightAttribute))] [assembly: TypeForwardedTo(typeof(AssemblyCultureAttribute))] [assembly: TypeForwardedTo(typeof(AssemblyDefaultAliasAttribute))] [assembly: TypeForwardedTo(typeof(AssemblyDelaySignAttribute))] [assembly: TypeForwardedTo(typeof(AssemblyDescriptionAttribute))] [assembly: TypeForwardedTo(typeof(AssemblyFileVersionAttribute))] [assembly: TypeForwardedTo(typeof(AssemblyFlagsAttribute))] [assembly: TypeForwardedTo(typeof(AssemblyInformationalVersionAttribute))] [assembly: TypeForwardedTo(typeof(AssemblyKeyFileAttribute))] [assembly: TypeForwardedTo(typeof(AssemblyKeyNameAttribute))] [assembly: TypeForwardedTo(typeof(AssemblyMetadataAttribute))] [assembly: TypeForwardedTo(typeof(AssemblyName))] [assembly: TypeForwardedTo(typeof(AssemblyNameFlags))] [assembly: TypeForwardedTo(typeof(AssemblyNameProxy))] [assembly: TypeForwardedTo(typeof(AssemblyProductAttribute))] [assembly: TypeForwardedTo(typeof(AssemblySignatureKeyAttribute))] [assembly: TypeForwardedTo(typeof(AssemblyTitleAttribute))] [assembly: TypeForwardedTo(typeof(AssemblyTrademarkAttribute))] [assembly: TypeForwardedTo(typeof(AssemblyVersionAttribute))] [assembly: TypeForwardedTo(typeof(Binder))] [assembly: TypeForwardedTo(typeof(BindingFlags))] [assembly: TypeForwardedTo(typeof(CallingConventions))] [assembly: TypeForwardedTo(typeof(ConstructorInfo))] [assembly: TypeForwardedTo(typeof(CustomAttributeData))] [assembly: TypeForwardedTo(typeof(CustomAttributeExtensions))] [assembly: TypeForwardedTo(typeof(CustomAttributeFormatException))] [assembly: TypeForwardedTo(typeof(CustomAttributeNamedArgument))] [assembly: TypeForwardedTo(typeof(CustomAttributeTypedArgument))] [assembly: TypeForwardedTo(typeof(DefaultMemberAttribute))] [assembly: TypeForwardedTo(typeof(DispatchProxy))] [assembly: TypeForwardedTo(typeof(AssemblyBuilder))] [assembly: TypeForwardedTo(typeof(AssemblyBuilderAccess))] [assembly: TypeForwardedTo(typeof(ConstructorBuilder))] [assembly: TypeForwardedTo(typeof(CustomAttributeBuilder))] [assembly: TypeForwardedTo(typeof(DynamicILInfo))] [assembly: TypeForwardedTo(typeof(DynamicMethod))] [assembly: TypeForwardedTo(typeof(EnumBuilder))] [assembly: TypeForwardedTo(typeof(EventBuilder))] [assembly: TypeForwardedTo(typeof(EventToken))] [assembly: TypeForwardedTo(typeof(ExceptionHandler))] [assembly: TypeForwardedTo(typeof(FieldBuilder))] [assembly: TypeForwardedTo(typeof(FieldToken))] [assembly: TypeForwardedTo(typeof(FlowControl))] [assembly: TypeForwardedTo(typeof(GenericTypeParameterBuilder))] [assembly: TypeForwardedTo(typeof(ILGenerator))] [assembly: TypeForwardedTo(typeof(Label))] [assembly: TypeForwardedTo(typeof(LocalBuilder))] [assembly: TypeForwardedTo(typeof(MethodBuilder))] [assembly: TypeForwardedTo(typeof(MethodToken))] [assembly: TypeForwardedTo(typeof(ModuleBuilder))] [assembly: TypeForwardedTo(typeof(OpCode))] [assembly: TypeForwardedTo(typeof(OpCodes))] [assembly: TypeForwardedTo(typeof(OpCodeType))] [assembly: TypeForwardedTo(typeof(OperandType))] [assembly: TypeForwardedTo(typeof(PackingSize))] [assembly: TypeForwardedTo(typeof(ParameterBuilder))] [assembly: TypeForwardedTo(typeof(ParameterToken))] [assembly: TypeForwardedTo(typeof(PropertyBuilder))] [assembly: TypeForwardedTo(typeof(PropertyToken))] [assembly: TypeForwardedTo(typeof(SignatureHelper))] [assembly: TypeForwardedTo(typeof(SignatureToken))] [assembly: TypeForwardedTo(typeof(StackBehaviour))] [assembly: TypeForwardedTo(typeof(StringToken))] [assembly: TypeForwardedTo(typeof(TypeBuilder))] [assembly: TypeForwardedTo(typeof(TypeToken))] [assembly: TypeForwardedTo(typeof(EventAttributes))] [assembly: TypeForwardedTo(typeof(EventInfo))] [assembly: TypeForwardedTo(typeof(ExceptionHandlingClause))] [assembly: TypeForwardedTo(typeof(ExceptionHandlingClauseOptions))] [assembly: TypeForwardedTo(typeof(FieldAttributes))] [assembly: TypeForwardedTo(typeof(FieldInfo))] [assembly: TypeForwardedTo(typeof(GenericParameterAttributes))] [assembly: TypeForwardedTo(typeof(ICustomAttributeProvider))] [assembly: TypeForwardedTo(typeof(ImageFileMachine))] [assembly: TypeForwardedTo(typeof(InterfaceMapping))] [assembly: TypeForwardedTo(typeof(IntrospectionExtensions))] [assembly: TypeForwardedTo(typeof(InvalidFilterCriteriaException))] [assembly: TypeForwardedTo(typeof(IReflect))] [assembly: TypeForwardedTo(typeof(IReflectableType))] [assembly: TypeForwardedTo(typeof(LocalVariableInfo))] [assembly: TypeForwardedTo(typeof(ManifestResourceInfo))] [assembly: TypeForwardedTo(typeof(MemberFilter))] [assembly: TypeForwardedTo(typeof(MemberInfo))] [assembly: TypeForwardedTo(typeof(MemberTypes))] [assembly: TypeForwardedTo(typeof(MethodAttributes))] [assembly: TypeForwardedTo(typeof(MethodBase))] [assembly: TypeForwardedTo(typeof(MethodBody))] [assembly: TypeForwardedTo(typeof(MethodImplAttributes))] [assembly: TypeForwardedTo(typeof(MethodInfo))] [assembly: TypeForwardedTo(typeof(Missing))] [assembly: TypeForwardedTo(typeof(Module))] [assembly: TypeForwardedTo(typeof(ModuleResolveEventHandler))] [assembly: TypeForwardedTo(typeof(ObfuscateAssemblyAttribute))] [assembly: TypeForwardedTo(typeof(ObfuscationAttribute))] [assembly: TypeForwardedTo(typeof(ParameterAttributes))] [assembly: TypeForwardedTo(typeof(ParameterInfo))] [assembly: TypeForwardedTo(typeof(ParameterModifier))] [assembly: TypeForwardedTo(typeof(Pointer))] [assembly: TypeForwardedTo(typeof(PortableExecutableKinds))] [assembly: TypeForwardedTo(typeof(ProcessorArchitecture))] [assembly: TypeForwardedTo(typeof(PropertyAttributes))] [assembly: TypeForwardedTo(typeof(PropertyInfo))] [assembly: TypeForwardedTo(typeof(ReflectionContext))] [assembly: TypeForwardedTo(typeof(ReflectionTypeLoadException))] [assembly: TypeForwardedTo(typeof(ResourceAttributes))] [assembly: TypeForwardedTo(typeof(ResourceLocation))] [assembly: TypeForwardedTo(typeof(RuntimeReflectionExtensions))] [assembly: TypeForwardedTo(typeof(StrongNameKeyPair))] [assembly: TypeForwardedTo(typeof(TargetException))] [assembly: TypeForwardedTo(typeof(TargetInvocationException))] [assembly: TypeForwardedTo(typeof(TargetParameterCountException))] [assembly: TypeForwardedTo(typeof(TypeAttributes))] [assembly: TypeForwardedTo(typeof(TypeDelegator))] [assembly: TypeForwardedTo(typeof(TypeFilter))] [assembly: TypeForwardedTo(typeof(TypeInfo))] [assembly: TypeForwardedTo(typeof(ResolveEventArgs))] [assembly: TypeForwardedTo(typeof(ResolveEventHandler))] [assembly: TypeForwardedTo(typeof(IResourceReader))] [assembly: TypeForwardedTo(typeof(IResourceWriter))] [assembly: TypeForwardedTo(typeof(MissingManifestResourceException))] [assembly: TypeForwardedTo(typeof(MissingSatelliteAssemblyException))] [assembly: TypeForwardedTo(typeof(NeutralResourcesLanguageAttribute))] [assembly: TypeForwardedTo(typeof(ResourceManager))] [assembly: TypeForwardedTo(typeof(ResourceReader))] [assembly: TypeForwardedTo(typeof(ResourceSet))] [assembly: TypeForwardedTo(typeof(ResourceWriter))] [assembly: TypeForwardedTo(typeof(SatelliteContractVersionAttribute))] [assembly: TypeForwardedTo(typeof(UltimateResourceFallbackLocation))] [assembly: TypeForwardedTo(typeof(AmbiguousImplementationException))] [assembly: TypeForwardedTo(typeof(AssemblyTargetedPatchBandAttribute))] [assembly: TypeForwardedTo(typeof(AccessedThroughPropertyAttribute))] [assembly: TypeForwardedTo(typeof(AsyncIteratorMethodBuilder))] [assembly: TypeForwardedTo(typeof(AsyncIteratorStateMachineAttribute))] [assembly: TypeForwardedTo(typeof(AsyncMethodBuilderAttribute))] [assembly: TypeForwardedTo(typeof(AsyncStateMachineAttribute))] [assembly: TypeForwardedTo(typeof(AsyncTaskMethodBuilder))] [assembly: TypeForwardedTo(typeof(AsyncTaskMethodBuilder<>))] [assembly: TypeForwardedTo(typeof(AsyncValueTaskMethodBuilder))] [assembly: TypeForwardedTo(typeof(AsyncValueTaskMethodBuilder<>))] [assembly: TypeForwardedTo(typeof(AsyncVoidMethodBuilder))] [assembly: TypeForwardedTo(typeof(CallConvCdecl))] [assembly: TypeForwardedTo(typeof(CallConvFastcall))] [assembly: TypeForwardedTo(typeof(CallConvStdcall))] [assembly: TypeForwardedTo(typeof(CallConvThiscall))] [assembly: TypeForwardedTo(typeof(CallerFilePathAttribute))] [assembly: TypeForwardedTo(typeof(CallerLineNumberAttribute))] [assembly: TypeForwardedTo(typeof(CallerMemberNameAttribute))] [assembly: TypeForwardedTo(typeof(CallSite))] [assembly: TypeForwardedTo(typeof(CallSite<>))] [assembly: TypeForwardedTo(typeof(CallSiteBinder))] [assembly: TypeForwardedTo(typeof(CallSiteHelpers))] [assembly: TypeForwardedTo(typeof(CompilationRelaxations))] [assembly: TypeForwardedTo(typeof(CompilationRelaxationsAttribute))] [assembly: TypeForwardedTo(typeof(CompilerGeneratedAttribute))] [assembly: TypeForwardedTo(typeof(CompilerGlobalScopeAttribute))] [assembly: TypeForwardedTo(typeof(CompilerMarshalOverride))] [assembly: TypeForwardedTo(typeof(ConditionalWeakTable<, >))] [assembly: TypeForwardedTo(typeof(ConfiguredAsyncDisposable))] [assembly: TypeForwardedTo(typeof(ConfiguredCancelableAsyncEnumerable<>))] [assembly: TypeForwardedTo(typeof(ConfiguredTaskAwaitable))] [assembly: TypeForwardedTo(typeof(ConfiguredTaskAwaitable<>))] [assembly: TypeForwardedTo(typeof(ConfiguredValueTaskAwaitable))] [assembly: TypeForwardedTo(typeof(ConfiguredValueTaskAwaitable<>))] [assembly: TypeForwardedTo(typeof(ContractHelper))] [assembly: TypeForwardedTo(typeof(CustomConstantAttribute))] [assembly: TypeForwardedTo(typeof(DateTimeConstantAttribute))] [assembly: TypeForwardedTo(typeof(DebugInfoGenerator))] [assembly: TypeForwardedTo(typeof(DecimalConstantAttribute))] [assembly: TypeForwardedTo(typeof(DefaultDependencyAttribute))] [assembly: TypeForwardedTo(typeof(DependencyAttribute))] [assembly: TypeForwardedTo(typeof(DisablePrivateReflectionAttribute))] [assembly: TypeForwardedTo(typeof(DiscardableAttribute))] [assembly: TypeForwardedTo(typeof(DynamicAttribute))] [assembly: TypeForwardedTo(typeof(EnumeratorCancellationAttribute))] [assembly: TypeForwardedTo(typeof(ExtensionAttribute))] [assembly: TypeForwardedTo(typeof(FixedAddressValueTypeAttribute))] [assembly: TypeForwardedTo(typeof(FixedBufferAttribute))] [assembly: TypeForwardedTo(typeof(FormattableStringFactory))] [assembly: TypeForwardedTo(typeof(HasCopySemanticsAttribute))] [assembly: TypeForwardedTo(typeof(IAsyncStateMachine))] [assembly: TypeForwardedTo(typeof(ICriticalNotifyCompletion))] [assembly: TypeForwardedTo(typeof(IndexerNameAttribute))] [assembly: TypeForwardedTo(typeof(INotifyCompletion))] [assembly: TypeForwardedTo(typeof(InternalsVisibleToAttribute))] [assembly: TypeForwardedTo(typeof(IRuntimeVariables))] [assembly: TypeForwardedTo(typeof(IsBoxed))] [assembly: TypeForwardedTo(typeof(IsByRefLikeAttribute))] [assembly: TypeForwardedTo(typeof(IsByValue))] [assembly: TypeForwardedTo(typeof(IsConst))] [assembly: TypeForwardedTo(typeof(IsCopyConstructed))] [assembly: TypeForwardedTo(typeof(IsExplicitlyDereferenced))] [assembly: TypeForwardedTo(typeof(IsImplicitlyDereferenced))] [assembly: TypeForwardedTo(typeof(IsJitIntrinsic))] [assembly: TypeForwardedTo(typeof(IsLong))] [assembly: TypeForwardedTo(typeof(IsPinned))] [assembly: TypeForwardedTo(typeof(IsReadOnlyAttribute))] [assembly: TypeForwardedTo(typeof(IsSignUnspecifiedByte))] [assembly: TypeForwardedTo(typeof(IStrongBox))] [assembly: TypeForwardedTo(typeof(IsUdtReturn))] [assembly: TypeForwardedTo(typeof(IsVolatile))] [assembly: TypeForwardedTo(typeof(IteratorStateMachineAttribute))] [assembly: TypeForwardedTo(typeof(ITuple))] [assembly: TypeForwardedTo(typeof(IUnknownConstantAttribute))] [assembly: TypeForwardedTo(typeof(LoadHint))] [assembly: TypeForwardedTo(typeof(MethodCodeType))] [assembly: TypeForwardedTo(typeof(MethodImplAttribute))] [assembly: TypeForwardedTo(typeof(MethodImplOptions))] [assembly: TypeForwardedTo(typeof(NativeCppClassAttribute))] [assembly: TypeForwardedTo(typeof(ReadOnlyCollectionBuilder<>))] [assembly: TypeForwardedTo(typeof(ReferenceAssemblyAttribute))] [assembly: TypeForwardedTo(typeof(RequiredAttributeAttribute))] [assembly: TypeForwardedTo(typeof(RuleCache<>))] [assembly: TypeForwardedTo(typeof(RuntimeCompatibilityAttribute))] [assembly: TypeForwardedTo(typeof(RuntimeFeature))] [assembly: TypeForwardedTo(typeof(RuntimeHelpers))] [assembly: TypeForwardedTo(typeof(RuntimeWrappedException))] [assembly: TypeForwardedTo(typeof(ScopelessEnumAttribute))] [assembly: TypeForwardedTo(typeof(SpecialNameAttribute))] [assembly: TypeForwardedTo(typeof(StateMachineAttribute))] [assembly: TypeForwardedTo(typeof(StringFreezingAttribute))] [assembly: TypeForwardedTo(typeof(StrongBox<>))] [assembly: TypeForwardedTo(typeof(SuppressIldasmAttribute))] [assembly: TypeForwardedTo(typeof(SwitchExpressionException))] [assembly: TypeForwardedTo(typeof(TaskAwaiter))] [assembly: TypeForwardedTo(typeof(TaskAwaiter<>))] [assembly: TypeForwardedTo(typeof(TupleElementNamesAttribute))] [assembly: TypeForwardedTo(typeof(TypeForwardedFromAttribute))] [assembly: TypeForwardedTo(typeof(TypeForwardedToAttribute))] [assembly: TypeForwardedTo(typeof(UnsafeValueTypeAttribute))] [assembly: TypeForwardedTo(typeof(ValueTaskAwaiter))] [assembly: TypeForwardedTo(typeof(ValueTaskAwaiter<>))] [assembly: TypeForwardedTo(typeof(YieldAwaitable))] [assembly: TypeForwardedTo(typeof(Cer))] [assembly: TypeForwardedTo(typeof(Consistency))] [assembly: TypeForwardedTo(typeof(CriticalFinalizerObject))] [assembly: TypeForwardedTo(typeof(PrePrepareMethodAttribute))] [assembly: TypeForwardedTo(typeof(ReliabilityContractAttribute))] [assembly: TypeForwardedTo(typeof(ExceptionDispatchInfo))] [assembly: TypeForwardedTo(typeof(FirstChanceExceptionEventArgs))] [assembly: TypeForwardedTo(typeof(HandleProcessCorruptedStateExceptionsAttribute))] [assembly: TypeForwardedTo(typeof(GCLargeObjectHeapCompactionMode))] [assembly: TypeForwardedTo(typeof(GCLatencyMode))] [assembly: TypeForwardedTo(typeof(GCSettings))] [assembly: TypeForwardedTo(typeof(AllowReversePInvokeCallsAttribute))] [assembly: TypeForwardedTo(typeof(Architecture))] [assembly: TypeForwardedTo(typeof(ArrayWithOffset))] [assembly: TypeForwardedTo(typeof(AutomationProxyAttribute))] [assembly: TypeForwardedTo(typeof(BestFitMappingAttribute))] [assembly: TypeForwardedTo(typeof(BStrWrapper))] [assembly: TypeForwardedTo(typeof(CallingConvention))] [assembly: TypeForwardedTo(typeof(CharSet))] [assembly: TypeForwardedTo(typeof(ClassInterfaceAttribute))] [assembly: TypeForwardedTo(typeof(ClassInterfaceType))] [assembly: TypeForwardedTo(typeof(CoClassAttribute))] [assembly: TypeForwardedTo(typeof(ComAliasNameAttribute))] [assembly: TypeForwardedTo(typeof(ComAwareEventInfo))] [assembly: TypeForwardedTo(typeof(ComCompatibleVersionAttribute))] [assembly: TypeForwardedTo(typeof(ComConversionLossAttribute))] [assembly: TypeForwardedTo(typeof(ComDefaultInterfaceAttribute))] [assembly: TypeForwardedTo(typeof(ComEventInterfaceAttribute))] [assembly: TypeForwardedTo(typeof(ComEventsHelper))] [assembly: TypeForwardedTo(typeof(COMException))] [assembly: TypeForwardedTo(typeof(ComImportAttribute))] [assembly: TypeForwardedTo(typeof(ComInterfaceType))] [assembly: TypeForwardedTo(typeof(ComMemberType))] [assembly: TypeForwardedTo(typeof(ComRegisterFunctionAttribute))] [assembly: TypeForwardedTo(typeof(ComSourceInterfacesAttribute))] [assembly: TypeForwardedTo(typeof(ADVF))] [assembly: TypeForwardedTo(typeof(BIND_OPTS))] [assembly: TypeForwardedTo(typeof(BINDPTR))] [assembly: TypeForwardedTo(typeof(CALLCONV))] [assembly: TypeForwardedTo(typeof(CONNECTDATA))] [assembly: TypeForwardedTo(typeof(DATADIR))] [assembly: TypeForwardedTo(typeof(DESCKIND))] [assembly: TypeForwardedTo(typeof(DISPPARAMS))] [assembly: TypeForwardedTo(typeof(DVASPECT))] [assembly: TypeForwardedTo(typeof(ELEMDESC))] [assembly: TypeForwardedTo(typeof(EXCEPINFO))] [assembly: TypeForwardedTo(typeof(FILETIME))] [assembly: TypeForwardedTo(typeof(FORMATETC))] [assembly: TypeForwardedTo(typeof(FUNCDESC))] [assembly: TypeForwardedTo(typeof(FUNCFLAGS))] [assembly: TypeForwardedTo(typeof(FUNCKIND))] [assembly: TypeForwardedTo(typeof(IAdviseSink))] [assembly: TypeForwardedTo(typeof(IBindCtx))] [assembly: TypeForwardedTo(typeof(IConnectionPoint))] [assembly: TypeForwardedTo(typeof(IConnectionPointContainer))] [assembly: TypeForwardedTo(typeof(IDataObject))] [assembly: TypeForwardedTo(typeof(IDLDESC))] [assembly: TypeForwardedTo(typeof(IDLFLAG))] [assembly: TypeForwardedTo(typeof(IEnumConnectionPoints))] [assembly: TypeForwardedTo(typeof(IEnumConnections))] [assembly: TypeForwardedTo(typeof(IEnumFORMATETC))] [assembly: TypeForwardedTo(typeof(IEnumMoniker))] [assembly: TypeForwardedTo(typeof(IEnumSTATDATA))] [assembly: TypeForwardedTo(typeof(IEnumString))] [assembly: TypeForwardedTo(typeof(IEnumVARIANT))] [assembly: TypeForwardedTo(typeof(IMoniker))] [assembly: TypeForwardedTo(typeof(IMPLTYPEFLAGS))] [assembly: TypeForwardedTo(typeof(INVOKEKIND))] [assembly: TypeForwardedTo(typeof(IPersistFile))] [assembly: TypeForwardedTo(typeof(IRunningObjectTable))] [assembly: TypeForwardedTo(typeof(IStream))] [assembly: TypeForwardedTo(typeof(ITypeComp))] [assembly: TypeForwardedTo(typeof(ITypeInfo))] [assembly: TypeForwardedTo(typeof(ITypeInfo2))] [assembly: TypeForwardedTo(typeof(ITypeLib))] [assembly: TypeForwardedTo(typeof(ITypeLib2))] [assembly: TypeForwardedTo(typeof(LIBFLAGS))] [assembly: TypeForwardedTo(typeof(PARAMDESC))] [assembly: TypeForwardedTo(typeof(PARAMFLAG))] [assembly: TypeForwardedTo(typeof(STATDATA))] [assembly: TypeForwardedTo(typeof(STATSTG))] [assembly: TypeForwardedTo(typeof(STGMEDIUM))] [assembly: TypeForwardedTo(typeof(SYSKIND))] [assembly: TypeForwardedTo(typeof(TYMED))] [assembly: TypeForwardedTo(typeof(TYPEATTR))] [assembly: TypeForwardedTo(typeof(TYPEDESC))] [assembly: TypeForwardedTo(typeof(TYPEFLAGS))] [assembly: TypeForwardedTo(typeof(TYPEKIND))] [assembly: TypeForwardedTo(typeof(TYPELIBATTR))] [assembly: TypeForwardedTo(typeof(VARDESC))] [assembly: TypeForwardedTo(typeof(VARFLAGS))] [assembly: TypeForwardedTo(typeof(VARKIND))] [assembly: TypeForwardedTo(typeof(ComUnregisterFunctionAttribute))] [assembly: TypeForwardedTo(typeof(ComVisibleAttribute))] [assembly: TypeForwardedTo(typeof(CriticalHandle))] [assembly: TypeForwardedTo(typeof(CurrencyWrapper))] [assembly: TypeForwardedTo(typeof(CustomQueryInterfaceMode))] [assembly: TypeForwardedTo(typeof(CustomQueryInterfaceResult))] [assembly: TypeForwardedTo(typeof(DefaultCharSetAttribute))] [assembly: TypeForwardedTo(typeof(DefaultDllImportSearchPathsAttribute))] [assembly: TypeForwardedTo(typeof(DefaultParameterValueAttribute))] [assembly: TypeForwardedTo(typeof(DispatchWrapper))] [assembly: TypeForwardedTo(typeof(DispIdAttribute))] [assembly: TypeForwardedTo(typeof(DllImportAttribute))] [assembly: TypeForwardedTo(typeof(DllImportSearchPath))] [assembly: TypeForwardedTo(typeof(ErrorWrapper))] [assembly: TypeForwardedTo(typeof(ExternalException))] [assembly: TypeForwardedTo(typeof(FieldOffsetAttribute))] [assembly: TypeForwardedTo(typeof(GCHandle))] [assembly: TypeForwardedTo(typeof(GCHandleType))] [assembly: TypeForwardedTo(typeof(GuidAttribute))] [assembly: TypeForwardedTo(typeof(HandleCollector))] [assembly: TypeForwardedTo(typeof(HandleRef))] [assembly: TypeForwardedTo(typeof(ICustomAdapter))] [assembly: TypeForwardedTo(typeof(ICustomFactory))] [assembly: TypeForwardedTo(typeof(ICustomMarshaler))] [assembly: TypeForwardedTo(typeof(ICustomQueryInterface))] [assembly: TypeForwardedTo(typeof(ImportedFromTypeLibAttribute))] [assembly: TypeForwardedTo(typeof(InAttribute))] [assembly: TypeForwardedTo(typeof(InterfaceTypeAttribute))] [assembly: TypeForwardedTo(typeof(InvalidComObjectException))] [assembly: TypeForwardedTo(typeof(InvalidOleVariantTypeException))] [assembly: TypeForwardedTo(typeof(LayoutKind))] [assembly: TypeForwardedTo(typeof(LCIDConversionAttribute))] [assembly: TypeForwardedTo(typeof(ManagedToNativeComInteropStubAttribute))] [assembly: TypeForwardedTo(typeof(Marshal))] [assembly: TypeForwardedTo(typeof(MarshalAsAttribute))] [assembly: TypeForwardedTo(typeof(MarshalDirectiveException))] [assembly: TypeForwardedTo(typeof(MemoryMarshal))] [assembly: TypeForwardedTo(typeof(OptionalAttribute))] [assembly: TypeForwardedTo(typeof(OSPlatform))] [assembly: TypeForwardedTo(typeof(OutAttribute))] [assembly: TypeForwardedTo(typeof(PreserveSigAttribute))] [assembly: TypeForwardedTo(typeof(PrimaryInteropAssemblyAttribute))] [assembly: TypeForwardedTo(typeof(ProgIdAttribute))] [assembly: TypeForwardedTo(typeof(RuntimeEnvironment))] [assembly: TypeForwardedTo(typeof(RuntimeInformation))] [assembly: TypeForwardedTo(typeof(SafeArrayRankMismatchException))] [assembly: TypeForwardedTo(typeof(SafeArrayTypeMismatchException))] [assembly: TypeForwardedTo(typeof(SafeBuffer))] [assembly: TypeForwardedTo(typeof(SafeHandle))] [assembly: TypeForwardedTo(typeof(SEHException))] [assembly: TypeForwardedTo(typeof(SequenceMarshal))] [assembly: TypeForwardedTo(typeof(StructLayoutAttribute))] [assembly: TypeForwardedTo(typeof(TypeIdentifierAttribute))] [assembly: TypeForwardedTo(typeof(TypeLibFuncAttribute))] [assembly: TypeForwardedTo(typeof(TypeLibFuncFlags))] [assembly: TypeForwardedTo(typeof(TypeLibImportClassAttribute))] [assembly: TypeForwardedTo(typeof(TypeLibTypeAttribute))] [assembly: TypeForwardedTo(typeof(TypeLibTypeFlags))] [assembly: TypeForwardedTo(typeof(TypeLibVarAttribute))] [assembly: TypeForwardedTo(typeof(TypeLibVarFlags))] [assembly: TypeForwardedTo(typeof(TypeLibVersionAttribute))] [assembly: TypeForwardedTo(typeof(UnknownWrapper))] [assembly: TypeForwardedTo(typeof(UnmanagedFunctionPointerAttribute))] [assembly: TypeForwardedTo(typeof(UnmanagedType))] [assembly: TypeForwardedTo(typeof(VarEnum))] [assembly: TypeForwardedTo(typeof(VariantWrapper))] [assembly: TypeForwardedTo(typeof(MemoryFailPoint))] [assembly: TypeForwardedTo(typeof(CollectionDataContractAttribute))] [assembly: TypeForwardedTo(typeof(ContractNamespaceAttribute))] [assembly: TypeForwardedTo(typeof(DataContractAttribute))] [assembly: TypeForwardedTo(typeof(DataContractResolver))] [assembly: TypeForwardedTo(typeof(DataContractSerializer))] [assembly: TypeForwardedTo(typeof(DataContractSerializerExtensions))] [assembly: TypeForwardedTo(typeof(DataContractSerializerSettings))] [assembly: TypeForwardedTo(typeof(DataMemberAttribute))] [assembly: TypeForwardedTo(typeof(DateTimeFormat))] [assembly: TypeForwardedTo(typeof(EmitTypeInformation))] [assembly: TypeForwardedTo(typeof(EnumMemberAttribute))] [assembly: TypeForwardedTo(typeof(ExportOptions))] [assembly: TypeForwardedTo(typeof(ExtensionDataObject))] [assembly: TypeForwardedTo(typeof(Formatter))] [assembly: TypeForwardedTo(typeof(FormatterConverter))] [assembly: TypeForwardedTo(typeof(BinaryFormatter))] [assembly: TypeForwardedTo(typeof(FormatterAssemblyStyle))] [assembly: TypeForwardedTo(typeof(FormatterTypeStyle))] [assembly: TypeForwardedTo(typeof(IFieldInfo))] [assembly: TypeForwardedTo(typeof(TypeFilterLevel))] [assembly: TypeForwardedTo(typeof(FormatterServices))] [assembly: TypeForwardedTo(typeof(IDeserializationCallback))] [assembly: TypeForwardedTo(typeof(IExtensibleDataObject))] [assembly: TypeForwardedTo(typeof(IFormatter))] [assembly: TypeForwardedTo(typeof(IFormatterConverter))] [assembly: TypeForwardedTo(typeof(IgnoreDataMemberAttribute))] [assembly: TypeForwardedTo(typeof(InvalidDa
BepInExPack\unstripped_corlib\System.Core.dll
Decompiled 2 months ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers; 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.Diagnostics.Tracing; using System.Dynamic; using System.Dynamic.Utils; using System.Globalization; using System.IO; using System.IO.MemoryMappedFiles; using System.Linq; using System.Linq.Expressions; using System.Linq.Expressions.Compiler; using System.Linq.Parallel; using System.Reflection; using System.Reflection.Emit; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security; using System.Security.AccessControl; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Security.Permissions; using System.Security.Principal; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Win32.SafeHandles; using Mono.Security.Cryptography; using Unity; [assembly: DefaultDependency(LoadHint.Always)] [assembly: AssemblyKeyFile("../ecma.pub")] [assembly: AssemblyDelaySign(true)] [assembly: CLSCompliant(true)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyFileVersion("4.6.57.0")] [assembly: AssemblyInformationalVersion("4.6.57.0")] [assembly: SatelliteContractVersion("4.0.0.0")] [assembly: AssemblyCopyright("(c) Various Mono authors")] [assembly: AssemblyProduct("Mono Common Language Infrastructure")] [assembly: AssemblyCompany("Mono development team")] [assembly: AssemblyDefaultAlias("System.Core.dll")] [assembly: AssemblyDescription("System.Core.dll")] [assembly: AssemblyTitle("System.Core.dll")] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: AllowPartiallyTrustedCallers] [assembly: CompilationRelaxations(8)] [assembly: StringFreezing] [assembly: ComVisible(false)] [assembly: SecurityCritical] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("4.0.0.0")] [assembly: TypeForwardedTo(typeof(Action))] [assembly: TypeForwardedTo(typeof(Action<, >))] [assembly: TypeForwardedTo(typeof(Action<, , >))] [assembly: TypeForwardedTo(typeof(Action<, , , >))] [assembly: TypeForwardedTo(typeof(Func<>))] [assembly: TypeForwardedTo(typeof(Func<, >))] [assembly: TypeForwardedTo(typeof(Func<, , >))] [assembly: TypeForwardedTo(typeof(Func<, , , >))] [assembly: TypeForwardedTo(typeof(Func<, , , , >))] [assembly: TypeForwardedTo(typeof(InvalidTimeZoneException))] [assembly: TypeForwardedTo(typeof(Lazy<>))] [assembly: TypeForwardedTo(typeof(ExtensionAttribute))] [assembly: TypeForwardedTo(typeof(Aes))] [assembly: TypeForwardedTo(typeof(LazyThreadSafetyMode))] [assembly: TypeForwardedTo(typeof(LockRecursionException))] [assembly: TypeForwardedTo(typeof(TimeZoneInfo))] [assembly: TypeForwardedTo(typeof(TimeZoneNotFoundException))] [module: UnverifiableCode] internal static class Interop { internal enum BOOL { FALSE, TRUE } internal class Errors { internal const int ERROR_SUCCESS = 0; internal const int ERROR_INVALID_FUNCTION = 1; internal const int ERROR_FILE_NOT_FOUND = 2; internal const int ERROR_PATH_NOT_FOUND = 3; internal const int ERROR_ACCESS_DENIED = 5; internal const int ERROR_INVALID_HANDLE = 6; internal const int ERROR_NOT_ENOUGH_MEMORY = 8; internal const int ERROR_INVALID_DATA = 13; internal const int ERROR_INVALID_DRIVE = 15; internal const int ERROR_NO_MORE_FILES = 18; internal const int ERROR_NOT_READY = 21; internal const int ERROR_BAD_COMMAND = 22; internal const int ERROR_BAD_LENGTH = 24; internal const int ERROR_SHARING_VIOLATION = 32; internal const int ERROR_LOCK_VIOLATION = 33; internal const int ERROR_HANDLE_EOF = 38; internal const int ERROR_BAD_NETPATH = 53; internal const int ERROR_BAD_NET_NAME = 67; internal const int ERROR_FILE_EXISTS = 80; internal const int ERROR_INVALID_PARAMETER = 87; internal const int ERROR_BROKEN_PIPE = 109; internal const int ERROR_SEM_TIMEOUT = 121; internal const int ERROR_CALL_NOT_IMPLEMENTED = 120; internal const int ERROR_INSUFFICIENT_BUFFER = 122; internal const int ERROR_INVALID_NAME = 123; internal const int ERROR_NEGATIVE_SEEK = 131; internal const int ERROR_DIR_NOT_EMPTY = 145; internal const int ERROR_BAD_PATHNAME = 161; internal const int ERROR_LOCK_FAILED = 167; internal const int ERROR_BUSY = 170; internal const int ERROR_ALREADY_EXISTS = 183; internal const int ERROR_BAD_EXE_FORMAT = 193; internal const int ERROR_ENVVAR_NOT_FOUND = 203; internal const int ERROR_FILENAME_EXCED_RANGE = 206; internal const int ERROR_EXE_MACHINE_TYPE_MISMATCH = 216; internal const int ERROR_PIPE_BUSY = 231; internal const int ERROR_NO_DATA = 232; internal const int ERROR_PIPE_NOT_CONNECTED = 233; internal const int ERROR_MORE_DATA = 234; internal const int ERROR_NO_MORE_ITEMS = 259; internal const int ERROR_DIRECTORY = 267; internal const int ERROR_PARTIAL_COPY = 299; internal const int ERROR_ARITHMETIC_OVERFLOW = 534; internal const int ERROR_PIPE_CONNECTED = 535; internal const int ERROR_PIPE_LISTENING = 536; internal const int ERROR_OPERATION_ABORTED = 995; internal const int ERROR_IO_INCOMPLETE = 996; internal const int ERROR_IO_PENDING = 997; internal const int ERROR_NO_TOKEN = 1008; internal const int ERROR_DLL_INIT_FAILED = 1114; internal const int ERROR_COUNTER_TIMEOUT = 1121; internal const int ERROR_NO_ASSOCIATION = 1155; internal const int ERROR_DDE_FAIL = 1156; internal const int ERROR_DLL_NOT_FOUND = 1157; internal const int ERROR_NOT_FOUND = 1168; internal const int ERROR_NETWORK_UNREACHABLE = 1231; internal const int ERROR_NON_ACCOUNT_SID = 1257; internal const int ERROR_NOT_ALL_ASSIGNED = 1300; internal const int ERROR_UNKNOWN_REVISION = 1305; internal const int ERROR_INVALID_OWNER = 1307; internal const int ERROR_INVALID_PRIMARY_GROUP = 1308; internal const int ERROR_NO_SUCH_PRIVILEGE = 1313; internal const int ERROR_PRIVILEGE_NOT_HELD = 1314; internal const int ERROR_INVALID_ACL = 1336; internal const int ERROR_INVALID_SECURITY_DESCR = 1338; internal const int ERROR_INVALID_SID = 1337; internal const int ERROR_BAD_IMPERSONATION_LEVEL = 1346; internal const int ERROR_CANT_OPEN_ANONYMOUS = 1347; internal const int ERROR_NO_SECURITY_ON_OBJECT = 1350; internal const int ERROR_CLASS_ALREADY_EXISTS = 1410; internal const int ERROR_TRUSTED_RELATIONSHIP_FAILURE = 1789; internal const int ERROR_RESOURCE_LANG_NOT_FOUND = 1815; internal const int EFail = -2147467259; internal const int E_FILENOTFOUND = -2147024894; } internal static class Libraries { internal const string Advapi32 = "advapi32.dll"; internal const string BCrypt = "BCrypt.dll"; internal const string CoreComm_L1_1_1 = "api-ms-win-core-comm-l1-1-1.dll"; internal const string Crypt32 = "crypt32.dll"; internal const string Error_L1 = "api-ms-win-core-winrt-error-l1-1-0.dll"; internal const string HttpApi = "httpapi.dll"; internal const string IpHlpApi = "iphlpapi.dll"; internal const string Kernel32 = "kernel32.dll"; internal const string Memory_L1_3 = "api-ms-win-core-memory-l1-1-3.dll"; internal const string Mswsock = "mswsock.dll"; internal const string NCrypt = "ncrypt.dll"; internal const string NtDll = "ntdll.dll"; internal const string Odbc32 = "odbc32.dll"; internal const string OleAut32 = "oleaut32.dll"; internal const string PerfCounter = "perfcounter.dll"; internal const string RoBuffer = "api-ms-win-core-winrt-robuffer-l1-1-0.dll"; internal const string Secur32 = "secur32.dll"; internal const string Shell32 = "shell32.dll"; internal const string SspiCli = "sspicli.dll"; internal const string User32 = "user32.dll"; internal const string Version = "version.dll"; internal const string WebSocket = "websocket.dll"; internal const string WinHttp = "winhttp.dll"; internal const string Ws2_32 = "ws2_32.dll"; internal const string Wtsapi32 = "wtsapi32.dll"; internal const string CompressionNative = "clrcompression.dll"; } internal static class Advapi32 { [DllImport("advapi32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool ImpersonateNamedPipeClient(SafePipeHandle hNamedPipe); [DllImport("advapi32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] internal static extern bool RevertToSelf(); } internal class Kernel32 { internal class IOReparseOptions { internal const uint IO_REPARSE_TAG_FILE_PLACEHOLDER = 2147483669u; internal const uint IO_REPARSE_TAG_MOUNT_POINT = 2684354563u; } internal class FileOperations { internal const int OPEN_EXISTING = 3; internal const int COPY_FILE_FAIL_IF_EXISTS = 1; internal const int FILE_ACTION_ADDED = 1; internal const int FILE_ACTION_REMOVED = 2; internal const int FILE_ACTION_MODIFIED = 3; internal const int FILE_ACTION_RENAMED_OLD_NAME = 4; internal const int FILE_ACTION_RENAMED_NEW_NAME = 5; internal const int FILE_FLAG_BACKUP_SEMANTICS = 33554432; internal const int FILE_FLAG_FIRST_PIPE_INSTANCE = 524288; internal const int FILE_FLAG_OVERLAPPED = 1073741824; internal const int FILE_LIST_DIRECTORY = 1; } internal class FileTypes { internal const int FILE_TYPE_UNKNOWN = 0; internal const int FILE_TYPE_DISK = 1; internal const int FILE_TYPE_CHAR = 2; internal const int FILE_TYPE_PIPE = 3; } internal class GenericOperations { internal const int GENERIC_READ = int.MinValue; internal const int GENERIC_WRITE = 1073741824; } internal class HandleOptions { internal const int DUPLICATE_SAME_ACCESS = 2; internal const int STILL_ACTIVE = 259; internal const int TOKEN_ADJUST_PRIVILEGES = 32; } internal class PipeOptions { internal const int PIPE_ACCESS_INBOUND = 1; internal const int PIPE_ACCESS_OUTBOUND = 2; internal const int PIPE_ACCESS_DUPLEX = 3; internal const int PIPE_TYPE_BYTE = 0; internal const int PIPE_TYPE_MESSAGE = 4; internal const int PIPE_READMODE_BYTE = 0; internal const int PIPE_READMODE_MESSAGE = 2; internal const int PIPE_UNLIMITED_INSTANCES = 255; } internal struct SECURITY_ATTRIBUTES { internal uint nLength; internal IntPtr lpSecurityDescriptor; internal BOOL bInheritHandle; } internal class SecurityOptions { internal const int SECURITY_SQOS_PRESENT = 1048576; internal const int SECURITY_ANONYMOUS = 0; internal const int SECURITY_IDENTIFICATION = 65536; internal const int SECURITY_IMPERSONATION = 131072; internal const int SECURITY_DELEGATION = 196608; } internal const uint SEM_FAILCRITICALERRORS = 1u; private const int FORMAT_MESSAGE_IGNORE_INSERTS = 512; private const int FORMAT_MESSAGE_FROM_HMODULE = 2048; private const int FORMAT_MESSAGE_FROM_SYSTEM = 4096; private const int FORMAT_MESSAGE_ARGUMENT_ARRAY = 8192; private const int ERROR_INSUFFICIENT_BUFFER = 122; private const int InitialBufferSize = 256; private const int BufferSizeIncreaseFactor = 4; private const int MaxAllowedBufferSize = 66560; internal const int MAX_PATH = 260; internal const int CREDUI_MAX_USERNAME_LENGTH = 513; [DllImport("kernel32.dll", SetLastError = true)] internal unsafe static extern bool CancelIoEx(SafeHandle handle, NativeOverlapped* lpOverlapped); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CloseHandle(IntPtr handle); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal unsafe static extern bool ConnectNamedPipe(SafePipeHandle handle, NativeOverlapped* overlapped); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool ConnectNamedPipe(SafePipeHandle handle, IntPtr overlapped); [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "CreateNamedPipeW", SetLastError = true)] internal static extern SafePipeHandle CreateNamedPipe(string pipeName, int openMode, int pipeMode, int maxInstances, int outBufferSize, int inBufferSize, int defaultTimeout, ref SECURITY_ATTRIBUTES securityAttributes); [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "CreateFileW", SetLastError = true)] internal static extern SafePipeHandle CreateNamedPipeClient(string lpFileName, int dwDesiredAccess, FileShare dwShareMode, ref SECURITY_ATTRIBUTES secAttrs, FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile); [DllImport("kernel32.dll", SetLastError = true)] internal static extern bool CreatePipe(out SafePipeHandle hReadPipe, out SafePipeHandle hWritePipe, ref SECURITY_ATTRIBUTES lpPipeAttributes, int nSize); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool DisconnectNamedPipe(SafePipeHandle hNamedPipe); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool DuplicateHandle(IntPtr hSourceProcessHandle, SafePipeHandle hSourceHandle, IntPtr hTargetProcessHandle, out SafePipeHandle lpTargetHandle, uint dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, uint dwOptions); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool FlushFileBuffers(SafeHandle hHandle); [DllImport("kernel32.dll", BestFitMapping = true, CharSet = CharSet.Unicode, EntryPoint = "FormatMessageW", SetLastError = true)] private unsafe static extern int FormatMessage(int dwFlags, IntPtr lpSource, uint dwMessageId, int dwLanguageId, char* lpBuffer, int nSize, IntPtr[] arguments); internal static string GetMessage(int errorCode) { return GetMessage(IntPtr.Zero, errorCode); } internal unsafe static string GetMessage(IntPtr moduleHandle, int errorCode) { //IL_000d: 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_0015: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) Span<char> buffer = new Span<char>((void*)stackalloc byte[512], 256); do { if (TryGetErrorMessage(moduleHandle, errorCode, buffer, out var errorMsg)) { return errorMsg; } buffer = Span<char>.op_Implicit(new char[buffer.Length * 4]); } while (buffer.Length < 66560); return $"Unknown error (0x{errorCode:x})"; } private unsafe static bool TryGetErrorMessage(IntPtr moduleHandle, int errorCode, Span<char> buffer, out string errorMsg) { //IL_001b: 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) int num = 12800; if (moduleHandle != IntPtr.Zero) { num |= 0x800; } int num2; fixed (char* lpBuffer = &MemoryMarshal.GetReference<char>(buffer)) { num2 = FormatMessage(num, moduleHandle, (uint)errorCode, 0, lpBuffer, buffer.Length, null); } if (num2 != 0) { int num3; for (num3 = num2; num3 > 0; num3--) { char c = buffer[num3 - 1]; if (c > ' ' && c != '.') { break; } } errorMsg = ((object)buffer.Slice(0, num3)).ToString(); } else { if (Marshal.GetLastWin32Error() == 122) { errorMsg = ""; return false; } errorMsg = $"Unknown error (0x{errorCode:x})"; } return true; } [DllImport("kernel32.dll", SetLastError = true)] internal static extern IntPtr GetCurrentProcess(); [DllImport("kernel32.dll", SetLastError = true)] internal static extern int GetFileType(SafeHandle hFile); [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "GetNamedPipeHandleStateW", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetNamedPipeHandleState(SafePipeHandle hNamedPipe, out int lpState, IntPtr lpCurInstances, IntPtr lpMaxCollectionCount, IntPtr lpCollectDataTimeout, IntPtr lpUserName, int nMaxUserNameSize); [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "GetNamedPipeHandleStateW", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetNamedPipeHandleState(SafePipeHandle hNamedPipe, IntPtr lpState, IntPtr lpCurInstances, IntPtr lpMaxCollectionCount, IntPtr lpCollectDataTimeout, [Out] StringBuilder lpUserName, int nMaxUserNameSize); [DllImport("kernel32.dll", EntryPoint = "GetNamedPipeHandleStateW", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetNamedPipeHandleState(SafePipeHandle hNamedPipe, IntPtr lpState, out int lpCurInstances, IntPtr lpMaxCollectionCount, IntPtr lpCollectDataTimeout, IntPtr lpUserName, int nMaxUserNameSize); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetNamedPipeInfo(SafePipeHandle hNamedPipe, out int lpFlags, IntPtr lpOutBufferSize, IntPtr lpInBufferSize, IntPtr lpMaxInstances); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetNamedPipeInfo(SafePipeHandle hNamedPipe, IntPtr lpFlags, out int lpOutBufferSize, IntPtr lpInBufferSize, IntPtr lpMaxInstances); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetNamedPipeInfo(SafePipeHandle hNamedPipe, IntPtr lpFlags, IntPtr lpOutBufferSize, out int lpInBufferSize, IntPtr lpMaxInstances); [DllImport("kernel32.dll", SetLastError = true)] internal unsafe static extern int ReadFile(SafeHandle handle, byte* bytes, int numBytesToRead, out int numBytesRead, IntPtr mustBeZero); [DllImport("kernel32.dll", SetLastError = true)] internal unsafe static extern int ReadFile(SafeHandle handle, byte* bytes, int numBytesToRead, IntPtr numBytesRead_mustBeZero, NativeOverlapped* overlapped); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal unsafe static extern bool SetNamedPipeHandleState(SafePipeHandle hNamedPipe, int* lpMode, IntPtr lpMaxCollectionCount, IntPtr lpCollectDataTimeout); [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "WaitNamedPipeW", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool WaitNamedPipe(string name, int timeout); [DllImport("kernel32.dll", SetLastError = true)] internal unsafe static extern int WriteFile(SafeHandle handle, byte* bytes, int numBytesToWrite, out int numBytesWritten, IntPtr mustBeZero); [DllImport("kernel32.dll", SetLastError = true)] internal unsafe static extern int WriteFile(SafeHandle handle, byte* bytes, int numBytesToWrite, IntPtr numBytesWritten_mustBeZero, NativeOverlapped* lpOverlapped); } } internal static class Consts { public const string MonoCorlibVersion = "1A5E0066-58DC-428A-B21C-0AD6CDAE2789"; public const string MonoVersion = "6.13.0.0"; public const string MonoCompany = "Mono development team"; public const string MonoProduct = "Mono Common Language Infrastructure"; public const string MonoCopyright = "(c) Various Mono authors"; public const string FxVersion = "4.0.0.0"; public const string FxFileVersion = "4.6.57.0"; public const string EnvironmentVersion = "4.0.30319.42000"; public const string VsVersion = "0.0.0.0"; public const string VsFileVersion = "11.0.0.0"; private const string PublicKeyToken = "b77a5c561934e089"; public const string AssemblyI18N = "I18N, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMicrosoft_JScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VisualStudio = "Microsoft.VisualStudio, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VisualStudio_Web = "Microsoft.VisualStudio.Web, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMicrosoft_VSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblyMono_Http = "Mono.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Posix = "Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Security = "Mono.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyMono_Messaging_RabbitMQ = "Mono.Messaging.RabbitMQ, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756"; public const string AssemblyCorlib = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Data = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Design = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_DirectoryServices = "System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Drawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Drawing_Design = "System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Messaging = "System.Messaging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Security = "System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_ServiceProcess = "System.ServiceProcess, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Web = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_2_0 = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystemCore_3_5 = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string AssemblySystem_Core = "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; public const string WindowsBase_3_0 = "WindowsBase, Version=3.0.0.0, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyWindowsBase = "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationCore_3_5 = "PresentationCore, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationCore_4_0 = "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblyPresentationFramework_3_5 = "PresentationFramework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; public const string AssemblySystemServiceModel_3_0 = "System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; } internal static class SR { public const string ReducibleMustOverrideReduce = "reducible nodes must override Expression.Reduce()"; public const string MustReduceToDifferent = "node cannot reduce to itself or null"; public const string ReducedNotCompatible = "cannot assign from the reduced node type to the original node type"; public const string SetterHasNoParams = "Setter must have parameters."; public const string PropertyCannotHaveRefType = "Property cannot have a managed pointer type."; public const string IndexesOfSetGetMustMatch = "Indexing parameters of getter and setter must match."; public const string AccessorsCannotHaveVarArgs = "Accessor method should not have VarArgs."; public const string AccessorsCannotHaveByRefArgs = "Accessor indexes cannot be passed ByRef."; public const string BoundsCannotBeLessThanOne = "Bounds count cannot be less than 1"; public const string TypeMustNotBeByRef = "Type must not be ByRef"; public const string TypeMustNotBePointer = "Type must not be a pointer type"; public const string SetterMustBeVoid = "Setter should have void type."; public const string PropertyTypeMustMatchGetter = "Property type must match the value type of getter"; public const string PropertyTypeMustMatchSetter = "Property type must match the value type of setter"; public const string BothAccessorsMustBeStatic = "Both accessors must be static."; public const string OnlyStaticFieldsHaveNullInstance = "Static field requires null instance, non-static field requires non-null instance."; public const string OnlyStaticPropertiesHaveNullInstance = "Static property requires null instance, non-static property requires non-null instance."; public const string OnlyStaticMethodsHaveNullInstance = "Static method requires null instance, non-static method requires non-null instance."; public const string PropertyTypeCannotBeVoid = "Property cannot have a void type."; public const string InvalidUnboxType = "Can only unbox from an object or interface type to a value type."; public const string ExpressionMustBeWriteable = "Expression must be writeable"; public const string ArgumentMustNotHaveValueType = "Argument must not have a value type."; public const string MustBeReducible = "must be reducible node"; public const string AllTestValuesMustHaveSameType = "All test values must have the same type."; public const string AllCaseBodiesMustHaveSameType = "All case bodies and the default body must have the same type."; public const string DefaultBodyMustBeSupplied = "Default body must be supplied if case bodies are not System.Void."; public const string LabelMustBeVoidOrHaveExpression = "Label type must be System.Void if an expression is not supplied"; public const string LabelTypeMustBeVoid = "Type must be System.Void for this label argument"; public const string QuotedExpressionMustBeLambda = "Quoted expression must be a lambda"; public const string VariableMustNotBeByRef = "Variable '{0}' uses unsupported type '{1}'. Reference types are not supported for variables."; public const string DuplicateVariable = "Found duplicate parameter '{0}'. Each ParameterExpression in the list must be a unique object."; public const string StartEndMustBeOrdered = "Start and End must be well ordered"; public const string FaultCannotHaveCatchOrFinally = "fault cannot be used with catch or finally clauses"; public const string TryMustHaveCatchFinallyOrFault = "try must have at least one catch, finally, or fault clause"; public const string BodyOfCatchMustHaveSameTypeAsBodyOfTry = "Body of catch must have the same type as body of try."; public const string ExtensionNodeMustOverrideProperty = "Extension node must override the property {0}."; public const string UserDefinedOperatorMustBeStatic = "User-defined operator method '{0}' must be static."; public const string UserDefinedOperatorMustNotBeVoid = "User-defined operator method '{0}' must not be void."; public const string CoercionOperatorNotDefined = "No coercion operator is defined between types '{0}' and '{1}'."; public const string UnaryOperatorNotDefined = "The unary operator {0} is not defined for the type '{1}'."; public const string BinaryOperatorNotDefined = "The binary operator {0} is not defined for the types '{1}' and '{2}'."; public const string ReferenceEqualityNotDefined = "Reference equality is not defined for the types '{0}' and '{1}'."; public const string OperandTypesDoNotMatchParameters = "The operands for operator '{0}' do not match the parameters of method '{1}'."; public const string OverloadOperatorTypeDoesNotMatchConversionType = "The return type of overload method for operator '{0}' does not match the parameter type of conversion method '{1}'."; public const string ConversionIsNotSupportedForArithmeticTypes = "Conversion is not supported for arithmetic types without operator overloading."; public const string ArgumentMustBeArray = "Argument must be array"; public const string ArgumentMustBeBoolean = "Argument must be boolean"; public const string EqualityMustReturnBoolean = "The user-defined equality method '{0}' must return a boolean value."; public const string ArgumentMustBeFieldInfoOrPropertyInfo = "Argument must be either a FieldInfo or PropertyInfo"; public const string ArgumentMustBeFieldInfoOrPropertyInfoOrMethod = "Argument must be either a FieldInfo, PropertyInfo or MethodInfo"; public const string ArgumentMustBeInstanceMember = "Argument must be an instance member"; public const string ArgumentMustBeInteger = "Argument must be of an integer type"; public const string ArgumentMustBeArrayIndexType = "Argument for array index must be of type Int32"; public const string ArgumentMustBeSingleDimensionalArrayType = "Argument must be single-dimensional, zero-based array type"; public const string ArgumentTypesMustMatch = "Argument types do not match"; public const string CannotAutoInitializeValueTypeElementThroughProperty = "Cannot auto initialize elements of value type through property '{0}', use assignment instead"; public const string CannotAutoInitializeValueTypeMemberThroughProperty = "Cannot auto initialize members of value type through property '{0}', use assignment instead"; public const string IncorrectTypeForTypeAs = "The type used in TypeAs Expression must be of reference or nullable type, {0} is neither"; public const string CoalesceUsedOnNonNullType = "Coalesce used with type that cannot be null"; public const string ExpressionTypeCannotInitializeArrayType = "An expression of type '{0}' cannot be used to initialize an array of type '{1}'"; public const string ArgumentTypeDoesNotMatchMember = " Argument type '{0}' does not match the corresponding member type '{1}'"; public const string ArgumentMemberNotDeclOnType = " The member '{0}' is not declared on type '{1}' being created"; public const string ExpressionTypeDoesNotMatchReturn = "Expression of type '{0}' cannot be used for return type '{1}'"; public const string ExpressionTypeDoesNotMatchAssignment = "Expression of type '{0}' cannot be used for assignment to type '{1}'"; public const string ExpressionTypeDoesNotMatchLabel = "Expression of type '{0}' cannot be used for label of type '{1}'"; public const string ExpressionTypeNotInvocable = "Expression of type '{0}' cannot be invoked"; public const string FieldNotDefinedForType = "Field '{0}' is not defined for type '{1}'"; public const string InstanceFieldNotDefinedForType = "Instance field '{0}' is not defined for type '{1}'"; public const string FieldInfoNotDefinedForType = "Field '{0}.{1}' is not defined for type '{2}'"; public const string IncorrectNumberOfIndexes = "Incorrect number of indexes"; public const string IncorrectNumberOfLambdaDeclarationParameters = "Incorrect number of parameters supplied for lambda declaration"; public const string IncorrectNumberOfMembersForGivenConstructor = " Incorrect number of members for constructor"; public const string IncorrectNumberOfArgumentsForMembers = "Incorrect number of arguments for the given members "; public const string LambdaTypeMustBeDerivedFromSystemDelegate = "Lambda type parameter must be derived from System.MulticastDelegate"; public const string MemberNotFieldOrProperty = "Member '{0}' not field or property"; public const string MethodContainsGenericParameters = "Method {0} contains generic parameters"; public const string MethodIsGeneric = "Method {0} is a generic method definition"; public const string MethodNotPropertyAccessor = "The method '{0}.{1}' is not a property accessor"; public const string PropertyDoesNotHaveGetter = "The property '{0}' has no 'get' accessor"; public const string PropertyDoesNotHaveSetter = "The property '{0}' has no 'set' accessor"; public const string PropertyDoesNotHaveAccessor = "The property '{0}' has no 'get' or 'set' accessors"; public const string NotAMemberOfType = "'{0}' is not a member of type '{1}'"; public const string NotAMemberOfAnyType = "'{0}' is not a member of any type"; public const string UnsupportedExpressionType = "The expression type '{0}' is not supported"; public const string ParameterExpressionNotValidAsDelegate = "ParameterExpression of type '{0}' cannot be used for delegate parameter of type '{1}'"; public const string PropertyNotDefinedForType = "Property '{0}' is not defined for type '{1}'"; public const string InstancePropertyNotDefinedForType = "Instance property '{0}' is not defined for type '{1}'"; public const string InstancePropertyWithoutParameterNotDefinedForType = "Instance property '{0}' that takes no argument is not defined for type '{1}'"; public const string InstancePropertyWithSpecifiedParametersNotDefinedForType = "Instance property '{0}{1}' is not defined for type '{2}'"; public const string InstanceAndMethodTypeMismatch = "Method '{0}' declared on type '{1}' cannot be called with instance of type '{2}'"; public const string TypeContainsGenericParameters = "Type {0} contains generic parameters"; public const string TypeIsGeneric = "Type {0} is a generic type definition"; public const string TypeMissingDefaultConstructor = "Type '{0}' does not have a default constructor"; public const string ElementInitializerMethodNotAdd = "Element initializer method must be named 'Add'"; public const string ElementInitializerMethodNoRefOutParam = "Parameter '{0}' of element initializer method '{1}' must not be a pass by reference parameter"; public const string ElementInitializerMethodWithZeroArgs = "Element initializer method must have at least 1 parameter"; public const string ElementInitializerMethodStatic = "Element initializer method must be an instance method"; public const string TypeNotIEnumerable = "Type '{0}' is not IEnumerable"; public const string UnhandledBinary = "Unhandled binary: {0}"; public const string UnhandledBinding = "Unhandled binding "; public const string UnhandledBindingType = "Unhandled Binding Type: {0}"; public const string UnhandledUnary = "Unhandled unary: {0}"; public const string UnknownBindingType = "Unknown binding type"; public const string UserDefinedOpMustHaveConsistentTypes = "The user-defined operator method '{1}' for operator '{0}' must have identical parameter and return types."; public const string UserDefinedOpMustHaveValidReturnType = "The user-defined operator method '{1}' for operator '{0}' must return the same type as its parameter or a derived type."; public const string LogicalOperatorMustHaveBooleanOperators = "The user-defined operator method '{1}' for operator '{0}' must have associated boolean True and False operators."; public const string MethodWithArgsDoesNotExistOnType = "No method '{0}' on type '{1}' is compatible with the supplied arguments."; public const string GenericMethodWithArgsDoesNotExistOnType = "No generic method '{0}' on type '{1}' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic. "; public const string MethodWithMoreThanOneMatch = "More than one method '{0}' on type '{1}' is compatible with the supplied arguments."; public const string PropertyWithMoreThanOneMatch = "More than one property '{0}' on type '{1}' is compatible with the supplied arguments."; public const string IncorrectNumberOfTypeArgsForFunc = "An incorrect number of type arguments were specified for the declaration of a Func type."; public const string IncorrectNumberOfTypeArgsForAction = "An incorrect number of type arguments were specified for the declaration of an Action type."; public const string ArgumentCannotBeOfTypeVoid = "Argument type cannot be System.Void."; public const string OutOfRange = "{0} must be greater than or equal to {1}"; public const string LabelTargetAlreadyDefined = "Cannot redefine label '{0}' in an inner block."; public const string LabelTargetUndefined = "Cannot jump to undefined label '{0}'."; public const string ControlCannotLeaveFinally = "Control cannot leave a finally block."; public const string ControlCannotLeaveFilterTest = "Control cannot leave a filter test."; public const string AmbiguousJump = "Cannot jump to ambiguous label '{0}'."; public const string ControlCannotEnterTry = "Control cannot enter a try block."; public const string ControlCannotEnterExpression = "Control cannot enter an expression--only statements can be jumped into."; public const string NonLocalJumpWithValue = "Cannot jump to non-local label '{0}' with a value. Only jumps to labels defined in outer blocks can pass values."; public const string CannotCompileConstant = "CompileToMethod cannot compile constant '{0}' because it is a non-trivial value, such as a live object. Instead, create an expression tree that can construct this value."; public const string CannotCompileDynamic = "Dynamic expressions are not supported by CompileToMethod. Instead, create an expression tree that uses System.Runtime.CompilerServices.CallSite."; public const string InvalidLvalue = "Invalid lvalue for assignment: {0}."; public const string UndefinedVariable = "variable '{0}' of type '{1}' referenced from scope '{2}', but it is not defined"; public const string CannotCloseOverByRef = "Cannot close over byref parameter '{0}' referenced in lambda '{1}'"; public const string UnexpectedVarArgsCall = "Unexpected VarArgs call to method '{0}'"; public const string RethrowRequiresCatch = "Rethrow statement is valid only inside a Catch block."; public const string TryNotAllowedInFilter = "Try expression is not allowed inside a filter body."; public const string MustRewriteToSameNode = "When called from '{0}', rewriting a node of type '{1}' must return a non-null value of the same type. Alternatively, override '{2}' and change it to not visit children of this type."; public const string MustRewriteChildToSameType = "Rewriting child expression from type '{0}' to type '{1}' is not allowed, because it would change the meaning of the operation. If this is intentional, override '{2}' and change it to allow this rewrite."; public const string MustRewriteWithoutMethod = "Rewritten expression calls operator method '{0}', but the original node had no operator method. If this is intentional, override '{1}' and change it to allow this rewrite."; public const string InvalidNullValue = "The value null is not of type '{0}' and cannot be used in this collection."; public const string InvalidObjectType = "The value '{0}' is not of type '{1}' and cannot be used in this collection."; public const string TryNotSupportedForMethodsWithRefArgs = "TryExpression is not supported as an argument to method '{0}' because it has an argument with by-ref type. Construct the tree so the TryExpression is not nested inside of this expression."; public const string TryNotSupportedForValueTypeInstances = "TryExpression is not supported as a child expression when accessing a member on type '{0}' because it is a value type. Construct the tree so the TryExpression is not nested inside of this expression."; public const string EnumerationIsDone = "Enumeration has either not started or has already finished."; public const string TestValueTypeDoesNotMatchComparisonMethodParameter = "Test value of type '{0}' cannot be used for the comparison method parameter of type '{1}'"; public const string SwitchValueTypeDoesNotMatchComparisonMethodParameter = "Switch value of type '{0}' cannot be used for the comparison method parameter of type '{1}'"; public const string PdbGeneratorNeedsExpressionCompiler = "DebugInfoGenerator created by CreatePdbGenerator can only be used with LambdaExpression.CompileToMethod."; public const string InvalidArgumentValue = "Invalid argument value"; public const string NonEmptyCollectionRequired = "Non-empty collection required"; public const string CollectionModifiedWhileEnumerating = "Collection was modified; enumeration operation may not execute."; public const string ExpressionMustBeReadable = "Expression must be readable"; public const string ExpressionTypeDoesNotMatchMethodParameter = "Expression of type '{0}' cannot be used for parameter of type '{1}' of method '{2}'"; public const string ExpressionTypeDoesNotMatchParameter = "Expression of type '{0}' cannot be used for parameter of type '{1}'"; public const string ExpressionTypeDoesNotMatchConstructorParameter = "Expression of type '{0}' cannot be used for constructor parameter of type '{1}'"; public const string IncorrectNumberOfMethodCallArguments = "Incorrect number of arguments supplied for call to method '{0}'"; public const string IncorrectNumberOfLambdaArguments = "Incorrect number of arguments supplied for lambda invocation"; public const string IncorrectNumberOfConstructorArguments = "Incorrect number of arguments for constructor"; public const string NonStaticConstructorRequired = "The constructor should not be static"; public const string NonAbstractConstructorRequired = "Can't compile a NewExpression with a constructor declared on an abstract class"; public const string FirstArgumentMustBeCallSite = "First argument of delegate must be CallSite"; public const string NoOrInvalidRuleProduced = "No or Invalid rule produced"; public const string TypeMustBeDerivedFromSystemDelegate = "Type must be derived from System.Delegate"; public const string TypeParameterIsNotDelegate = "Type parameter is {0}. Expected a delegate."; public const string ArgumentTypeCannotBeVoid = "Argument type cannot be void"; public const string ArgCntMustBeGreaterThanNameCnt = "Argument count must be greater than number of named arguments."; public const string BinderNotCompatibleWithCallSite = "The result type '{0}' of the binder '{1}' is not compatible with the result type '{2}' expected by the call site."; public const string BindingCannotBeNull = "Bind cannot return null."; public const string DynamicBinderResultNotAssignable = "The result type '{0}' of the dynamic binding produced by binder '{1}' is not compatible with the result type '{2}' expected by the call site."; public const string DynamicBindingNeedsRestrictions = "The result of the dynamic binding produced by the object with type '{0}' for the binder '{1}' needs at least one restriction."; public const string DynamicObjectResultNotAssignable = "The result type '{0}' of the dynamic binding produced by the object with type '{1}' for the binder '{2}' is not compatible with the result type '{3}' expected by the call site."; public const string InvalidMetaObjectCreated = "An IDynamicMetaObjectProvider {0} created an invalid DynamicMetaObject instance."; public const string AmbiguousMatchInExpandoObject = "More than one key matching '{0}' was found in the ExpandoObject."; public const string CollectionReadOnly = "Collection is read-only."; public const string KeyDoesNotExistInExpando = "The specified key '{0}' does not exist in the ExpandoObject."; public const string SameKeyExistsInExpando = "An element with the same key '{0}' already exists in the ExpandoObject."; public const string Arg_KeyNotFoundWithKey = "The given key '{0}' was not present in the dictionary."; public const string EmptyEnumerable = "Enumeration yielded no results"; public const string MoreThanOneElement = "Sequence contains more than one element"; public const string MoreThanOneMatch = "Sequence contains more than one matching element"; public const string NoElements = "Sequence contains no elements"; public const string NoMatch = "Sequence contains no matching element"; public const string ParallelPartitionable_NullReturn = "The return value must not be null."; public const string ParallelPartitionable_IncorretElementCount = "The returned array's length must equal the number of partitions requested."; public const string ParallelPartitionable_NullElement = "Elements returned must not be null."; public const string PLINQ_CommonEnumerator_Current_NotStarted = "Enumeration has not started. MoveNext must be called to initiate enumeration."; public const string PLINQ_ExternalCancellationRequested = "The query has been canceled via the token supplied to WithCancellation."; public const string PLINQ_DisposeRequested = "The query enumerator has been disposed."; public const string ParallelQuery_DuplicateTaskScheduler = "The WithTaskScheduler operator may be used at most once in a query."; public const string ParallelQuery_DuplicateDOP = "The WithDegreeOfParallelism operator may be used at most once in a query."; public const string ParallelQuery_DuplicateExecutionMode = "The WithExecutionMode operator may be used at most once in a query."; public const string PartitionerQueryOperator_NullPartitionList = "Partitioner returned null instead of a list of partitions."; public const string PartitionerQueryOperator_WrongNumberOfPartitions = "Partitioner returned a wrong number of partitions."; public const string PartitionerQueryOperator_NullPartition = "Partitioner returned a null partition."; public const string ParallelQuery_DuplicateWithCancellation = "The WithCancellation operator may by used at most once in a query."; public const string ParallelQuery_DuplicateMergeOptions = "The WithMergeOptions operator may be used at most once in a query."; public const string PLINQ_EnumerationPreviouslyFailed = "The query enumerator previously threw an exception."; public const string ParallelQuery_PartitionerNotOrderable = "AsOrdered may not be used with a partitioner that is not orderable."; public const string ParallelQuery_InvalidAsOrderedCall = "AsOrdered may only be called on the result of AsParallel, ParallelEnumerable.Range, or ParallelEnumerable.Repeat."; public const string ParallelQuery_InvalidNonGenericAsOrderedCall = "Non-generic AsOrdered may only be called on the result of the non-generic AsParallel."; public const string ParallelEnumerable_BinaryOpMustUseAsParallel = "The second data source of a binary operator must be of type System.Linq.ParallelQuery<T> rather than System.Collections.Generic.IEnumerable<T>. To fix this problem, use the AsParallel() extension method to convert the right data source to System.Linq.ParallelQuery<T>."; public const string ParallelEnumerable_WithQueryExecutionMode_InvalidMode = "The executionMode argument contains an invalid value."; public const string ParallelEnumerable_WithMergeOptions_InvalidOptions = "The mergeOptions argument contains an invalid value."; public const string ArgumentNotIEnumerableGeneric = "{0} is not IEnumerable<>"; public const string ArgumentNotValid = "Argument {0} is not valid"; public const string NoMethodOnType = "There is no method '{0}' on type '{1}'"; public const string NoMethodOnTypeMatchingArguments = "There is no method '{0}' on type '{1}' that matches the specified arguments"; public const string EnumeratingNullEnumerableExpression = "Cannot enumerate a query created from a null IEnumerable<>"; public const string ArgumentOutOfRange_NeedNonNegNum = "Non negative number is required."; public const string ArgumentOutOfRange_NeedValidPipeAccessRights = "Invalid PipeAccessRights value."; public const string Argument_InvalidOffLen = "Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection."; public const string Argument_NeedNonemptyPipeName = "pipeName cannot be an empty string."; public const string Argument_NonContainerInvalidAnyFlag = "This flag may not be set on a pipe."; public const string Argument_EmptyServerName = "serverName cannot be an empty string. Use \\\\\\\".\\\\\\\" for current machine."; public const string Argument_InvalidHandle = "Invalid handle."; public const string ArgumentNull_Buffer = "Buffer cannot be null."; public const string ArgumentNull_ServerName = "serverName cannot be null. Use \\\".\\\" for current machine."; public const string ArgumentOutOfRange_AnonymousReserved = "The pipeName \\\"anonymous\\\" is reserved."; public const string ArgumentOutOfRange_TransmissionModeByteOrMsg = "For named pipes, transmission mode can be TransmissionMode.Byte or PipeTransmissionMode.Message. For anonymous pipes, transmission mode can be TransmissionMode.Byte."; public const string ArgumentOutOfRange_DirectionModeInOutOrInOut = "For named pipes, the pipe direction can be PipeDirection.In, PipeDirection.Out or PipeDirection.InOut. For anonymous pipes, the pipe direction can be PipeDirection.In or PipeDirection.Out."; public const string ArgumentOutOfRange_ImpersonationInvalid = "TokenImpersonationLevel.None, TokenImpersonationLevel.Anonymous, TokenImpersonationLevel.Identification, TokenImpersonationLevel.Impersonation or TokenImpersonationLevel.Delegation required."; public const string ArgumentOutOfRange_OptionsInvalid = "options contains an invalid flag."; public const string ArgumentOutOfRange_HandleInheritabilityNoneOrInheritable = "HandleInheritability.None or HandleInheritability.Inheritable required."; public const string ArgumentOutOfRange_InvalidTimeout = "Timeout must be non-negative or equal to -1 (Timeout.Infinite)"; public const string ArgumentOutOfRange_MaxNumServerInstances = "maxNumberOfServerInstances must either be a value between 1 and 254, or NamedPipeServerStream.MaxAllowedServerInstances (to obtain the maximum number allowed by system resources)."; public const string ArgumentOutOfRange_NeedPosNum = "Positive number required."; public const string InvalidOperation_PipeNotYetConnected = "Pipe hasn't been connected yet."; public const string InvalidOperation_PipeDisconnected = "Pipe is in a disconnected state."; public const string InvalidOperation_PipeHandleNotSet = "Pipe handle has not been set. Did your PipeStream implementation call InitializeHandle?"; public const string InvalidOperation_PipeNotAsync = "Pipe is not opened in asynchronous mode."; public const string InvalidOperation_PipeReadModeNotMessage = "ReadMode is not of PipeTransmissionMode.Message."; public const string InvalidOperation_PipeAlreadyConnected = "Already in a connected state."; public const string InvalidOperation_PipeAlreadyDisconnected = "Already in a disconnected state."; public const string IO_EOF_ReadBeyondEOF = "Unable to read beyond the end of the stream."; public const string IO_FileNotFound = "Unable to find the specified file."; public const string IO_FileNotFound_FileName = "Could not find file '{0}'."; public const string IO_AlreadyExists_Name = "Cannot create \\\"{0}\\\" because a file or directory with the same name already exists."; public const string IO_FileExists_Name = "The file '{0}' already exists."; public const string IO_IO_PipeBroken = "Pipe is broken."; public const string IO_OperationAborted = "IO operation was aborted unexpectedly."; public const string IO_SharingViolation_File = "The process cannot access the file '{0}' because it is being used by another process."; public const string IO_SharingViolation_NoFileName = "The process cannot access the file because it is being used by another process."; public const string IO_PipeBroken = "Pipe is broken."; public const string IO_InvalidPipeHandle = "Invalid pipe handle."; public const string IO_PathNotFound_Path = "Could not find a part of the path '{0}'."; public const string IO_PathNotFound_NoPathName = "Could not find a part of the path."; public const string IO_PathTooLong = "The specified file name or path is too long, or a component of the specified path is too long."; public const string NotSupported_UnreadableStream = "Stream does not support reading."; public const string NotSupported_UnseekableStream = "Stream does not support seeking."; public const string NotSupported_UnwritableStream = "Stream does not support writing."; public const string NotSupported_AnonymousPipeUnidirectional = "Anonymous pipes can only be in one direction."; public const string NotSupported_AnonymousPipeMessagesNotSupported = "Anonymous pipes do not support PipeTransmissionMode.Message ReadMode."; public const string ObjectDisposed_PipeClosed = "Cannot access a closed pipe."; public const string UnauthorizedAccess_IODenied_Path = "Access to the path '{0}' is denied."; public const string UnauthorizedAccess_IODenied_NoPathName = "Access to the path is denied."; public const string ArgumentOutOfRange_FileLengthTooBig = "Specified file length was too large for the file system."; public const string PlatformNotSupported_MessageTransmissionMode = "Message transmission mode is not supported on this platform."; public const string PlatformNotSupported_RemotePipes = "Access to remote named pipes is not supported on this platform."; public const string PlatformNotSupported_InvalidPipeNameChars = "The name of a pipe on this platform must be a valid file name or a valid absolute path to a file name."; public const string ObjectDisposed_StreamClosed = "Cannot access a closed Stream."; public const string PlatformNotSupported_OperatingSystemError = "The operating system returned error '{0}' indicating that the operation is not supported."; public const string IO_AllPipeInstancesAreBusy = "All pipe instances are busy."; public const string IO_PathTooLong_Path = "The path '{0}' is too long, or a component of the specified path is too long."; public const string UnauthorizedAccess_NotOwnedByCurrentUser = "Could not connect to the pipe because it was not owned by the current user."; public const string UnauthorizedAccess_ClientIsNotCurrentUser = "Client connection (user id {0}) was refused because it was not owned by the current user (id {1})."; public const string net_invalidversion = "This protocol version is not supported."; public const string net_noseek = "This stream does not support seek operations."; public const string net_invasync = "Cannot block a call on this socket while an earlier asynchronous call is in progress."; public const string net_io_timeout_use_gt_zero = "Timeout can be only be set to 'System.Threading.Timeout.Infinite' or a value > 0."; public const string net_notconnected = "The operation is not allowed on non-connected sockets."; public const string net_notstream = "The operation is not allowed on non-stream oriented sockets."; public const string net_stopped = "Not listening. You must call the Start() method before calling this method."; public const string net_udpconnected = "Cannot send packets to an arbitrary host while connected."; public const string net_readonlystream = "The stream does not support writing."; public const string net_writeonlystream = "The stream does not support reading."; public const string net_InvalidAddressFamily = "The AddressFamily {0} is not valid for the {1} end point, use {2} instead."; public const string net_InvalidEndPointAddressFamily = "The supplied EndPoint of AddressFamily {0} is not valid for this Socket, use {1} instead."; public const string net_InvalidSocketAddressSize = "The supplied {0} is an invalid size for the {1} end point."; public const string net_invalidAddressList = "None of the discovered or specified addresses match the socket address family."; public const string net_completed_result = "This operation cannot be performed on a completed asynchronous result object."; public const string net_protocol_invalid_family = "'{0}' Client can only accept InterNetwork or InterNetworkV6 addresses."; public const string net_protocol_invalid_multicast_family = "Multicast family is not the same as the family of the '{0}' Client."; public const string net_sockets_zerolist = "The parameter {0} must contain one or more elements."; public const string net_sockets_blocking = "The operation is not allowed on a non-blocking Socket."; public const string net_sockets_useblocking = "Use the Blocking property to change the status of the Socket."; public const string net_sockets_select = "The operation is not allowed on objects of type {0}. Use only objects of type {1}."; public const string net_sockets_toolarge_select = "The {0} list contains too many items; a maximum of {1} is allowed."; public const string net_sockets_empty_select = "All lists are either null or empty."; public const string net_sockets_mustbind = "You must call the Bind method before performing this operation."; public const string net_sockets_mustlisten = "You must call the Listen method before performing this operation."; public const string net_sockets_mustnotlisten = "You may not perform this operation after calling the Listen method."; public const string net_sockets_mustnotbebound = "The socket must not be bound or connected."; public const string net_sockets_namedmustnotbebound = "{0}: The socket must not be bound or connected."; public const string net_sockets_invalid_ipaddress_length = "The number of specified IP addresses has to be greater than 0."; public const string net_sockets_invalid_optionValue = "The specified value is not a valid '{0}'."; public const string net_sockets_invalid_optionValue_all = "The specified value is not valid."; public const string net_sockets_invalid_dnsendpoint = "The parameter {0} must not be of type DnsEndPoint."; public const string net_sockets_disconnectedConnect = "Once the socket has been disconnected, you can only reconnect again asynchronously, and only to a different EndPoint. BeginConnect must be called on a thread that won't exit until the operation has been completed."; public const string net_sockets_disconnectedAccept = "Once the socket has been disconnected, you can only accept again asynchronously. BeginAccept must be called on a thread that won't exit until the operation has been completed."; public const string net_tcplistener_mustbestopped = "The TcpListener must not be listening before performing this operation."; public const string net_socketopinprogress = "An asynchronous socket operation is already in progress using this SocketAsyncEventArgs instance."; public const string net_buffercounttoosmall = "The Buffer space specified by the Count property is insufficient for the AcceptAsync method."; public const string net_multibuffernotsupported = "Multiple buffers cannot be used with this method."; public const string net_ambiguousbuffers = "Buffer and BufferList properties cannot both be non-null."; public const string net_io_writefailure = "Unable to write data to the transport connection: {0}."; public const string net_io_readfailure = "Unable to read data from the transport connection: {0}."; public const string net_io_invalidasyncresult = "The IAsyncResult object was not returned from the corresponding asynchronous method on this class."; public const string net_io_invalidendcall = "{0} can only be called once for each asynchronous operation."; public const string net_value_cannot_be_negative = "The specified value cannot be negative."; public const string ArgumentOutOfRange_Bounds_Lower_Upper = "Argument must be between {0} and {1}."; public const string net_sockets_connect_multiconnect_notsupported = "Sockets on this platform are invalid for use after a failed connection attempt."; public const string net_sockets_dualmode_receivefrom_notsupported = "This platform does not support packet information for dual-mode sockets. If packet information is not required, use Socket.Receive. If packet information is required set Socket.DualMode to false."; public const string net_sockets_accept_receive_notsupported = "This platform does not support receiving data with Socket.AcceptAsync. Instead, make a separate call to Socket.ReceiveAsync."; public const string net_sockets_duplicateandclose_notsupported = "This platform does not support Socket.DuplicateAndClose. Instead, create a new socket."; public const string net_sockets_transmitfileoptions_notsupported = "This platform does not support TransmitFileOptions other than TransmitFileOptions.UseDefaultWorkerThread."; public const string ArgumentOutOfRange_PathLengthInvalid = "The path '{0}' is of an invalid length for use with domain sockets on this platform. The length must be between 1 and {1} characters, inclusive."; public const string net_io_readwritefailure = "Unable to transfer data on the transport connection: {0}."; public const string PlatformNotSupported_AcceptSocket = "Accepting into an existing Socket is not supported on this platform."; public const string PlatformNotSupported_IOControl = "Socket.IOControl handles Windows-specific control codes and is not supported on this platform."; public const string PlatformNotSupported_IPProtectionLevel = "IP protection level cannot be controlled on this platform."; public const string InvalidOperation_BufferNotExplicitArray = "This operation may only be performed when the buffer was set using the SetBuffer overload that accepts an array."; public const string InvalidOperation_IncorrectToken = "The result of the operation was already consumed and may not be used again."; public const string InvalidOperation_MultipleContinuations = "Another continuation was already registered."; public const string Argument_InvalidOidValue = "The OID value was invalid."; public const string Argument_InvalidValue = "Value was invalid."; public const string Arg_CryptographyException = "Error occurred during a cryptographic operation."; public const string Cryptography_ArgECDHKeySizeMismatch = "The keys from both parties must be the same size to generate a secret agreement."; public const string Cryptography_ArgECDHRequiresECDHKey = "Keys used with the ECDiffieHellmanCng algorithm must have an algorithm group of ECDiffieHellman."; public const string Cryptography_TlsRequiresLabelAndSeed = "The TLS key derivation function requires both the label and seed properties to be set."; public const string Cryptography_TlsRequires64ByteSeed = "The TLS key derivation function requires a seed value of exactly 64 bytes."; public const string Cryptography_BadHashSize_ForAlgorithm = "The provided value of {0} bytes does not match the expected size of {1} bytes for the algorithm ({2})."; public const string Cryptography_Config_EncodedOIDError = "Encoded OID length is too large (greater than 0x7f bytes)."; public const string Cryptography_CSP_NoPrivateKey = "Object contains only the public half of a key pair. A private key must also be provided."; public const string Cryptography_Der_Invalid_Encoding = "ASN1 corrupted data."; public const string Cryptography_DSA_KeyGenNotSupported = "DSA keys can be imported, but new key generation is not supported on this platform."; public const string Cryptography_Encryption_MessageTooLong = "The message exceeds the maximum allowable length for the chosen options ({0})."; public const string Cryptography_ECXmlSerializationFormatRequired = "XML serialization of an elliptic curve key requires using an overload which specifies the XML format to be used."; public const string Cryptography_ECC_NamedCurvesOnly = "Only named curves are supported on this platform."; public const string Cryptography_HashAlgorithmNameNullOrEmpty = "The hash algorithm name cannot be null or empty."; public const string Cryptography_InvalidOID = "Object identifier (OID) is unknown."; public const string Cryptography_CurveNotSupported = "The specified curve '{0}' or its parameters are not valid for this platform."; public const string Cryptography_InvalidCurveOid = "The specified Oid is not valid. The Oid.FriendlyName or Oid.Value property must be set."; public const string Cryptography_InvalidCurveKeyParameters = "The specified key parameters are not valid. Q.X and Q.Y are required fields. Q.X, Q.Y must be the same length. If D is specified it must be the same length as Q.X and Q.Y for named curves or the same length as Order for explicit curves."; public const string Cryptography_InvalidDsaParameters_MissingFields = "The specified DSA parameters are not valid; P, Q, G and Y are all required."; public const string Cryptography_InvalidDsaParameters_MismatchedPGY = "The specified DSA parameters are not valid; P, G and Y must be the same length (the key size)."; public const string Cryptography_InvalidDsaParameters_MismatchedQX = "The specified DSA parameters are not valid; Q and X (if present) must be the same length."; public const string Cryptography_InvalidDsaParameters_MismatchedPJ = "The specified DSA parameters are not valid; J (if present) must be shorter than P."; public const string Cryptography_InvalidDsaParameters_SeedRestriction_ShortKey = "The specified DSA parameters are not valid; Seed, if present, must be 20 bytes long for keys shorter than 1024 bits."; public const string Cryptography_InvalidDsaParameters_QRestriction_ShortKey = "The specified DSA parameters are not valid; Q must be 20 bytes long for keys shorter than 1024 bits."; public const string Cryptography_InvalidDsaParameters_QRestriction_LargeKey = "The specified DSA parameters are not valid; Q's length must be one of 20, 32 or 64 bytes."; public const string Cryptography_InvalidECCharacteristic2Curve = "The specified Characteristic2 curve parameters are not valid. Polynomial, A, B, G.X, G.Y, and Order are required. A, B, G.X, G.Y must be the same length, and the same length as Q.X, Q.Y and D if those are specified. Seed, Cofactor and Hash are optional. Other parameters are not allowed."; public const string Cryptography_InvalidECPrimeCurve = "The specified prime curve parameters are not valid. Prime, A, B, G.X, G.Y and Order are required and must be the same length, and the same length as Q.X, Q.Y and D if those are specified. Seed, Cofactor and Hash are optional. Other parameters are not allowed."; public const string Cryptography_InvalidECNamedCurve = "The specified named curve parameters are not valid. Only the Oid parameter must be set."; public const string Cryptography_InvalidKeySize = "Specified key is not a valid size for this algorithm."; public const string Cryptography_InvalidKey_SemiWeak = "Specified key is a known semi-weak key for '{0}' and cannot be used."; public const string Cryptography_InvalidKey_Weak = "Specified key is a known weak key for '{0}' and cannot be used."; public const string Cryptography_InvalidIVSize = "Specified initialization vector (IV) does not match the block size for this algorithm."; public const string Cryptography_InvalidOperation = "This operation is not supported for this class."; public const string Cryptography_InvalidPadding = "Padding is invalid and cannot be removed."; public const string Cryptography_InvalidRsaParameters = "The specified RSA parameters are not valid; both Exponent and Modulus are required fields."; public const string Cryptography_InvalidPaddingMode = "Specified padding mode is not valid for this algorithm."; public const string Cryptography_Invalid_IA5String = "The string contains a character not in the 7 bit ASCII character set."; public const string Cryptography_KeyTooSmall = "The key is too small for the requested operation."; public const string Cryptography_MissingIV = "The cipher mode specified requires that an initialization vector (IV) be used."; public const string Cryptography_MissingKey = "No asymmetric key object has been associated with this formatter object."; public const string Cryptography_MissingOID = "Required object identifier (OID) cannot be found."; public const string Cryptography_MustTransformWholeBlock = "TransformBlock may only process bytes in block sized increments."; public const string Cryptography_NotValidPrivateKey = "Key is not a valid private key."; public const string Cryptography_NotValidPublicOrPrivateKey = "Key is not a valid public or private key."; public const string Cryptography_OAEP_Decryption_Failed = "Error occurred while decoding OAEP padding."; public const string Cryptography_OpenInvalidHandle = "Cannot open an invalid handle."; public const string Cryptography_PartialBlock = "The input data is not a complete block."; public const string Cryptography_PasswordDerivedBytes_FewBytesSalt = "Salt is not at least eight bytes."; public const string Cryptography_RC2_EKS40 = "EffectiveKeySize value must be at least 40 bits."; public const string Cryptography_RC2_EKSKS = "KeySize value must be at least as large as the EffectiveKeySize value."; public const string Cryptography_RC2_EKSKS2 = "EffectiveKeySize must be the same as KeySize in this implementation."; public const string Cryptography_Rijndael_BlockSize = "BlockSize must be 128 in this implementation."; public const string Cryptography_RSA_DecryptWrongSize = "The length of the data to decrypt is not valid for the size of this key."; public const string Cryptography_SignHash_WrongSize = "The provided hash value is not the expected size for the specified hash algorithm."; public const string Cryptography_TransformBeyondEndOfBuffer = "Attempt to transform beyond end of buffer."; public const string Cryptography_CipherModeNotSupported = "The specified CipherMode '{0}' is not supported."; public const string Cryptography_UnknownHashAlgorithm = "'{0}' is not a known hash algorithm."; public const string Cryptography_UnknownPaddingMode = "Unknown padding mode used."; public const string Cryptography_UnexpectedTransformTruncation = "CNG provider unexpectedly terminated encryption or decryption prematurely."; public const string Cryptography_Unmapped_System_Typed_Error = "The system cryptographic library returned error '{0}' of type '{1}'"; public const string Cryptography_UnsupportedPaddingMode = "The specified PaddingMode is not supported."; public const string NotSupported_Method = "Method not supported."; public const string NotSupported_SubclassOverride = "Method not supported. Derived class must override."; public const string Cryptography_AlgorithmTypesMustBeVisible = "Algorithms added to CryptoConfig must be accessable from outside their assembly."; public const string Cryptography_AddNullOrEmptyName = "CryptoConfig cannot add a mapping for a null or empty name."; public const string Argument_Invalid_SafeHandleInvalidOrClosed = "The method cannot be called with an invalid or closed SafeHandle."; public const string Cryptography_ArgExpectedECDiffieHellmanCngPublicKey = "DeriveKeyMaterial requires an ECDiffieHellmanCngPublicKey."; public const string Cryptography_ArgDSARequiresDSAKey = "Keys used with the DSACng algorithm must have an algorithm group of DSA."; public const string Cryptography_ArgECDsaRequiresECDsaKey = "Keys used with the ECDsaCng algorithm must have an algorithm group of ECDsa."; public const string Cryptography_ArgRSARequiresRSAKey = "Keys used with the RSACng algorithm must have an algorithm group of RSA."; public const string Cryptography_CngKeyWrongAlgorithm = "This key is for algorithm '{0}'. Expected '{1}'."; public const string Cryptography_InvalidAlgorithmGroup = "The algorithm group '{0}' is invalid."; public const string Cryptography_InvalidAlgorithmName = "The algorithm name '{0}' is invalid."; public const string Cryptography_InvalidCipherMode = "Specified cipher mode is not valid for this algorithm."; public const string Cryptography_InvalidKeyBlobFormat = "The key blob format '{0}' is invalid."; public const string Cryptography_InvalidProviderName = "The provider name '{0}' is invalid."; public const string Cryptography_KeyBlobParsingError = "Key Blob not in expected format."; public const string Cryptography_OpenEphemeralKeyHandleWithoutEphemeralFlag = "The CNG key handle being opened was detected to be ephemeral, but the EphemeralKey open option was not specified."; public const string Cryptography_WeakKey = "Specified key is a known weak key for this algorithm and cannot be used."; public const string PlatformNotSupported_CryptographyCng = "Windows Cryptography Next Generation (CNG) is not supported on this platform."; public const string CountdownEvent_Increment_AlreadyZero = "The event is already signaled and cannot be incremented."; public const string CountdownEvent_Increment_AlreadyMax = "The increment operation would cause the CurrentCount to overflow."; public const string CountdownEvent_Decrement_BelowZero = "Invalid attempt made to decrement the event's count below zero."; public const string Common_OperationCanceled = "The operation was canceled."; public const string Barrier_Dispose = "The barrier has been disposed."; public const string Barrier_SignalAndWait_InvalidOperation_ZeroTotal = "The barrier has no registered participants."; public const string Barrier_SignalAndWait_ArgumentOutOfRange = "The specified timeout must represent a value between -1 and Int32.MaxValue, inclusive."; public const string Barrier_RemoveParticipants_InvalidOperation = "The participantCount argument is greater than the number of participants that haven't yet arrived at the barrier in this phase."; public const string Barrier_RemoveParticipants_ArgumentOutOfRange = "The participantCount argument must be less than or equal the number of participants."; public const string Barrier_RemoveParticipants_NonPositive_ArgumentOutOfRange = "The participantCount argument must be a positive value."; public const string Barrier_InvalidOperation_CalledFromPHA = "This method may not be called from within the postPhaseAction."; public const string Barrier_AddParticipants_NonPositive_ArgumentOutOfRange = "The participantCount argument must be a positive value."; public const string Barrier_SignalAndWait_InvalidOperation_ThreadsExceeded = "The number of threads using the barrier exceeded the total number of registered participants."; public const string BarrierPostPhaseException = "The postPhaseAction failed with an exception."; public const string Barrier_ctor_ArgumentOutOfRange = "The participantCount argument must be non-negative and less than or equal to 32767."; public const string Barrier_AddParticipants_Overflow_ArgumentOutOfRange = "Adding participantCount participants would result in the number of participants exceeding the maximum number allowed."; public const string SynchronizationLockException_IncorrectDispose = "The lock is being disposed while still being used. It either is being held by a thread and/or has active waiters waiting to acquire the lock."; public const string SynchronizationLockException_MisMatchedWrite = "The write lock is being released without being held."; public const string LockRecursionException_UpgradeAfterReadNotAllowed = "Upgradeable lock may not be acquired with read lock held."; public const string LockRecursionException_UpgradeAfterWriteNotAllowed = "Upgradeable lock may not be acquired with write lock held in this mode. Acquiring Upgradeable lock gives the ability to read along with an option to upgrade to a writer."; public const string SynchronizationLockException_MisMatchedUpgrade = "The upgradeable lock is being released without being held."; public const string SynchronizationLockException_MisMatchedRead = "The read lock is being released without being held."; public const string LockRecursionException_WriteAfterReadNotAllowed = "Write lock may not be acquired with read lock held. This pattern is prone to deadlocks. Please ensure that read locks are released before taking a write lock. If an upgrade is necessary, use an upgrade lock in place of the read lock."; public const string LockRecursionException_RecursiveWriteNotAllowed = "Recursive write lock acquisitions not allowed in this mode."; public const string LockRecursionException_ReadAfterWriteNotAllowed = "A read lock may not be acquired with the write lock held in this mode."; public const string LockRecursionException_RecursiveUpgradeNotAllowed = "Recursive upgradeable lock acquisitions not allowed in this mode."; public const string LockRecursionException_RecursiveReadNotAllowed = "Recursive read lock acquisitions not allowed in this mode."; public const string Overflow_UInt16 = "Value was either too large or too small for a UInt16."; public const string ReaderWriterLock_Timeout = "The operation has timed out. {0}"; public const string ArgumentOutOfRange_TimeoutMilliseconds = "Timeout value in milliseconds must be nonnegative and less than or equal to Int32.MaxValue, or -1 for an infinite timeout."; public const string ReaderWriterLock_NotOwner = "Attempt to release a lock that is not owned by the calling thread. {0}"; public const string ExceptionFromHResult = "(Exception from HRESULT: 0x{0:X})"; public const string ReaderWriterLock_InvalidLockCookie = "The specified lock cookie is invalid for this operation. {0}"; public const string ReaderWriterLock_RestoreLockWithOwnedLocks = "ReaderWriterLock.RestoreLock was called without releasing all locks acquired since the call to ReleaseLock."; public const string HostExecutionContextManager_InvalidOperation_NotNewCaptureContext = "Cannot apply a context that has been marshaled across AppDomains, that was not acquired through a Capture operation or that has already been the argument to a Set call."; public const string HostExecutionContextManager_InvalidOperation_CannotOverrideSetWithoutRevert = "Must override both HostExecutionContextManager.SetHostExecutionContext and HostExecutionContextManager.Revert."; public const string HostExecutionContextManager_InvalidOperation_CannotUseSwitcherOtherThread = "Undo operation must be performed on the thread where the corresponding context was Set."; public const string Arg_NonZeroLowerBound = "The lower bound of target array must be zero."; public const string Arg_WrongType = "The value '{0}' is not of type '{1}' and cannot be used in this generic collection."; public const string Arg_ArrayPlusOffTooSmall = "Destination array is not long enough to copy all the items in the collection. Check array index and length."; public const string ArgumentOutOfRange_SmallCapacity = "capacity was less than the current size."; public const string Argument_AddingDuplicate = "An item with the same key has already been added. Key: {0}"; public const string InvalidOperation_ConcurrentOperationsNotSupported = "Operations that change non-concurrent collections must have exclusive access. A concurrent update was performed on this collection and corrupted its state. The collection's state is no longer correct."; public const string InvalidOperation_EmptyQueue = "Queue empty."; public const string InvalidOperation_EnumOpCantHappen = "Enumeration has either not started or has already finished."; public const string InvalidOperation_EnumFailedVersion = "Collection was modified; enumeration operation may not execute."; public const string InvalidOperation_EmptyStack = "Stack empty."; public const string InvalidOperation_EnumNotStarted = "Enumeration has not started. Call MoveNext."; public const string InvalidOperation_EnumEnded = "Enumeration already finished."; public const string NotSupported_KeyCollectionSet = "Mutating a key collection derived from a dictionary is not allowed."; public const string NotSupported_ValueCollectionSet = "Mutating a value collection derived from a dictionary is not allowed."; public const string Arg_ArrayLengthsDiffer = "Array lengths must be the same."; public const string Arg_BitArrayTypeUnsupported = "Only supported array types for CopyTo on BitArrays are Boolean[], Int32[] and Byte[]."; public const string Arg_HSCapacityOverflow = "HashSet capacity is too big."; public const string Arg_HTCapacityOverflow = "Hashtable's capacity overflowed and went negative. Check load factor, capacity and the current size of the table."; public const string Arg_InsufficientSpace = "Insufficient space in the target location to copy the information."; public const string Arg_RankMultiDimNotSupported = "Only single dimensional arrays are supported for the requested action."; public const string Argument_ArrayTooLarge = "The input array length must not exceed Int32.MaxValue / {0}. Otherwise BitArray.Length would exceed Int32.MaxValue."; public const string Argument_InvalidArrayType = "Target array type is not compatible with the type of items in the collection."; public const string ArgumentOutOfRange_BiggerThanCollection = "Must be less than or equal to the size of the collection."; public const string ArgumentOutOfRange_Index = "Index was out of range. Must be non-negative and less than the size of the collection."; public const string ExternalLinkedListNode = "The LinkedList node does not belong to current LinkedList."; public const string LinkedListEmpty = "The LinkedList is empty."; public const string LinkedListNodeIsAttached = "The LinkedList node already belongs to a LinkedList."; public const string NotSupported_SortedListNestedWrite = "This operation is not supported on SortedList nested types because they require modifying the original SortedList."; public const string SortedSet_LowerValueGreaterThanUpperValue = "Must be less than or equal to upperValue."; public const string Serialization_InvalidOnDeser = "OnDeserialization method was called while the object was not being deserialized."; public const string Serialization_MismatchedCount = "The serialized Count information doesn't match the number of items."; public const string Serialization_MissingKeys = "The keys for this dictionary are missing."; public const string Serialization_MissingValues = "The values for this dictionary are missing."; public const string Argument_MapNameEmptyString = "Map name cannot be an empty string."; public const string Argument_EmptyFile = "A positive capacity must be specified for a Memory Mapped File backed by an empty file."; public const string Argument_NewMMFWriteAccessNotAllowed = "MemoryMappedFileAccess.Write is not permitted when creating new memory mapped files. Use MemoryMappedFileAccess.ReadWrite instead."; public const string Argument_ReadAccessWithLargeCapacity = "When specifying MemoryMappedFileAccess.Read access, the capacity must not be larger than the file size."; public const string Argument_NewMMFAppendModeNotAllowed = "FileMode.Append is not permitted when creating new memory mapped files. Instead, use MemoryMappedFileView to ensure write-only access within a specified region."; public const string Argument_NewMMFTruncateModeNotAllowed = "FileMode.Truncate is not permitted when creating new memory mapped files."; public const string ArgumentNull_MapName = "Map name cannot be null."; public const string ArgumentNull_FileStream = "fileStream cannot be null."; public const string ArgumentOutOfRange_CapacityLargerThanLogicalAddressSpaceNotAllowed = "The capacity cannot be greater than the size of the system's logical address space."; public const string ArgumentOutOfRange_NeedPositiveNumber = "A positive number is required."; public const string ArgumentOutOfRange_PositiveOrDefaultCapacityRequired = "The capacity must be greater than or equal to 0. 0 represents the size of the file being mapped."; public const string ArgumentOutOfRange_PositiveOrDefaultSizeRequired = "The size must be greater than or equal to 0. If 0 is specified, the view extends from the specified offset to the end of the file mapping."; public const string ArgumentOutOfRange_CapacityGEFileSizeRequired = "The capacity may not be smaller than the file size."; public const string IO_NotEnoughMemory = "Not enough memory to map view."; public const string InvalidOperation_CantCreateFileMapping = "Cannot create file mapping."; public const string NotSupported_MMViewStreamsFixedLength = "MemoryMappedViewStreams are fixed length."; public const string ObjectDisposed_ViewAccessorClosed = "Cannot access a closed accessor."; public const string ObjectDisposed_StreamIsClosed = "Cannot access a closed Stream."; public const string PlatformNotSupported_NamedMaps = "Named maps are not supported."; public const string MethodBuilderDoesNotHaveTypeBuilder = "MethodBuilder does not have a valid TypeBuilder"; public const string Cryptography_NonCompliantFIPSAlgorithm = "This implementation is not part of the Windows Platform FIPS validated cryptographic algorithms."; public const string InvalidOperation_ViewIsNull = "The underlying MemoryMappedView object is null."; public const string ArgumentOutOfRange_InvalidPipeAccessRights = "Invalid PipeAccessRights flag."; public const string ArgumentOutOfRange_AdditionalAccessLimited = "additionalAccessRights is limited to the PipeAccessRights.ChangePermissions, PipeAccessRights.TakeOwnership, and PipeAccessRights.AccessSystemSecurity flags when creating NamedPipeServerStreams."; public const string InterfaceType_Must_Be_Interface = "The type '{0}' must be an interface, not a class."; public const string BaseType_Cannot_Be_Sealed = "The base type '{0}' cannot be sealed."; public const string BaseType_Cannot_Be_Abstract = "The base type '{0}' cannot be abstract."; public const string BaseType_Must_Have_Default_Ctor = "The base type '{0}' must have a public parameterless constructor."; public const string Cryptography_Cert_AlreadyHasPrivateKey = "The certificate already has an associated private key."; public const string Cryptography_PrivateKey_WrongAlgorithm = "The provided key does not match the public key algorithm for this certificate."; public const string Cryptography_PrivateKey_DoesNotMatch = "The provided key does not match the public key for this certificate."; internal static string GetString(string name, params object[] args) { return GetString(CultureInfo.InvariantCulture, name, args); } internal static string GetString(CultureInfo culture, string name, params object[] args) { return string.Format(culture, name, args); } internal static string GetString(string name) { return name; } internal static string GetString(CultureInfo culture, string name) { return name; } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { return string.Format(CultureInfo.InvariantCulture, resourceFormat, args); } return resourceFormat; } internal static string Format(string resourceFormat, object p1) { return string.Format(CultureInfo.InvariantCulture, resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { return string.Format(CultureInfo.InvariantCulture, resourceFormat, p1, p2); } internal static string Format(CultureInfo ci, string resourceFormat, object p1, object p2) { return string.Format(ci, resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { return string.Format(CultureInfo.InvariantCulture, resourceFormat, p1, p2, p3); } internal static string GetResourceString(string str) { return str; } } namespace Microsoft.Win32.SafeHandles { public sealed class SafePipeHandle : SafeHandleZeroOrMinusOneIsInvalid { private const int DefaultInvalidHandle = 0; protected override bool ReleaseHandle() { return global::Interop.Kernel32.CloseHandle(handle); } internal SafePipeHandle() : this(new IntPtr(0), ownsHandle: true) { } public SafePipeHandle(IntPtr preexistingHandle, bool ownsHandle) : base(ownsHandle) { SetHandle(preexistingHandle); } internal void SetHandle(int descriptor) { SetHandle((IntPtr)descriptor); } } public sealed class SafeMemoryMappedFileHandle : SafeHandleZeroOrMinusOneIsInvalid { public SafeMemoryMappedFileHandle(IntPtr preexistingHandle, bool ownsHandle) : base(ownsHandle) { handle = preexistingHandle; } protected override bool ReleaseHandle() { MemoryMapImpl.CloseMapping(handle); handle = IntPtr.Zero; return true; } internal SafeMemoryMappedFileHandle() { ThrowStub.ThrowNotSupportedException(); } } public sealed class SafeMemoryMappedViewHandle : SafeBuffer { private IntPtr mmap_handle; internal SafeMemoryMappedViewHandle(IntPtr mmap_handle, IntPtr base_address, long size) : base(ownsHandle: true) { this.mmap_handle = mmap_handle; handle = base_address; Initialize((ulong)size); } internal void Flush() { MemoryMapImpl.Flush(mmap_handle); } protected override bool ReleaseHandle() { if (handle != (IntPtr)(-1)) { return MemoryMapImpl.Unmap(mmap_handle); } throw new NotImplementedException(); } internal SafeMemoryMappedViewHandle() { ThrowStub.ThrowNotSupportedException(); } } public abstract class SafeNCryptHandle : SafeHandleZeroOrMinusOneIsInvalid { public override bool IsInvalid { get { throw new NotImplementedException(); } } protected SafeNCryptHandle() : base(ownsHandle: true) { } protected SafeNCryptHandle(IntPtr handle, SafeHandle parentHandle) : base(ownsHandle: false) { throw new NotImplementedException(); } protected override bool ReleaseHandle() { return false; } protected abstract bool ReleaseNativeHandle(); } public sealed class SafeNCryptKeyHandle : SafeNCryptHandle { public SafeNCryptKeyHandle() { } public SafeNCryptKeyHandle(IntPtr handle, SafeHandle parentHandle) : base(handle, parentHandle) { } protected override bool ReleaseNativeHandle() { return false; } } public sealed class SafeNCryptProviderHandle : SafeNCryptHandle { protected override bool ReleaseNativeHandle() { return false; } } public sealed class SafeNCryptSecretHandle : SafeNCryptHandle { protected override bool ReleaseNativeHandle() { return false; } } } namespace System { internal static class NotImplemented { internal static Exception ByDesign => new NotImplementedException(); internal static Exception ByDesignWithMessage(string message) { return new NotImplementedException(message); } internal static Exception ActiveIssue(string issue) { return new NotImplementedException(); } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] internal class MonoTODOAttribute : Attribute { private string comment; public string Comment => comment; public MonoTODOAttribute() { } public MonoTODOAttribute(string comment) { this.comment = comment; } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] internal class MonoDocumentationNoteAttribute : MonoTODOAttribute { public MonoDocumentationNoteAttribute(string comment) : base(comment) { } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] internal class MonoExtensionAttribute : MonoTODOAttribute { public MonoExtensionAttribute(string comment) : base(comment) { } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] internal class MonoInternalNoteAttribute : MonoTODOAttribute { public MonoInternalNoteAttribute(string comment) : base(comment) { } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] internal class MonoLimitationAttribute : MonoTODOAttribute { public MonoLimitationAttribute(string comment) : base(comment) { } } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] internal class MonoNotSupportedAttribute : MonoTODOAttribute { public MonoNotSupportedAttribute(string comment) : base(comment) { } } public delegate void Action<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9); public delegate void Action<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10); public delegate void Action<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11); public delegate void Action<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12); public delegate void Action<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13); public delegate void Action<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14); public delegate void Action<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14, in T15>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15); public delegate void Action<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14, in T15, in T16>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15, T16 arg16); public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9); public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10); public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11); public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12); public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13); public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14); public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14, in T15, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15); public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14, in T15, in T16, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15, T16 arg16); internal static class MonoUtil { public static readonly bool IsUnix; static MonoUtil() { int platform = (int)Environment.OSVersion.Platform; IsUnix = platform == 4 || platform == 128 || platform == 6; } } } namespace System.Security.Cryptography { [DebuggerDisplay("ECCurve: {Oid}")] public struct ECCurve { public enum ECCurveType { Implicit, PrimeShortWeierstrass, PrimeTwistedEdwards, PrimeMontgomery, Characteristic2, Named } public static class NamedCurves { private const string ECDSA_P256_OID_VALUE = "1.2.840.10045.3.1.7"; private const string ECDSA_P384_OID_VALUE = "1.3.132.0.34"; private const string ECDSA_P521_OID_VALUE = "1.3.132.0.35"; public static ECCurve brainpoolP160r1 => CreateFromFriendlyName("brainpoolP160r1"); public static ECCurve brainpoolP160t1 => CreateFromFriendlyName("brainpoolP160t1"); public static ECCurve brainpoolP192r1 => CreateFromFriendlyName("brainpoolP192r1"); public static ECCurve brainpoolP192t1 => CreateFromFriendlyName("brainpoolP192t1"); public static ECCurve brainpoolP224r1 => CreateFromFriendlyName("brainpoolP224r1"); public static ECCurve brainpoolP224t1 => CreateFromFriendlyName("brainpoolP224t1"); public static ECCurve brainpoolP256r1 => CreateFromFriendlyName("brainpoolP256r1"); public static ECCurve brainpoolP256t1 => CreateFromFriendlyName("brainpoolP256t1"); public static ECCurve brainpoolP320r1 => CreateFromFriendlyName("brainpoolP320r1"); public static ECCurve brainpoolP320t1 => CreateFromFriendlyName("brainpoolP320t1"); public static ECCurve brainpoolP384r1 => CreateFromFriendlyName("brainpoolP384r1"); public static ECCurve brainpoolP384t1 => CreateFromFriendlyName("brainpoolP384t1"); public static ECCurve brainpoolP512r1 => CreateFromFriendlyName("brainpoolP512r1"); public static ECCurve brainpoolP512t1 => CreateFromFriendlyName("brainpoolP512t1"); public static ECCurve nistP256 => CreateFromValueAndName("1.2.840.10045.3.1.7", "nistP256"); public static ECCurve nistP384 => CreateFromValueAndName("1.3.132.0.34", "nistP384"); public static ECCurve nistP521 => CreateFromValueAndName("1.3.132.0.35", "nistP521"); } public byte[] A; public byte[] B; public ECPoint G; public byte[] Order; public byte[] Cofactor; public byte[] Seed; public ECCurveType CurveType; public HashAlgorithmName? Hash; public byte[] Polynomial; public byte[] Prime; private Oid _oid; public Oid Oid { get { return new Oid(_oid.Value, _oid.FriendlyName); } private set { if (value == null) { throw new ArgumentNullException("Oid"); } if (string.IsNullOrEmpty(value.Value) && string.IsNullOrEmpty(value.FriendlyName)) { throw new ArgumentException($"The specified Oid is not valid. The Oid.FriendlyName or Oid.Value property must be set."); } _oid = value; } } public bool IsPrime { get { if (CurveType != ECCurveType.PrimeShortWeierstrass && CurveType != ECCurveType.PrimeMontgomery) { return CurveType == ECCurveType.PrimeTwistedEdwards; } return true; } } public bool IsCharacteristic2 => CurveType == ECCurveType.Characteristic2; public bool IsExplicit { get { if (!IsPrime) { return IsCharacteristic2; } return true; } } public bool IsNamed => CurveType == ECCurveType.Named; private static ECCurve Create(Oid oid) { ECCurve result = default(ECCurve); result.CurveType = ECCurveType.Named; result.Oid = oid; return result; } public static ECCurve CreateFromOid(Oid curveOid) { return Create(new Oid(curveOid.Value, curveOid.FriendlyName)); } public static ECCurve CreateFromFriendlyName(string oidFriendlyName) { if (oidFriendlyName == null) { throw new ArgumentNullException("oidFriendlyName"); } return CreateFromValueAndName(null, oidFriendlyName); } public static ECCurve CreateFromValue(string oidValue) { if (oidValue == null) { throw new ArgumentNullException("oidValue"); } return CreateFromValueAndName(oidValue, null); } private static ECCurve CreateFromValueAndName(string oidValue, string oidFriendlyName) { return Create(new Oid(oidValue, oidFriendlyName)); } public void Validate() { if (IsNamed) { if (HasAnyExplicitParameters()) { throw new CryptographicException("The specified named curve parameters are not valid. Only the Oid parameter must be set."); } if (Oid == null || (string.IsNullOrEmpty(Oid.FriendlyName) && string.IsNullOrEmpty(Oid.Value))) { throw new CryptographicException("The specified Oid is not valid. The Oid.FriendlyName or Oid.Value property must be set."); } } else if (IsExplicit) { bool flag = false; if (A == null || B == null || B.Length != A.Length || G.X == null || G.X.Length != A.Length || G.Y == null || G.Y.Length != A.Length || Order == null || Order.Length == 0 || Cofactor == null || Cofactor.Length == 0) { flag = true; } if (IsPrime) { if (!flag && (Prime == null || Prime.Length != A.Length)) { flag = true; } if (flag) { throw new CryptographicException("The specified prime curve parameters are not valid. Prime, A, B, G.X, G.Y and Order are required and must be the same length, and the same length as Q.X, Q.Y and D if those are
BepInExPack\unstripped_corlib\System.dll
Decompiled 2 months ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers; using System.Buffers.Binary; using System.CodeDom; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.ComponentModel.Design; using System.ComponentModel.Design.Serialization; using System.Configuration; using System.Configuration.Internal; using System.Configuration.Provider; using System.Diagnostics; using System.Diagnostics.Tracing; using System.Globalization; using System.IO; using System.IO.Compression; using System.IO.CoreFX; using System.IO.Enumeration; using System.IO.Ports; using System.Linq; using System.Net; using System.Net.Cache; using System.Net.Configuration; using System.Net.Http; using System.Net.Mail; using System.Net.Mime; using System.Net.NetworkInformation; using System.Net.Security; using System.Net.Sockets; using System.Net.WebSockets; using System.Numerics; using System.Reflection; using System.Reflection.Emit; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Runtime.Remoting.Messaging; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Security; using System.Security.AccessControl; using System.Security.Authentication; using System.Security.Authentication.ExtendedProtection; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Security.Permissions; using System.Security.Policy; using System.Security.Principal; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Sources; using System.Timers; using System.Web.Util; using System.Xml; using System.Xml.Serialization; using System.Xml.XPath; using Internal.Cryptography; using Internal.Cryptography.Pal; using Microsoft.CSharp; using Microsoft.VisualBasic; using Microsoft.Win32; using Microsoft.Win32.SafeHandles; using Mono; using Mono.Audio; using Mono.Btls; using Mono.Http; using Mono.Net; using Mono.Net.Dns; using Mono.Net.Security; using Mono.Net.Security.Private; using Mono.Security; using Mono.Security.Authenticode; using Mono.Security.Cryptography; using Mono.Security.Interface; using Mono.Security.Protocol.Ntlm; using Mono.Security.X509; using Mono.Security.X509.Extensions; using Mono.Unity; using Mono.Util; using ObjCRuntimeInternal; using Unity; [assembly: InternalsVisibleTo("System.Web, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("System.dll")] [assembly: AssemblyDescription("System.dll")] [assembly: AssemblyDefaultAlias("System.dll")] [assembly: AssemblyCompany("Mono development team")] [assembly: AssemblyProduct("Mono Common Language Infrastructure")] [assembly: AssemblyCopyright("(c) Various Mono authors")] [assembly: AssemblyFileVersion("4.6.57.0")] [assembly: SatelliteContractVersion("4.0.0.0")] [assembly: CompilationRelaxations(8)] [assembly: CLSCompliant(true)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: ComVisible(false)] [assembly: AllowPartiallyTrustedCallers] [assembly: AssemblyDelaySign(true)] [assembly: AssemblyKeyFile("../ecma.pub")] [assembly: InternalsVisibleTo("System.ComponentModel.DataAnnotations, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] [assembly: InternalsVisibleTo("System.Data, PublicKey=00000000000000000400000000000000")] [assembly: InternalsVisibleTo("System.Net.Http, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] [assembly: InternalsVisibleTo("System.Net.Http.WebRequest, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] [assembly: AssemblyInformationalVersion("4.6.57.0")] [assembly: InternalsVisibleTo("Mono.Btls.Interface, PublicKey=002400000480000094000000060200000024000052534131000400000100010079159977d2d03a8e6bea7a2e74e8d1afcc93e8851974952bb480a12c9134474d04062447c37e0e68c080536fcf3c3fbe2ff9c979ce998475e506e8ce82dd5b0f350dc10e93bf2eeecf874b24770c5081dbea7447fddafa277b22de47d6ffea449674a4f9fccf84d15069089380284dbdd35f46cdff12a1bd78e4ef0065d016df")] [assembly: InternalsVisibleTo("Mono.Security, PublicKey=002400000480000094000000060200000024000052534131000400000100010079159977d2d03a8e6bea7a2e74e8d1afcc93e8851974952bb480a12c9134474d04062447c37e0e68c080536fcf3c3fbe2ff9c979ce998475e506e8ce82dd5b0f350dc10e93bf2eeecf874b24770c5081dbea7447fddafa277b22de47d6ffea449674a4f9fccf84d15069089380284dbdd35f46cdff12a1bd78e4ef0065d016df")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("4.0.0.0")] [assembly: TypeForwardedTo(typeof(Queue<>))] [assembly: TypeForwardedTo(typeof(Stack<>))] [assembly: TypeForwardedTo(typeof(FileSystemName))] [assembly: TypeForwardedTo(typeof(CryptographicOperations))] [module: UnverifiableCode] internal static class Interop { internal static class Crypt32 { internal struct CRYPT_OID_INFO { public int cbSize; public IntPtr pszOID; public IntPtr pwszName; public OidGroup dwGroupId; public int AlgId; public int cbData; public IntPtr pbData; public string OID => Marshal.PtrToStringAnsi(pszOID); public string Name => Marshal.PtrToStringUni(pwszName); } internal enum CryptOidInfoKeyType { CRYPT_OID_INFO_OID_KEY = 1, CRYPT_OID_INFO_NAME_KEY, CRYPT_OID_INFO_ALGID_KEY, CRYPT_OID_INFO_SIGN_KEY, CRYPT_OID_INFO_CNG_ALGID_KEY, CRYPT_OID_INFO_CNG_SIGN_KEY } internal static class AuthType { internal const uint AUTHTYPE_CLIENT = 1u; internal const uint AUTHTYPE_SERVER = 2u; } internal static class CertChainPolicyIgnoreFlags { internal const uint CERT_CHAIN_POLICY_IGNORE_NOT_TIME_VALID_FLAG = 1u; internal const uint CERT_CHAIN_POLICY_IGNORE_CTL_NOT_TIME_VALID_FLAG = 2u; internal const uint CERT_CHAIN_POLICY_IGNORE_NOT_TIME_NESTED_FLAG = 4u; internal const uint CERT_CHAIN_POLICY_IGNORE_INVALID_BASIC_CONSTRAINTS_FLAG = 8u; internal const uint CERT_CHAIN_POLICY_ALLOW_UNKNOWN_CA_FLAG = 16u; internal const uint CERT_CHAIN_POLICY_IGNORE_WRONG_USAGE_FLAG = 32u; internal const uint CERT_CHAIN_POLICY_IGNORE_INVALID_NAME_FLAG = 64u; internal const uint CERT_CHAIN_POLICY_IGNORE_INVALID_POLICY_FLAG = 128u; internal const uint CERT_CHAIN_POLICY_IGNORE_END_REV_UNKNOWN_FLAG = 256u; internal const uint CERT_CHAIN_POLICY_IGNORE_CTL_SIGNER_REV_UNKNOWN_FLAG = 512u; internal const uint CERT_CHAIN_POLICY_IGNORE_CA_REV_UNKNOWN_FLAG = 1024u; internal const uint CERT_CHAIN_POLICY_IGNORE_ROOT_REV_UNKNOWN_FLAG = 2048u; internal const uint CERT_CHAIN_POLICY_IGNORE_ALL = 4095u; } internal static class CertChainPolicy { internal const int CERT_CHAIN_POLICY_BASE = 1; internal const int CERT_CHAIN_POLICY_AUTHENTICODE = 2; internal const int CERT_CHAIN_POLICY_AUTHENTICODE_TS = 3; internal const int CERT_CHAIN_POLICY_SSL = 4; internal const int CERT_CHAIN_POLICY_BASIC_CONSTRAINTS = 5; internal const int CERT_CHAIN_POLICY_NT_AUTH = 6; internal const int CERT_CHAIN_POLICY_MICROSOFT_ROOT = 7; internal const int CERT_CHAIN_POLICY_EV = 8; } internal static class CertChainPolicyErrors { internal const uint TRUST_E_CERT_SIGNATURE = 2148098052u; internal const uint CRYPT_E_REVOKED = 2148081680u; internal const uint CERT_E_UNTRUSTEDROOT = 2148204809u; internal const uint CERT_E_UNTRUSTEDTESTROOT = 2148204813u; internal const uint CERT_E_CHAINING = 2148204810u; internal const uint CERT_E_WRONG_USAGE = 2148204816u; internal const uint CERT_E_EXPIRE = 2148204801u; internal const uint CERT_E_INVALID_NAME = 2148204820u; internal const uint CERT_E_INVALID_POLICY = 2148204819u; internal const uint TRUST_E_BASIC_CONSTRAINTS = 2148098073u; internal const uint CERT_E_CRITICAL = 2148204805u; internal const uint CERT_E_VALIDITYPERIODNESTING = 2148204802u; internal const uint CRYPT_E_NO_REVOCATION_CHECK = 2148081682u; internal const uint CRYPT_E_REVOCATION_OFFLINE = 2148081683u; internal const uint CERT_E_PURPOSE = 2148204806u; internal const uint CERT_E_REVOKED = 2148204812u; internal const uint CERT_E_REVOCATION_FAILURE = 2148204814u; internal const uint CERT_E_CN_NO_MATCH = 2148204815u; internal const uint CERT_E_ROLE = 2148204803u; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct CERT_CONTEXT { internal uint dwCertEncodingType; internal IntPtr pbCertEncoded; internal uint cbCertEncoded; internal IntPtr pCertInfo; internal IntPtr hCertStore; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct SSL_EXTRA_CERT_CHAIN_POLICY_PARA { internal uint cbSize; internal uint dwAuthType; internal uint fdwChecks; internal unsafe char* pwszServerName; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct CERT_CHAIN_POLICY_PARA { public uint cbSize; public uint dwFlags; public unsafe SSL_EXTRA_CERT_CHAIN_POLICY_PARA* pvExtraPolicyPara; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct CERT_CHAIN_POLICY_STATUS { public uint cbSize; public uint dwError; public int lChainIndex; public int lElementIndex; public unsafe void* pvExtraPolicyStatus; } internal static CRYPT_OID_INFO FindOidInfo(CryptOidInfoKeyType keyType, string key, OidGroup group, bool fallBackToAllGroups) { IntPtr intPtr = IntPtr.Zero; try { intPtr = keyType switch { CryptOidInfoKeyType.CRYPT_OID_INFO_OID_KEY => Marshal.StringToCoTaskMemAnsi(key), CryptOidInfoKeyType.CRYPT_OID_INFO_NAME_KEY => Marshal.StringToCoTaskMemUni(key), _ => throw new NotSupportedException(), }; if (!OidGroupWillNotUseActiveDirectory(group)) { OidGroup group2 = group | (OidGroup)(-2147483648); IntPtr intPtr2 = CryptFindOIDInfo(keyType, intPtr, group2); if (intPtr2 != IntPtr.Zero) { return Marshal.PtrToStructure<CRYPT_OID_INFO>(intPtr2); } } IntPtr intPtr3 = CryptFindOIDInfo(keyType, intPtr, group); if (intPtr3 != IntPtr.Zero) { return Marshal.PtrToStructure<CRYPT_OID_INFO>(intPtr3); } if (fallBackToAllGroups && group != 0) { IntPtr intPtr4 = CryptFindOIDInfo(keyType, intPtr, OidGroup.All); if (intPtr4 != IntPtr.Zero) { return Marshal.PtrToStructure<CRYPT_OID_INFO>(intPtr4); } } CRYPT_OID_INFO result = default(CRYPT_OID_INFO); result.AlgId = -1; return result; } finally { if (intPtr != IntPtr.Zero) { Marshal.FreeCoTaskMem(intPtr); } } } private static bool OidGroupWillNotUseActiveDirectory(OidGroup group) { if (group != OidGroup.HashAlgorithm && group != OidGroup.EncryptionAlgorithm && group != OidGroup.PublicKeyAlgorithm && group != OidGroup.SignatureAlgorithm && group != OidGroup.Attribute && group != OidGroup.ExtensionOrAttribute) { return group == OidGroup.KeyDerivationFunction; } return true; } [DllImport("crypt32.dll", CharSet = CharSet.Unicode)] private static extern IntPtr CryptFindOIDInfo(CryptOidInfoKeyType dwKeyType, IntPtr pvKey, OidGroup group); [DllImport("crypt32.dll", CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CertFreeCertificateContext(IntPtr pCertContext); [DllImport("crypt32.dll", CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CertVerifyCertificateChainPolicy(IntPtr pszPolicyOID, SafeX509ChainHandle pChainContext, [In] ref CERT_CHAIN_POLICY_PARA pPolicyPara, [In][Out] ref CERT_CHAIN_POLICY_STATUS pPolicyStatus); } internal enum BOOL { FALSE, TRUE } internal static class Libraries { internal const string Advapi32 = "advapi32.dll"; internal const string BCrypt = "BCrypt.dll"; internal const string CoreComm_L1_1_1 = "api-ms-win-core-comm-l1-1-1.dll"; internal const string Crypt32 = "crypt32.dll"; internal const string Error_L1 = "api-ms-win-core-winrt-error-l1-1-0.dll"; internal const string HttpApi = "httpapi.dll"; internal const string IpHlpApi = "iphlpapi.dll"; internal const string Kernel32 = "kernel32.dll"; internal const string Memory_L1_3 = "api-ms-win-core-memory-l1-1-3.dll"; internal const string Mswsock = "mswsock.dll"; internal const string NCrypt = "ncrypt.dll"; internal const string NtDll = "ntdll.dll"; internal const string Odbc32 = "odbc32.dll"; internal const string OleAut32 = "oleaut32.dll"; internal const string PerfCounter = "perfcounter.dll"; internal const string RoBuffer = "api-ms-win-core-winrt-robuffer-l1-1-0.dll"; internal const string Secur32 = "secur32.dll"; internal const string Shell32 = "shell32.dll"; internal const string SspiCli = "sspicli.dll"; internal const string User32 = "user32.dll"; internal const string Version = "version.dll"; internal const string WebSocket = "websocket.dll"; internal const string WinHttp = "winhttp.dll"; internal const string Ws2_32 = "ws2_32.dll"; internal const string Wtsapi32 = "wtsapi32.dll"; internal const string CompressionNative = "clrcompression.dll"; } internal enum SECURITY_STATUS { OK = 0, ContinueNeeded = 590610, CompleteNeeded = 590611, CompAndContinue = 590612, ContextExpired = 590615, CredentialsNeeded = 590624, Renegotiate = 590625, OutOfMemory = -2146893056, InvalidHandle = -2146893055, Unsupported = -2146893054, TargetUnknown = -2146893053, InternalError = -2146893052, PackageNotFound = -2146893051, NotOwner = -2146893050, CannotInstall = -2146893049, InvalidToken = -2146893048, CannotPack = -2146893047, QopNotSupported = -2146893046, NoImpersonation = -2146893045, LogonDenied = -2146893044, UnknownCredentials = -2146893043, NoCredentials = -2146893042, MessageAltered = -2146893041, OutOfSequence = -2146893040, NoAuthenticatingAuthority = -2146893039, IncompleteMessage = -2146893032, IncompleteCredentials = -2146893024, BufferNotEnough = -2146893023, WrongPrincipal = -2146893022, TimeSkew = -2146893020, UntrustedRoot = -2146893019, IllegalMessage = -2146893018, CertUnknown = -2146893017, CertExpired = -2146893016, AlgorithmMismatch = -2146893007, SecurityQosFailed = -2146893006, SmartcardLogonRequired = -2146892994, UnsupportedPreauth = -2146892989, BadBinding = -2146892986, DowngradeDetected = -2146892976, ApplicationProtocolMismatch = -2146892953 } internal enum ApplicationProtocolNegotiationStatus { None, Success, SelectedClientOnly } internal enum ApplicationProtocolNegotiationExt { None, NPN, ALPN } [StructLayout(LayoutKind.Sequential)] internal class SecPkgContext_ApplicationProtocol { private const int MaxProtocolIdSize = 255; public ApplicationProtocolNegotiationStatus ProtoNegoStatus; public ApplicationProtocolNegotiationExt ProtoNegoExt; public byte ProtocolIdSize; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 255)] public byte[] ProtocolId; public byte[] Protocol => new Span<byte>(ProtocolId, 0, (int)ProtocolIdSize).ToArray(); } internal class Kernel32 { internal class IOReparseOptions { internal const uint IO_REPARSE_TAG_FILE_PLACEHOLDER = 2147483669u; internal const uint IO_REPARSE_TAG_MOUNT_POINT = 2684354563u; } internal class FileOperations { internal const int OPEN_EXISTING = 3; internal const int COPY_FILE_FAIL_IF_EXISTS = 1; internal const int FILE_ACTION_ADDED = 1; internal const int FILE_ACTION_REMOVED = 2; internal const int FILE_ACTION_MODIFIED = 3; internal const int FILE_ACTION_RENAMED_OLD_NAME = 4; internal const int FILE_ACTION_RENAMED_NEW_NAME = 5; internal const int FILE_FLAG_BACKUP_SEMANTICS = 33554432; internal const int FILE_FLAG_FIRST_PIPE_INSTANCE = 524288; internal const int FILE_FLAG_OVERLAPPED = 1073741824; internal const int FILE_LIST_DIRECTORY = 1; } internal struct SECURITY_ATTRIBUTES { internal uint nLength; internal IntPtr lpSecurityDescriptor; internal BOOL bInheritHandle; } internal const uint SEM_FAILCRITICALERRORS = 1u; [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CloseHandle(IntPtr handle); [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "CreateFileW", ExactSpelling = true, SetLastError = true)] private unsafe static extern IntPtr CreateFilePrivate(string lpFileName, int dwDesiredAccess, FileShare dwShareMode, SECURITY_ATTRIBUTES* securityAttrs, FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile); internal unsafe static SafeFileHandle CreateFile(string lpFileName, int dwDesiredAccess, FileShare dwShareMode, ref SECURITY_ATTRIBUTES securityAttrs, FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile) { lpFileName = System.IO.PathInternal.EnsureExtendedPrefixIfNeeded(lpFileName); fixed (SECURITY_ATTRIBUTES* securityAttrs2 = &securityAttrs) { IntPtr intPtr = CreateFilePrivate(lpFileName, dwDesiredAccess, dwShareMode, securityAttrs2, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); try { return new SafeFileHandle(intPtr, ownsHandle: true); } catch { CloseHandle(intPtr); throw; } } } internal static SafeFileHandle CreateFile(string lpFileName, int dwDesiredAccess, FileShare dwShareMode, FileMode dwCreationDisposition, int dwFlagsAndAttributes) { IntPtr intPtr = CreateFile_IntPtr(lpFileName, dwDesiredAccess, dwShareMode, dwCreationDisposition, dwFlagsAndAttributes); try { return new SafeFileHandle(intPtr, ownsHandle: true); } catch { CloseHandle(intPtr); throw; } } internal unsafe static IntPtr CreateFile_IntPtr(string lpFileName, int dwDesiredAccess, FileShare dwShareMode, FileMode dwCreationDisposition, int dwFlagsAndAttributes) { lpFileName = System.IO.PathInternal.EnsureExtendedPrefixIfNeeded(lpFileName); return CreateFilePrivate(lpFileName, dwDesiredAccess, dwShareMode, null, dwCreationDisposition, dwFlagsAndAttributes, IntPtr.Zero); } [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] internal unsafe static extern bool ReadDirectoryChangesW(SafeFileHandle hDirectory, byte[] lpBuffer, uint nBufferLength, [MarshalAs(UnmanagedType.Bool)] bool bWatchSubtree, int dwNotifyFilter, out int lpBytesReturned, NativeOverlapped* lpOverlapped, IntPtr lpCompletionRoutine); } internal static class SspiCli { [StructLayout(LayoutKind.Sequential, Pack = 1)] internal struct CredHandle { private IntPtr dwLower; private IntPtr dwUpper; public bool IsZero { get { if (dwLower == IntPtr.Zero) { return dwUpper == IntPtr.Zero; } return false; } } internal void SetToInvalid() { dwLower = IntPtr.Zero; dwUpper = IntPtr.Zero; } public override string ToString() { return dwLower.ToString("x") + ":" + dwUpper.ToString("x"); } } internal enum ContextAttribute { SECPKG_ATTR_SIZES = 0, SECPKG_ATTR_NAMES = 1, SECPKG_ATTR_LIFESPAN = 2, SECPKG_ATTR_DCE_INFO = 3, SECPKG_ATTR_STREAM_SIZES = 4, SECPKG_ATTR_AUTHORITY = 6, SECPKG_ATTR_PACKAGE_INFO = 10, SECPKG_ATTR_NEGOTIATION_INFO = 12, SECPKG_ATTR_UNIQUE_BINDINGS = 25, SECPKG_ATTR_ENDPOINT_BINDINGS = 26, SECPKG_ATTR_CLIENT_SPECIFIED_TARGET = 27, SECPKG_ATTR_APPLICATION_PROTOCOL = 35, SECPKG_ATTR_REMOTE_CERT_CONTEXT = 83, SECPKG_ATTR_LOCAL_CERT_CONTEXT = 84, SECPKG_ATTR_ROOT_STORE = 85, SECPKG_ATTR_ISSUER_LIST_EX = 89, SECPKG_ATTR_CONNECTION_INFO = 90, SECPKG_ATTR_UI_INFO = 104 } [Flags] internal enum ContextFlags { Zero = 0, Delegate = 1, MutualAuth = 2, ReplayDetect = 4, SequenceDetect = 8, Confidentiality = 0x10, UseSessionKey = 0x20, AllocateMemory = 0x100, Connection = 0x800, InitExtendedError = 0x4000, AcceptExtendedError = 0x8000, InitStream = 0x8000, AcceptStream = 0x10000, InitIntegrity = 0x10000, AcceptIntegrity = 0x20000, InitManualCredValidation = 0x80000, InitUseSuppliedCreds = 0x80, InitIdentify = 0x20000, AcceptIdentify = 0x80000, ProxyBindings = 0x4000000, AllowMissingBindings = 0x10000000, UnverifiedTargetName = 0x20000000 } internal enum Endianness { SECURITY_NETWORK_DREP = 0, SECURITY_NATIVE_DREP = 0x10 } internal enum CredentialUse { SECPKG_CRED_INBOUND = 1, SECPKG_CRED_OUTBOUND, SECPKG_CRED_BOTH } internal struct CERT_CHAIN_ELEMENT { public uint cbSize; public IntPtr pCertContext; } internal struct SecPkgContext_IssuerListInfoEx { public SafeHandle aIssuers; public uint cIssuers; public unsafe SecPkgContext_IssuerListInfoEx(SafeHandle handle, byte[] nativeBuffer) { aIssuers = handle; fixed (byte* ptr = nativeBuffer) { cIssuers = *(uint*)(ptr + IntPtr.Size); } } } internal struct SCHANNEL_CRED { [Flags] public enum Flags { Zero = 0, SCH_CRED_NO_SYSTEM_MAPPER = 2, SCH_CRED_NO_SERVERNAME_CHECK = 4, SCH_CRED_MANUAL_CRED_VALIDATION = 8, SCH_CRED_NO_DEFAULT_CREDS = 0x10, SCH_CRED_AUTO_CRED_VALIDATION = 0x20, SCH_SEND_AUX_RECORD = 0x200000, SCH_USE_STRONG_CRYPTO = 0x400000 } public const int CurrentVersion = 4; public int dwVersion; public int cCreds; public IntPtr paCred; public IntPtr hRootStore; public int cMappers; public IntPtr aphMappers; public int cSupportedAlgs; public IntPtr palgSupportedAlgs; public int grbitEnabledProtocols; public int dwMinimumCipherStrength; public int dwMaximumCipherStrength; public int dwSessionLifespan; public Flags dwFlags; public int reserved; } internal struct SecBuffer { public int cbBuffer; public SecurityBufferType BufferType; public IntPtr pvBuffer; public unsafe static readonly int Size = sizeof(SecBuffer); } internal struct SecBufferDesc { public readonly int ulVersion; public readonly int cBuffers; public unsafe void* pBuffers; public unsafe SecBufferDesc(int count) { ulVersion = 0; cBuffers = count; pBuffers = null; } } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct SEC_WINNT_AUTH_IDENTITY_W { internal string User; internal int UserLength; internal string Domain; internal int DomainLength; internal string Password; internal int PasswordLength; internal int Flags; } internal const uint SECQOP_WRAP_NO_ENCRYPT = 2147483649u; internal const int SEC_I_RENEGOTIATE = 590625; internal const int SECPKG_NEGOTIATION_COMPLETE = 0; internal const int SECPKG_NEGOTIATION_OPTIMISTIC = 1; [DllImport("sspicli.dll", ExactSpelling = true, SetLastError = true)] internal static extern int EncryptMessage(ref CredHandle contextHandle, [In] uint qualityOfProtection, [In][Out] ref SecBufferDesc inputOutput, [In] uint sequenceNumber); [DllImport("sspicli.dll", ExactSpelling = true, SetLastError = true)] internal unsafe static extern int DecryptMessage([In] ref CredHandle contextHandle, [In][Out] ref SecBufferDesc inputOutput, [In] uint sequenceNumber, uint* qualityOfProtection); [DllImport("sspicli.dll", ExactSpelling = true, SetLastError = true)] internal static extern int QuerySecurityContextToken(ref CredHandle phContext, out SecurityContextTokenHandle handle); [DllImport("sspicli.dll", ExactSpelling = true, SetLastError = true)] internal static extern int FreeContextBuffer([In] IntPtr contextBuffer); [DllImport("sspicli.dll", ExactSpelling = true, SetLastError = true)] internal static extern int FreeCredentialsHandle(ref CredHandle handlePtr); [DllImport("sspicli.dll", ExactSpelling = true, SetLastError = true)] internal static extern int DeleteSecurityContext(ref CredHandle handlePtr); [DllImport("sspicli.dll", ExactSpelling = true, SetLastError = true)] internal unsafe static extern int AcceptSecurityContext(ref CredHandle credentialHandle, [In] void* inContextPtr, [In] SecBufferDesc* inputBuffer, [In] ContextFlags inFlags, [In] Endianness endianness, ref CredHandle outContextPtr, [In][Out] ref SecBufferDesc outputBuffer, [In][Out] ref ContextFlags attributes, out long timeStamp); [DllImport("sspicli.dll", ExactSpelling = true, SetLastError = true)] internal unsafe static extern int QueryContextAttributesW(ref CredHandle contextHandle, [In] ContextAttribute attribute, [In] void* buffer); [DllImport("sspicli.dll", ExactSpelling = true, SetLastError = true)] internal static extern int SetContextAttributesW(ref CredHandle contextHandle, [In] ContextAttribute attribute, [In] byte[] buffer, [In] int bufferSize); [DllImport("sspicli.dll", ExactSpelling = true, SetLastError = true)] internal static extern int EnumerateSecurityPackagesW(out int pkgnum, out SafeFreeContextBuffer_SECURITY handle); [DllImport("sspicli.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] internal unsafe static extern int AcquireCredentialsHandleW([In] string principal, [In] string moduleName, [In] int usage, [In] void* logonID, [In] ref SEC_WINNT_AUTH_IDENTITY_W authdata, [In] void* keyCallback, [In] void* keyArgument, ref CredHandle handlePtr, out long timeStamp); [DllImport("sspicli.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] internal unsafe static extern int AcquireCredentialsHandleW([In] string principal, [In] string moduleName, [In] int usage, [In] void* logonID, [In] IntPtr zero, [In] void* keyCallback, [In] void* keyArgument, ref CredHandle handlePtr, out long timeStamp); [DllImport("sspicli.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] internal unsafe static extern int AcquireCredentialsHandleW([In] string principal, [In] string moduleName, [In] int usage, [In] void* logonID, [In] SafeSspiAuthDataHandle authdata, [In] void* keyCallback, [In] void* keyArgument, ref CredHandle handlePtr, out long timeStamp); [DllImport("sspicli.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] internal unsafe static extern int AcquireCredentialsHandleW([In] string principal, [In] string moduleName, [In] int usage, [In] void* logonID, [In] ref SCHANNEL_CRED authData, [In] void* keyCallback, [In] void* keyArgument, ref CredHandle handlePtr, out long timeStamp); [DllImport("sspicli.dll", ExactSpelling = true, SetLastError = true)] internal unsafe static extern int InitializeSecurityContextW(ref CredHandle credentialHandle, [In] void* inContextPtr, [In] byte* targetName, [In] ContextFlags inFlags, [In] int reservedI, [In] Endianness endianness, [In] SecBufferDesc* inputBuffer, [In] int reservedII, ref CredHandle outContextPtr, [In][Out] ref SecBufferDesc outputBuffer, [In][Out] ref ContextFlags attributes, out long timeStamp); [DllImport("sspicli.dll", ExactSpelling = true, SetLastError = true)] internal unsafe static extern int CompleteAuthToken([In] void* inContextPtr, [In][Out] ref SecBufferDesc inputBuffers); [DllImport("sspicli.dll", ExactSpelling = true, SetLastError = true)] internal unsafe static extern int ApplyControlToken([In] void* inContextPtr, [In][Out] ref SecBufferDesc inputBuffers); [DllImport("sspicli.dll", ExactSpelling = true, SetLastError = true)] internal static extern SECURITY_STATUS SspiFreeAuthIdentity([In] IntPtr authData); [DllImport("sspicli.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] internal static extern SECURITY_STATUS SspiEncodeStringsAsAuthIdentity([In] string userName, [In] string domainName, [In] string password, out SafeSspiAuthDataHandle authData); } } namespace Mono { internal class CFType { [DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation", EntryPoint = "CFGetTypeID")] public static extern IntPtr GetTypeID(IntPtr typeRef); } internal class CFObject : IDisposable, INativeObject { public const string CoreFoundationLibrary = "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation"; private const string SystemLibrary = "/usr/lib/libSystem.dylib"; public IntPtr Handle { get; private set; } [DllImport("/usr/lib/libSystem.dylib")] public static extern IntPtr dlopen(string path, int mode); [DllImport("/usr/lib/libSystem.dylib")] private static extern IntPtr dlsym(IntPtr handle, string symbol); [DllImport("/usr/lib/libSystem.dylib")] public static extern void dlclose(IntPtr handle); public static IntPtr GetIndirect(IntPtr handle, string symbol) { return dlsym(handle, symbol); } public static CFString GetStringConstant(IntPtr handle, string symbol) { IntPtr intPtr = dlsym(handle, symbol); if (intPtr == IntPtr.Zero) { return null; } IntPtr intPtr2 = Marshal.ReadIntPtr(intPtr); if (intPtr2 == IntPtr.Zero) { return null; } return new CFString(intPtr2, own: false); } public static IntPtr GetIntPtr(IntPtr handle, string symbol) { IntPtr intPtr = dlsym(handle, symbol); if (intPtr == IntPtr.Zero) { return IntPtr.Zero; } return Marshal.ReadIntPtr(intPtr); } public static IntPtr GetCFObjectHandle(IntPtr handle, string symbol) { IntPtr intPtr = dlsym(handle, symbol); if (intPtr == IntPtr.Zero) { return IntPtr.Zero; } return Marshal.ReadIntPtr(intPtr); } public CFObject(IntPtr handle, bool own) { Handle = handle; if (!own) { Retain(); } } ~CFObject() { Dispose(disposing: false); } [DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")] internal static extern IntPtr CFRetain(IntPtr handle); private void Retain() { CFRetain(Handle); } [DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")] internal static extern void CFRelease(IntPtr handle); private void Release() { CFRelease(Handle); } protected virtual void Dispose(bool disposing) { if (Handle != IntPtr.Zero) { Release(); Handle = IntPtr.Zero; } } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } } internal class CFArray : CFObject { private static readonly IntPtr kCFTypeArrayCallbacks; public int Count => (int)CFArrayGetCount(base.Handle); public IntPtr this[int index] => CFArrayGetValueAtIndex(base.Handle, (IntPtr)index); public CFArray(IntPtr handle, bool own) : base(handle, own) { } [DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")] private static extern IntPtr CFArrayCreate(IntPtr allocator, IntPtr values, IntPtr numValues, IntPtr callbacks); static CFArray() { IntPtr intPtr = CFObject.dlopen("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation", 0); if (intPtr == IntPtr.Zero) { return; } try { kCFTypeArrayCallbacks = CFObject.GetIndirect(intPtr, "kCFTypeArrayCallBacks"); } finally { CFObject.dlclose(intPtr); } } public static CFArray FromNativeObjects(params INativeObject[] values) { return new CFArray(Create(values), own: true); } public unsafe static IntPtr Create(params IntPtr[] values) { if (values == null) { throw new ArgumentNullException("values"); } fixed (IntPtr* ptr = values) { return CFArrayCreate(IntPtr.Zero, (IntPtr)ptr, (IntPtr)values.Length, kCFTypeArrayCallbacks); } } internal unsafe static CFArray CreateArray(params IntPtr[] values) { if (values == null) { throw new ArgumentNullException("values"); } fixed (IntPtr* ptr = values) { return new CFArray(CFArrayCreate(IntPtr.Zero, (IntPtr)ptr, (IntPtr)values.Length, kCFTypeArrayCallbacks), own: false); } } public static CFArray CreateArray(params INativeObject[] values) { return new CFArray(Create(values), own: true); } public static IntPtr Create(params INativeObject[] values) { if (values == null) { throw new ArgumentNullException("values"); } IntPtr[] array = new IntPtr[values.Length]; for (int i = 0; i < array.Length; i++) { array[i] = values[i].Handle; } return Create(array); } [DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")] private static extern IntPtr CFArrayGetCount(IntPtr handle); [DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")] private static extern IntPtr CFArrayGetValueAtIndex(IntPtr handle, IntPtr index); public static T[] ArrayFromHandle<T>(IntPtr handle, Func<IntPtr, T> creation) where T : class, INativeObject { if (handle == IntPtr.Zero) { return null; } IntPtr intPtr = CFArrayGetCount(handle); T[] array = new T[(int)intPtr]; for (uint num = 0u; num < (uint)(int)intPtr; num++) { array[num] = creation(CFArrayGetValueAtIndex(handle, (IntPtr)num)); } return array; } } internal class CFNumber : CFObject { public CFNumber(IntPtr handle, bool own) : base(handle, own) { } [DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")] [return: MarshalAs(UnmanagedType.I1)] private static extern bool CFNumberGetValue(IntPtr handle, IntPtr type, [MarshalAs(UnmanagedType.I1)] out bool value); public static bool AsBool(IntPtr handle) { if (handle == IntPtr.Zero) { return false; } CFNumberGetValue(handle, (IntPtr)1, out bool value); return value; } public static implicit operator bool(CFNumber number) { return AsBool(number.Handle); } [DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")] [return: MarshalAs(UnmanagedType.I1)] private static extern bool CFNumberGetValue(IntPtr handle, IntPtr type, out int value); public static int AsInt32(IntPtr handle) { if (handle == IntPtr.Zero) { return 0; } CFNumberGetValue(handle, (IntPtr)9, out int value); return value; } [DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")] private static extern IntPtr CFNumberCreate(IntPtr allocator, IntPtr theType, IntPtr valuePtr); public static CFNumber FromInt32(int number) { return new CFNumber(CFNumberCreate(IntPtr.Zero, (IntPtr)9, (IntPtr)number), own: true); } public static implicit operator int(CFNumber number) { return AsInt32(number.Handle); } } internal struct CFRange { public IntPtr Location; public IntPtr Length; public CFRange(int loc, int len) { Location = (IntPtr)loc; Length = (IntPtr)len; } } internal class CFString : CFObject { private string str; public int Length { get { if (str != null) { return str.Length; } return (int)CFStringGetLength(base.Handle); } } public CFString(IntPtr handle, bool own) : base(handle, own) { } [DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")] private static extern IntPtr CFStringCreateWithCharacters(IntPtr alloc, IntPtr chars, IntPtr length); public unsafe static CFString Create(string value) { IntPtr intPtr; fixed (char* ptr = value) { intPtr = CFStringCreateWithCharacters(IntPtr.Zero, (IntPtr)ptr, (IntPtr)value.Length); } if (intPtr == IntPtr.Zero) { return null; } return new CFString(intPtr, own: true); } [DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")] private static extern IntPtr CFStringGetLength(IntPtr handle); [DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")] private static extern int CFStringCompare(IntPtr theString1, IntPtr theString2, int compareOptions); public static int Compare(IntPtr string1, IntPtr string2, int compareOptions = 0) { return CFStringCompare(string1, string2, compareOptions); } [DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")] private static extern IntPtr CFStringGetCharactersPtr(IntPtr handle); [DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")] private static extern IntPtr CFStringGetCharacters(IntPtr handle, CFRange range, IntPtr buffer); public unsafe static string AsString(IntPtr handle) { if (handle == IntPtr.Zero) { return null; } int num = (int)CFStringGetLength(handle); if (num == 0) { return string.Empty; } IntPtr intPtr = CFStringGetCharactersPtr(handle); IntPtr intPtr2 = IntPtr.Zero; if (intPtr == IntPtr.Zero) { CFRange range = new CFRange(0, num); intPtr2 = Marshal.AllocHGlobal(num * 2); CFStringGetCharacters(handle, range, intPtr2); intPtr = intPtr2; } string result = new string((char*)(void*)intPtr, 0, num); if (intPtr2 != IntPtr.Zero) { Marshal.FreeHGlobal(intPtr2); } return result; } public override string ToString() { if (str == null) { str = AsString(base.Handle); } return str; } public static implicit operator string(CFString str) { return str.ToString(); } public static implicit operator CFString(string str) { return Create(str); } } internal class CFData : CFObject { public IntPtr Length => CFDataGetLength(base.Handle); public IntPtr Bytes => CFDataGetBytePtr(base.Handle); public byte this[long idx] { get { if (idx < 0 || (ulong)idx > (ulong)(long)Length) { throw new ArgumentException("idx"); } return Marshal.ReadByte(new IntPtr(Bytes.ToInt64() + idx)); } set { throw new NotImplementedException("NSData arrays can not be modified, use an NSMutableData instead"); } } public CFData(IntPtr handle, bool own) : base(handle, own) { } [DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")] private static extern IntPtr CFDataCreate(IntPtr allocator, IntPtr bytes, IntPtr length); public unsafe static CFData FromData(byte[] buffer) { fixed (byte* ptr = buffer) { return FromData((IntPtr)ptr, (IntPtr)buffer.Length); } } public static CFData FromData(IntPtr buffer, IntPtr length) { return new CFData(CFDataCreate(IntPtr.Zero, buffer, length), own: true); } [DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")] internal static extern IntPtr CFDataGetLength(IntPtr theData); [DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")] internal static extern IntPtr CFDataGetBytePtr(IntPtr theData); } internal class CFDictionary : CFObject { private static readonly IntPtr KeyCallbacks; private static readonly IntPtr ValueCallbacks; public IntPtr this[IntPtr key] => GetValue(key); static CFDictionary() { IntPtr intPtr = CFObject.dlopen("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation", 0); if (intPtr == IntPtr.Zero) { return; } try { KeyCallbacks = CFObject.GetIndirect(intPtr, "kCFTypeDictionaryKeyCallBacks"); ValueCallbacks = CFObject.GetIndirect(intPtr, "kCFTypeDictionaryValueCallBacks"); } finally { CFObject.dlclose(intPtr); } } public CFDictionary(IntPtr handle, bool own) : base(handle, own) { } public static CFDictionary FromObjectAndKey(IntPtr obj, IntPtr key) { return new CFDictionary(CFDictionaryCreate(IntPtr.Zero, new IntPtr[1] { key }, new IntPtr[1] { obj }, (IntPtr)1, KeyCallbacks, ValueCallbacks), own: true); } public static CFDictionary FromKeysAndObjects(IList<Tuple<IntPtr, IntPtr>> items) { IntPtr[] array = new IntPtr[items.Count]; IntPtr[] array2 = new IntPtr[items.Count]; for (int i = 0; i < items.Count; i++) { array[i] = items[i].Item1; array2[i] = items[i].Item2; } return new CFDictionary(CFDictionaryCreate(IntPtr.Zero, array, array2, (IntPtr)items.Count, KeyCallbacks, ValueCallbacks), own: true); } [DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")] private static extern IntPtr CFDictionaryCreate(IntPtr allocator, IntPtr[] keys, IntPtr[] vals, IntPtr len, IntPtr keyCallbacks, IntPtr valCallbacks); [DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")] private static extern IntPtr CFDictionaryGetValue(IntPtr handle, IntPtr key); [DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")] private static extern IntPtr CFDictionaryCreateCopy(IntPtr allocator, IntPtr handle); public CFDictionary Copy() { return new CFDictionary(CFDictionaryCreateCopy(IntPtr.Zero, base.Handle), own: true); } public CFMutableDictionary MutableCopy() { return new CFMutableDictionary(CFDictionaryCreateMutableCopy(IntPtr.Zero, IntPtr.Zero, base.Handle), own: true); } [DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")] private static extern IntPtr CFDictionaryCreateMutableCopy(IntPtr allocator, IntPtr capacity, IntPtr theDict); public IntPtr GetValue(IntPtr key) { return CFDictionaryGetValue(base.Handle, key); } } internal class CFMutableDictionary : CFDictionary { public CFMutableDictionary(IntPtr handle, bool own) : base(handle, own) { } public void SetValue(IntPtr key, IntPtr val) { CFDictionarySetValue(base.Handle, key, val); } public static CFMutableDictionary Create() { IntPtr intPtr = CFDictionaryCreateMutable(IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); if (intPtr == IntPtr.Zero) { throw new InvalidOperationException(); } return new CFMutableDictionary(intPtr, own: true); } [DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")] private static extern void CFDictionarySetValue(IntPtr handle, IntPtr key, IntPtr val); [DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")] private static extern IntPtr CFDictionaryCreateMutable(IntPtr allocator, IntPtr capacity, IntPtr keyCallback, IntPtr valueCallbacks); } internal class CFBoolean : INativeObject, IDisposable { private IntPtr handle; public static readonly CFBoolean True; public static readonly CFBoolean False; public IntPtr Handle => handle; public bool Value => CFBooleanGetValue(handle); static CFBoolean() { IntPtr intPtr = CFObject.dlopen("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation", 0); if (intPtr == IntPtr.Zero) { return; } try { True = new CFBoolean(CFObject.GetCFObjectHandle(intPtr, "kCFBooleanTrue"), owns: false); False = new CFBoolean(CFObject.GetCFObjectHandle(intPtr, "kCFBooleanFalse"), owns: false); } finally { CFObject.dlclose(intPtr); } } internal CFBoolean(IntPtr handle, bool owns) { this.handle = handle; if (!owns) { CFObject.CFRetain(handle); } } ~CFBoolean() { Dispose(disposing: false); } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (handle != IntPtr.Zero) { CFObject.CFRelease(handle); handle = IntPtr.Zero; } } public static implicit operator bool(CFBoolean value) { return value.Value; } public static explicit operator CFBoolean(bool value) { return FromBoolean(value); } public static CFBoolean FromBoolean(bool value) { if (!value) { return False; } return True; } [DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")] [return: MarshalAs(UnmanagedType.I1)] private static extern bool CFBooleanGetValue(IntPtr boolean); public static bool GetValue(IntPtr boolean) { return CFBooleanGetValue(boolean); } } internal class CFDate : INativeObject, IDisposable { private IntPtr handle; public IntPtr Handle => handle; internal CFDate(IntPtr handle, bool owns) { this.handle = handle; if (!owns) { CFObject.CFRetain(handle); } } ~CFDate() { Dispose(disposing: false); } [DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")] private static extern IntPtr CFDateCreate(IntPtr allocator, double at); public static CFDate Create(DateTime date) { DateTime dateTime = new DateTime(2001, 1, 1); double totalSeconds = (date - dateTime).TotalSeconds; IntPtr intPtr = CFDateCreate(IntPtr.Zero, totalSeconds); if (intPtr == IntPtr.Zero) { throw new NotSupportedException(); } return new CFDate(intPtr, owns: true); } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (handle != IntPtr.Zero) { CFObject.CFRelease(handle); handle = IntPtr.Zero; } } } internal class SystemCertificateProvider : ISystemCertificateProvider { private static MonoTlsProvider provider; private static int initialized; private static X509PalImpl x509pal; private static object syncRoot = new object(); public MonoTlsProvider Provider { get { EnsureInitialized(); return provider; } } public X509PalImpl X509Pal { get { EnsureInitialized(); return x509pal; } } private static X509PalImpl GetX509Pal() { MonoTlsProvider obj = provider; if (((obj != null) ? new Guid?(obj.ID) : null) == MonoTlsProviderFactory.BtlsId) { return new X509PalImplBtls(provider); } return new X509PalImplMono(); } private static void EnsureInitialized() { lock (syncRoot) { if (Interlocked.CompareExchange(ref initialized, 1, 0) == 0) { provider = MonoTlsProviderFactory.GetProvider(); x509pal = GetX509Pal(); } } } public X509CertificateImpl Import(byte[] data, CertificateImportFlags importFlags = 0) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) if (data == null || data.Length == 0) { return null; } X509CertificateImpl val = null; if ((importFlags & 1) == 0) { val = X509Pal.Import(data); if (val != null) { return val; } } if ((importFlags & 2) != 0) { return null; } return (X509CertificateImpl)(object)X509Pal.ImportFallback(data); } X509CertificateImpl ISystemCertificateProvider.Import(byte[] data, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags, CertificateImportFlags importFlags) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) return (X509CertificateImpl)(object)Import(data, password, keyStorageFlags, importFlags); } public X509Certificate2Impl Import(byte[] data, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags, CertificateImportFlags importFlags = 0) { //IL_000b: 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_0025: 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) if (data == null || data.Length == 0) { return null; } X509Certificate2Impl x509Certificate2Impl = null; if ((importFlags & 1) == 0) { x509Certificate2Impl = X509Pal.Import(data, password, keyStorageFlags); if (x509Certificate2Impl != null) { return x509Certificate2Impl; } } if ((importFlags & 2) != 0) { return null; } return X509Pal.ImportFallback(data, password, keyStorageFlags); } X509CertificateImpl ISystemCertificateProvider.Import(X509Certificate cert, CertificateImportFlags importFlags) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return (X509CertificateImpl)(object)Import(cert, importFlags); } public X509Certificate2Impl Import(X509Certificate cert, CertificateImportFlags importFlags = 0) { //IL_0025: 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_003c: 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) if (cert.Impl == null) { return null; } if (cert.Impl is X509Certificate2Impl x509Certificate2Impl) { return (X509Certificate2Impl)(object)((X509CertificateImpl)x509Certificate2Impl).Clone(); } if ((importFlags & 1) == 0) { X509Certificate2Impl x509Certificate2Impl2 = X509Pal.Import(cert); if (x509Certificate2Impl2 != null) { return x509Certificate2Impl2; } } if ((importFlags & 2) != 0) { return null; } return X509Pal.ImportFallback(cert.GetRawCertData()); } } internal class SystemDependencyProvider : ISystemDependencyProvider { private static SystemDependencyProvider instance; private static object syncRoot = new object(); public static SystemDependencyProvider Instance { get { Initialize(); return instance; } } ISystemCertificateProvider ISystemDependencyProvider.CertificateProvider => (ISystemCertificateProvider)(object)CertificateProvider; public SystemCertificateProvider CertificateProvider { get; } public X509PalImpl X509Pal => CertificateProvider.X509Pal; internal static void Initialize() { lock (syncRoot) { if (instance == null) { instance = new SystemDependencyProvider(); } } } private SystemDependencyProvider() { CertificateProvider = new SystemCertificateProvider(); DependencyInjector.Register((ISystemDependencyProvider)(object)this); } } internal static class X509Pal { public static X509PalImpl Instance => SystemDependencyProvider.Instance.X509Pal; } internal class X509PalImplMono : X509PalImpl { public override X509CertificateImpl Import(byte[] data) { return (X509CertificateImpl)(object)ImportFallback(data); } public override X509Certificate2Impl Import(byte[] data, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags) { return ImportFallback(data, password, keyStorageFlags); } public override X509Certificate2Impl Import(X509Certificate cert) { return null; } } internal abstract class X509PalImpl { private static byte[] signedData = new byte[9] { 42, 134, 72, 134, 247, 13, 1, 7, 2 }; public bool SupportsLegacyBasicConstraintsExtension => false; public abstract X509CertificateImpl Import(byte[] data); public abstract X509Certificate2Impl Import(byte[] data, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags); public abstract X509Certificate2Impl Import(X509Certificate cert); private static byte[] PEM(string type, byte[] data) { string @string = Encoding.ASCII.GetString(data); string text = $"-----BEGIN {type}-----"; string value = $"-----END {type}-----"; int num = @string.IndexOf(text) + text.Length; int num2 = @string.IndexOf(value, num); return Convert.FromBase64String(@string.Substring(num, num2 - num)); } protected static byte[] ConvertData(byte[] data) { if (data == null || data.Length == 0) { return data; } if (data[0] != 48) { try { return PEM("CERTIFICATE", data); } catch { } } return data; } internal X509Certificate2Impl ImportFallback(byte[] data) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Expected O, but got Unknown data = ConvertData(data); SafePasswordHandle val = new SafePasswordHandle((string)null); try { return new X509Certificate2ImplMono(data, val, X509KeyStorageFlags.DefaultKeySet); } finally { ((IDisposable)val)?.Dispose(); } } internal X509Certificate2Impl ImportFallback(byte[] data, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags) { return new X509Certificate2ImplMono(data, password, keyStorageFlags); } public X509ContentType GetCertContentType(byte[] rawData) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Expected O, but got Unknown //IL_00f2: Unknown result type (might be due to invalid IL or missing references) if (rawData == null || rawData.Length == 0) { throw new ArgumentException("rawData"); } if (rawData[0] == 48) { try { ASN1 val = new ASN1(rawData); if (val.Count == 3 && val[0].Tag == 48 && val[1].Tag == 48 && val[2].Tag == 3) { return X509ContentType.Cert; } if (val.Count == 3 && val[0].Tag == 2 && val[1].Tag == 48 && val[2].Tag == 48) { return X509ContentType.Pfx; } if (val.Count > 0 && val[0].Tag == 6 && val[0].CompareValue(signedData)) { return X509ContentType.Pkcs7; } return X509ContentType.Unknown; } catch (Exception) { return X509ContentType.Unknown; } } if (Encoding.ASCII.GetString(rawData).IndexOf("-----BEGIN CERTIFICATE-----") >= 0) { return X509ContentType.Cert; } try { new AuthenticodeDeformatter(rawData); return X509ContentType.Authenticode; } catch { return X509ContentType.Unknown; } } public X509ContentType GetCertContentType(string fileName) { if (fileName == null) { throw new ArgumentNullException("fileName"); } if (fileName.Length == 0) { throw new ArgumentException("fileName"); } byte[] rawData = File.ReadAllBytes(fileName); return GetCertContentType(rawData); } } } namespace Mono.Audio { internal abstract class AudioData { protected const int buffer_size = 4096; private bool stopped; public abstract int Channels { get; } public abstract int Rate { get; } public abstract AudioFormat Format { get; } public virtual bool IsStopped { get { return stopped; } set { stopped = value; } } public virtual void Setup(AudioDevice dev) { dev.SetFormat(Format, Channels, Rate); } public abstract void Play(AudioDevice dev); } internal class WavData : AudioData { private Stream stream; private short channels; private ushort frame_divider; private int sample_rate; private int data_len; private long data_offset; private AudioFormat format; public override int Channels => channels; public override int Rate => sample_rate; public override AudioFormat Format => format; public WavData(Stream data) { stream = data; byte[] array = new byte[44]; int num = stream.Read(array, 0, 12); if (num != 12 || array[0] != 82 || array[1] != 73 || array[2] != 70 || array[3] != 70 || array[8] != 87 || array[9] != 65 || array[10] != 86 || array[11] != 69) { throw new Exception("incorrect format" + num); } num = stream.Read(array, 0, 8); if (num == 8 && array[0] == 102 && array[1] == 109 && array[2] == 116 && array[3] == 32) { int num2 = array[4]; num2 |= array[5] << 8; num2 |= array[6] << 16; num2 |= array[7] << 24; num = stream.Read(array, 0, num2); if (num2 == num) { int num3 = 0; if ((array[num3++] | (array[num3++] << 8)) != 1) { throw new Exception("incorrect format (not PCM)"); } channels = (short)(array[num3++] | (array[num3++] << 8)); sample_rate = array[num3++]; sample_rate |= array[num3++] << 8; sample_rate |= array[num3++] << 16; sample_rate |= array[num3++] << 24; _ = array[num3++] | (array[num3++] << 8) | (array[num3++] << 16); _ = array[num3++]; num3 += 2; switch (array[num3++] | (array[num3++] << 8)) { case 8: frame_divider = 1; format = AudioFormat.U8; break; case 16: frame_divider = 2; format = AudioFormat.S16_LE; break; default: throw new Exception("bits per sample"); } num = stream.Read(array, 0, 8); if (num == 8) { if (array[0] == 102 && array[1] == 97 && array[2] == 99 && array[3] == 116) { int num4 = array[4]; num4 |= array[5] << 8; num4 |= array[6] << 16; num4 |= array[7] << 24; num = stream.Read(array, 0, num4); num = stream.Read(array, 0, 8); } if (array[0] != 100 || array[1] != 97 || array[2] != 116 || array[3] != 97) { throw new Exception("incorrect format (data/fact chunck)"); } int num5 = array[4]; num5 |= array[5] << 8; num5 |= array[6] << 16; num5 |= array[7] << 24; data_len = num5; data_offset = stream.Position; } return; } throw new Exception("Error: Can't Read " + num2 + " bytes from stream (" + num + " bytes read"); } throw new Exception("incorrect format (fmt)"); } public override void Play(AudioDevice dev) { int num = 0; int num2 = 0; int chunkSize = (int)dev.ChunkSize; int num3 = data_len; byte[] array = new byte[data_len]; byte[] array2 = new byte[chunkSize]; stream.Position = data_offset; stream.Read(array, 0, data_len); while (!IsStopped && num3 >= 0) { Buffer.BlockCopy(array, num2, array2, 0, chunkSize); num = dev.PlaySample(array2, chunkSize / (frame_divider * channels)); if (num > 0) { num2 += num * frame_divider * channels; num3 -= num * frame_divider * channels; } } } } internal class AuData : AudioData { private Stream stream; private short channels; private ushort frame_divider; private int sample_rate; private int data_len; private AudioFormat format; public override int Channels => channels; public override int Rate => sample_rate; public override AudioFormat Format => format; public AuData(Stream data) { stream = data; byte[] array = new byte[24]; int num = stream.Read(array, 0, 24); if (num != 24 || array[0] != 46 || array[1] != 115 || array[2] != 110 || array[3] != 100) { throw new Exception("incorrect format" + num); } int num2 = array[7]; num2 |= array[6] << 8; num2 |= array[5] << 16; num2 |= array[4] << 24; data_len = array[11]; data_len |= array[10] << 8; data_len |= array[9] << 16; data_len |= array[8] << 24; int num3 = array[15]; num3 |= array[14] << 8; num3 |= array[13] << 16; num3 |= array[12] << 24; sample_rate = array[19]; sample_rate |= array[18] << 8; sample_rate |= array[17] << 16; sample_rate |= array[16] << 24; int num4 = array[23]; num4 |= array[22] << 8; num4 |= array[21] << 16; num4 |= array[20] << 24; channels = (short)num4; if (num2 < 24 || (num4 != 1 && num4 != 2)) { throw new Exception("incorrect format offset" + num2); } if (num2 != 24) { for (int i = 24; i < num2; i++) { stream.ReadByte(); } } if (num3 == 1) { frame_divider = 1; format = AudioFormat.MU_LAW; if (data_len == -1) { data_len = (int)stream.Length - num2; } return; } throw new Exception("incorrect format encoding" + num3); } public override void Play(AudioDevice dev) { int num = 0; int num2 = 0; int chunkSize = (int)dev.ChunkSize; int num3 = data_len; byte[] array = new byte[data_len]; byte[] array2 = new byte[chunkSize]; stream.Position = 0L; stream.Read(array, 0, data_len); while (!IsStopped && num3 >= 0) { Buffer.BlockCopy(array, num2, array2, 0, chunkSize); num = dev.PlaySample(array2, chunkSize / (frame_divider * channels)); if (num > 0) { num2 += num * frame_divider * channels; num3 -= num * frame_divider * channels; } } } } internal enum AudioFormat { S8, U8, S16_LE, S16_BE, U16_LE, U16_BE, S24_LE, S24_BE, U24_LE, U24_BE, S32_LE, S32_BE, U32_LE, U32_BE, FLOAT_LE, FLOAT_BE, FLOAT64_LE, FLOAT64_BE, IEC958_SUBFRAME_LE, IEC958_SUBFRAME_BE, MU_LAW, A_LAW, IMA_ADPCM, MPEG, GSM } internal class AudioDevice { protected uint chunk_size; public uint ChunkSize => chunk_size; private static AudioDevice TryAlsa(string name) { try { return new AlsaDevice(name); } catch { return null; } } public static AudioDevice CreateDevice(string name) { AudioDevice audioDevice = TryAlsa(name); if (audioDevice == null) { audioDevice = new AudioDevice(); } return audioDevice; } public virtual bool SetFormat(AudioFormat format, int channels, int rate) { return true; } public virtual int PlaySample(byte[] buffer, int num_frames) { return num_frames; } public virtual int XRunRecovery(int err) { return err; } public virtual void Wait() { } } internal class AlsaDevice : AudioDevice, IDisposable { private IntPtr handle; private IntPtr hw_param; private IntPtr sw_param; [DllImport("libasound")] private static extern int snd_pcm_open(ref IntPtr handle, string pcm_name, int stream, int mode); [DllImport("libasound")] private static extern int snd_pcm_close(IntPtr handle); [DllImport("libasound")] private static extern int snd_pcm_drain(IntPtr handle); [DllImport("libasound")] private static extern int snd_pcm_writei(IntPtr handle, byte[] buf, int size); [DllImport("libasound")] private static extern int snd_pcm_set_params(IntPtr handle, int format, int access, int channels, int rate, int soft_resample, int latency); [DllImport("libasound")] private static extern int snd_pcm_state(IntPtr handle); [DllImport("libasound")] private static extern int snd_pcm_prepare(IntPtr handle); [DllImport("libasound")] private static extern int snd_pcm_hw_params(IntPtr handle, IntPtr param); [DllImport("libasound")] private static extern int snd_pcm_hw_params_malloc(ref IntPtr param); [DllImport("libasound")] private static extern void snd_pcm_hw_params_free(IntPtr param); [DllImport("libasound")] private static extern int snd_pcm_hw_params_any(IntPtr handle, IntPtr param); [DllImport("libasound")] private static extern int snd_pcm_hw_params_set_access(IntPtr handle, IntPtr param, int access); [DllImport("libasound")] private static extern int snd_pcm_hw_params_set_format(IntPtr handle, IntPtr param, int format); [DllImport("libasound")] private static extern int snd_pcm_hw_params_set_channels(IntPtr handle, IntPtr param, uint channel); [DllImport("libasound")] private static extern int snd_pcm_hw_params_set_rate_near(IntPtr handle, IntPtr param, ref uint rate, ref int dir); [DllImport("libasound")] private static extern int snd_pcm_hw_params_set_period_time_near(IntPtr handle, IntPtr param, ref uint period, ref int dir); [DllImport("libasound")] private static extern int snd_pcm_hw_params_get_period_size(IntPtr param, ref uint period, ref int dir); [DllImport("libasound")] private static extern int snd_pcm_hw_params_set_buffer_size_near(IntPtr handle, IntPtr param, ref uint buff_size); [DllImport("libasound")] private static extern int snd_pcm_hw_params_get_buffer_time_max(IntPtr param, ref uint buffer_time, ref int dir); [DllImport("libasound")] private static extern int snd_pcm_hw_params_set_buffer_time_near(IntPtr handle, IntPtr param, ref uint BufferTime, ref int dir); [DllImport("libasound")] private static extern int snd_pcm_hw_params_get_buffer_size(IntPtr param, ref uint BufferSize); [DllImport("libasound")] private static extern int snd_pcm_sw_params(IntPtr handle, IntPtr param); [DllImport("libasound")] private static extern int snd_pcm_sw_params_malloc(ref IntPtr param); [DllImport("libasound")] private static extern void snd_pcm_sw_params_free(IntPtr param); [DllImport("libasound")] private static extern int snd_pcm_sw_params_current(IntPtr handle, IntPtr param); [DllImport("libasound")] private static extern int snd_pcm_sw_params_set_avail_min(IntPtr handle, IntPtr param, uint frames); [DllImport("libasound")] private static extern int snd_pcm_sw_params_set_start_threshold(IntPtr handle, IntPtr param, uint StartThreshold); public AlsaDevice(string name) { if (name == null) { name = "default"; } int num = snd_pcm_open(ref handle, name, 0, 0); if (num < 0) { throw new Exception("no open " + num); } } ~AlsaDevice() { Dispose(disposing: false); } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (sw_param != IntPtr.Zero) { snd_pcm_sw_params_free(sw_param); } if (hw_param != IntPtr.Zero) { snd_pcm_hw_params_free(hw_param); } if (handle != IntPtr.Zero) { snd_pcm_close(handle); } sw_param = IntPtr.Zero; hw_param = IntPtr.Zero; handle = IntPtr.Zero; } public override bool SetFormat(AudioFormat format, int channels, int rate) { uint period = 0u; uint period2 = 0u; uint BufferSize = 0u; uint buffer_time = 0u; int num = 0; uint rate2 = (uint)rate; if (snd_pcm_hw_params_malloc(ref hw_param) == 0) { snd_pcm_hw_params_any(handle, hw_param); snd_pcm_hw_params_set_access(handle, hw_param, 3); snd_pcm_hw_params_set_format(handle, hw_param, (int)format); snd_pcm_hw_params_set_channels(handle, hw_param, (uint)channels); num = 0; snd_pcm_hw_params_set_rate_near(handle, hw_param, ref rate2, ref num); num = 0; snd_pcm_hw_params_get_buffer_time_max(hw_param, ref buffer_time, ref num); if (buffer_time > 500000) { buffer_time = 500000u; } if (buffer_time != 0) { period = buffer_time / 4; } num = 0; snd_pcm_hw_params_set_period_time_near(handle, hw_param, ref period, ref num); num = 0; snd_pcm_hw_params_set_buffer_time_near(handle, hw_param, ref buffer_time, ref num); snd_pcm_hw_params_get_period_size(hw_param, ref period2, ref num); chunk_size = period2; snd_pcm_hw_params_get_buffer_size(hw_param, ref BufferSize); snd_pcm_hw_params(handle, hw_param); } else { Console.WriteLine("failed to alloc Alsa hw param struct"); } int num2 = snd_pcm_sw_params_malloc(ref sw_param); if (num2 == 0) { snd_pcm_sw_params_current(handle, sw_param); snd_pcm_sw_params_set_avail_min(handle, sw_param, chunk_size); snd_pcm_sw_params_set_start_threshold(handle, sw_param, BufferSize); snd_pcm_sw_params(handle, sw_param); } else { Console.WriteLine("failed to alloc Alsa sw param struct"); } if (hw_param != IntPtr.Zero) { snd_pcm_hw_params_free(hw_param); hw_param = IntPtr.Zero; } if (sw_param != IntPtr.Zero) { snd_pcm_sw_params_free(sw_param); sw_param = IntPtr.Zero; } return num2 == 0; } public override int PlaySample(byte[] buffer, int num_frames) { int num; do { num = snd_pcm_writei(handle, buffer, num_frames); if (num < 0) { XRunRecovery(num); } } while (num < 0); return num; } public override int XRunRecovery(int err) { int result = 0; if (-32 == err) { result = snd_pcm_prepare(handle); } return result; } public override void Wait() { snd_pcm_drain(handle); } } internal class Win32SoundPlayer : IDisposable { private enum SoundFlags : uint { SND_SYNC = 0u, SND_ASYNC = 1u, SND_NODEFAULT = 2u, SND_MEMORY = 4u, SND_LOOP = 8u, SND_FILENAME = 0x20000u } private byte[] _buffer; private bool _disposed; public Stream Stream { set { Stop(); if (value != null) { _buffer = new byte[value.Length]; value.Read(_buffer, 0, _buffer.Length); } else { _buffer = new byte[0]; } } } public Win32SoundPlayer(Stream s) { if (s != null) { _buffer = new byte[s.Length]; s.Read(_buffer, 0, _buffer.Length); } else { _buffer = new byte[0]; } } [DllImport("winmm.dll", SetLastError = true)] private static extern bool PlaySound(byte[] ptrToSound, UIntPtr hmod, SoundFlags flags); public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } ~Win32SoundPlayer() { Dispose(disposing: false); } protected virtual void Dispose(bool disposing) { if (!_disposed) { Stop(); _disposed = true; } } public void Play() { PlaySound(_buffer, UIntPtr.Zero, (SoundFlags)5u); } public void PlayLooping() { PlaySound(_buffer, UIntPtr.Zero, (SoundFlags)13u); } public void PlaySync() { PlaySound(_buffer, UIntPtr.Zero, (SoundFlags)6u); } public void Stop() { PlaySound(null, UIntPtr.Zero, SoundFlags.SND_SYNC); } } } namespace Mono.Util { [Conditional("FULL_AOT_RUNTIME")] [Conditional("UNITY")] [AttributeUsage(AttributeTargets.Method)] [Conditional("MONOTOUCH")] internal sealed class MonoPInvokeCallbackAttribute : Attribute { public MonoPInvokeCallbackAttribute(Type t) { } } } namespace Mono.Unity { internal static class CertHelper { public unsafe static void AddCertificatesToNativeChain(UnityTls.unitytls_x509list* nativeCertificateChain, X509CertificateCollection certificates, UnityTls.unitytls_errorstate* errorState) { foreach (X509Certificate certificate in certificates) { AddCertificateToNativeChain(nativeCertificateChain, certificate, errorState); } } public unsafe static void AddCertificateToNativeChain(UnityTls.unitytls_x509list* nativeCertificateChain, X509Certificate certificate, UnityTls.unitytls_errorstate* errorState) { byte[] rawCertData = certificate.GetRawCertData(); fixed (byte* buffer = rawCertData) { UnityTls.NativeInterface.unitytls_x509list_append_der(nativeCertificateChain, buffer, (IntPtr)rawCertData.Length, errorState); } if (!(certificate.Impl is X509Certificate2Impl x509Certificate2Impl)) { return; } X509CertificateImplCollection intermediateCertificates = x509Certificate2Impl.IntermediateCertificates; if (intermediateCertificates != null && intermediateCertificates.Count > 0) { for (int i = 0; i < intermediateCertificates.Count; i++) { AddCertificateToNativeChain(nativeCertificateChain, new X509Certificate(intermediateCertificates[i]), errorState); } } } } internal static class Debug { public static void CheckAndThrow(UnityTls.unitytls_errorstate errorState, string context, AlertDescription defaultAlert = 80) { //IL_0020: 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 (errorState.code == UnityTls.unitytls_error_code.UNITYTLS_SUCCESS) { return; } string text = $"{context} - error code: {errorState.code}"; throw new TlsException(defaultAlert, text); } public static void CheckAndThrow(UnityTls.unitytls_errorstate errorState, UnityTls.unitytls_x509verify_result verifyResult, string context, AlertDescription defaultAlert = 80) { //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_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) if (verifyResult == UnityTls.unitytls_x509verify_result.UNITYTLS_X509VERIFY_SUCCESS) { CheckAndThrow(errorState, context, defaultAlert); return; } AlertDescription val = UnityTlsConversions.VerifyResultToAlertDescription(verifyResult, defaultAlert); string text = $"{context} - error code: {errorState.code}, verify result: {verifyResult}"; throw new TlsException(val, text); } } internal static class UnityTls { public enum unitytls_error_code : uint { UNITYTLS_SUCCESS = 0u, UNITYTLS_INVALID_ARGUMENT = 1u, UNITYTLS_INVALID_FORMAT = 2u, UNITYTLS_INVALID_PASSWORD = 3u, UNITYTLS_INVALID_STATE = 4u, UNITYTLS_BUFFER_OVERFLOW = 5u, UNITYTLS_OUT_OF_MEMORY = 6u, UNITYTLS_INTERNAL_ERROR = 7u, UNITYTLS_NOT_SUPPORTED = 8u, UNITYTLS_ENTROPY_SOURCE_FAILED = 9u, UNITYTLS_STREAM_CLOSED = 10u, UNITYTLS_USER_CUSTOM_ERROR_START = 1048576u, UNITYTLS_USER_WOULD_BLOCK = 1048577u, UNITYTLS_USER_READ_FAILED = 1048578u, UNITYTLS_USER_WRITE_FAILED = 1048579u, UNITYTLS_USER_UNKNOWN_ERROR = 1048580u, UNITYTLS_USER_CUSTOM_ERROR_END = 2097152u } public struct unitytls_errorstate { private uint magic; public unitytls_error_code code; private ulong reserved; } [StructLayout(LayoutKind.Sequential, Size = 1)] public struct unitytls_key { } public struct unitytls_key_ref { public ulong handle; } [StructLayout(LayoutKind.Sequential, Size = 1)] public struct unitytls_x509 { } public struct unitytls_x509_ref { public ulong handle; } [StructLayout(LayoutKind.Sequential, Size = 1)] public struct unitytls_x509list { } public struct unitytls_x509list_ref { public ulong handle; } [Flags] public enum unitytls_x509verify_result : uint { UNITYTLS_X509VERIFY_SUCCESS = 0u, UNITYTLS_X509VERIFY_NOT_DONE = 0x80000000u, UNITYTLS_X509VERIFY_FATAL_ERROR = uint.MaxValue, UNITYTLS_X509VERIFY_FLAG_EXPIRED = 1u, UNITYTLS_X509VERIFY_FLAG_REVOKED = 2u, UNITYTLS_X509VERIFY_FLAG_CN_MISMATCH = 4u, UNITYTLS_X509VERIFY_FLAG_NOT_TRUSTED = 8u, UNITYTLS_X509VERIFY_FLAG_USER_ERROR1 = 0x10000u, UNITYTLS_X509VERIFY_FLAG_USER_ERROR2 = 0x20000u, UNITYTLS_X509VERIFY_FLAG_USER_ERROR3 = 0x40000u, UNITYTLS_X509VERIFY_FLAG_USER_ERROR4 = 0x80000u, UNITYTLS_X509VERIFY_FLAG_USER_ERROR5 = 0x100000u, UNITYTLS_X509VERIFY_FLAG_USER_ERROR6 = 0x200000u, UNITYTLS_X509VERIFY_FLAG_USER_ERROR7 = 0x400000u, UNITYTLS_X509VERIFY_FLAG_USER_ERROR8 = 0x800000u, UNITYTLS_X509VERIFY_FLAG_UNKNOWN_ERROR = 0x8000000u } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate unitytls_x509verify_result unitytls_x509verify_callback(void* userData, unitytls_x509_ref cert, unitytls_x509verify_result result, unitytls_errorstate* errorState); [StructLayout(LayoutKind.Sequential, Size = 1)] public struct unitytls_tlsctx { } public struct unitytls_tlsctx_ref { public ulong handle; } [StructLayout(LayoutKind.Sequential, Size = 1)] public struct unitytls_x509name { } public enum unitytls_ciphersuite : uint { UNITYTLS_CIPHERSUITE_INVALID = 16777215u } public enum unitytls_protocol : uint { UNITYTLS_PROTOCOL_TLS_1_0, UNITYTLS_PROTOCOL_TLS_1_1, UNITYTLS_PROTOCOL_TLS_1_2, UNITYTLS_PROTOCOL_INVALID } public struct unitytls_tlsctx_protocolrange { public unitytls_protocol min; public unitytls_protocol max; } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate IntPtr unitytls_tlsctx_write_callback(void* userData, byte* data, IntPtr bufferLen, unitytls_errorstate* errorState); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate IntPtr unitytls_tlsctx_read_callback(void* userData, byte* buffer, IntPtr bufferLen, unitytls_errorstate* errorState); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate void unitytls_tlsctx_trace_callback(void* userData, unitytls_tlsctx* ctx, byte* traceMessage, IntPtr traceMessageLen); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate void unitytls_tlsctx_certificate_callback(void* userData, unitytls_tlsctx* ctx, byte* cn, IntPtr cnLen, unitytls_x509name* caList, IntPtr caListLen, unitytls_x509list_ref* chain, unitytls_key_ref* key, unitytls_errorstate* errorState); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate unitytls_x509verify_result unitytls_tlsctx_x509verify_callback(void* userData, unitytls_x509list_ref chain, unitytls_errorstate* errorState); public struct unitytls_tlsctx_callbacks { public unitytls_tlsctx_read_callback read; public unitytls_tlsctx_write_callback write; public unsafe void* data; } [StructLayout(LayoutKind.Sequential)] public class unitytls_interface_struct { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate unitytls_errorstate unitytls_errorstate_create_t(); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate void unitytls_errorstate_raise_error_t(unitytls_errorstate* errorState, unitytls_error_code errorCode); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate unitytls_key_ref unitytls_key_get_ref_t(unitytls_key* key, unitytls_errorstate* errorState); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate unitytls_key* unitytls_key_parse_der_t(byte* buffer, IntPtr bufferLen, byte* password, IntPtr passwordLen, unitytls_errorstate* errorState); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate unitytls_key* unitytls_key_parse_pem_t(byte* buffer, IntPtr bufferLen, byte* password, IntPtr passwordLen, unitytls_errorstate* errorState); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate void unitytls_key_free_t(unitytls_key* key); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate IntPtr unitytls_x509_export_der_t(unitytls_x509_ref cert, byte* buffer, IntPtr bufferLen, unitytls_errorstate* errorState); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate unitytls_x509list_ref unitytls_x509list_get_ref_t(unitytls_x509list* list, unitytls_errorstate* errorState); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate unitytls_x509_ref unitytls_x509list_get_x509_t(unitytls_x509list_ref list, IntPtr index, unitytls_errorstate* errorState); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate unitytls_x509list* unitytls_x509list_create_t(unitytls_errorstate* errorState); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate void unitytls_x509list_append_t(unitytls_x509list* list, unitytls_x509_ref cert, unitytls_errorstate* errorState); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate void unitytls_x509list_append_der_t(unitytls_x509list* list, byte* buffer, IntPtr bufferLen, unitytls_errorstate* errorState); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate void unitytls_x509list_append_pem_t(unitytls_x509list* list, byte* buffer, IntPtr bufferLen, unitytls_errorstate* errorState); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate void unitytls_x509list_free_t(unitytls_x509list* list); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate unitytls_x509verify_result unitytls_x509verify_default_ca_t(unitytls_x509list_ref chain, byte* cn, IntPtr cnLen, unitytls_x509verify_callback cb, void* userData, unitytls_errorstate* errorState); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate unitytls_x509verify_result unitytls_x509verify_explicit_ca_t(unitytls_x509list_ref chain, unitytls_x509list_ref trustCA, byte* cn, IntPtr cnLen, unitytls_x509verify_callback cb, void* userData, unitytls_errorstate* errorState); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate unitytls_tlsctx* unitytls_tlsctx_create_server_t(unitytls_tlsctx_protocolrange supportedProtocols, unitytls_tlsctx_callbacks callbacks, ulong certChain, ulong leafCertificateKey, unitytls_errorstate* errorState); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate unitytls_tlsctx* unitytls_tlsctx_create_client_t(unitytls_tlsctx_protocolrange supportedProtocols, unitytls_tlsctx_callbacks callbacks, byte* cn, IntPtr cnLen, unitytls_errorstate* errorState); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate void unitytls_tlsctx_server_require_client_authentication_t(unitytls_tlsctx* ctx, unitytls_x509list_ref clientAuthCAList, unitytls_errorstate* errorState); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate void unitytls_tlsctx_set_certificate_callback_t(unitytls_tlsctx* ctx, unitytls_tlsctx_certificate_callback cb, void* userData, unitytls_errorstate* errorState); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate void unitytls_tlsctx_set_trace_callback_t(unitytls_tlsctx* ctx, unitytls_tlsctx_trace_callback cb, void* userData, unitytls_errorstate* errorState); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate void unitytls_tlsctx_set_x509verify_callback_t(unitytls_tlsctx* ctx, unitytls_tlsctx_x509verify_callback cb, void* userData, unitytls_errorstate* errorState); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate void unitytls_tlsctx_set_supported_ciphersuites_t(unitytls_tlsctx* ctx, unitytls_ciphersuite* supportedCiphersuites, IntPtr supportedCiphersuitesLen, unitytls_errorstate* errorState); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate unitytls_ciphersuite unitytls_tlsctx_get_ciphersuite_t(unitytls_tlsctx* ctx, unitytls_errorstate* errorState); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate unitytls_protocol unitytls_tlsctx_get_protocol_t(unitytls_tlsctx* ctx, unitytls_errorstate* errorState); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate unitytls_x509verify_result unitytls_tlsctx_process_handshake_t(unitytls_tlsctx* ctx, unitytls_errorstate* errorState); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate IntPtr unitytls_tlsctx_read_t(unitytls_tlsctx* ctx, byte* buffer, IntPtr bufferLen, unitytls_errorstate* errorState); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate IntPtr unitytls_tlsctx_write_t(unitytls_tlsctx* ctx, byte* data, IntPtr bufferLen, unitytls_errorstate* errorState); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate void unitytls_tlsctx_notify_close_t(unitytls_tlsctx* ctx, unitytls_errorstate* errorState); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate void unitytls_tlsctx_free_t(unitytls_tlsctx* ctx); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public unsafe delegate void unitytls_random_generate_bytes_t(byte* buffer, IntPtr bufferLen, unitytls_errorstate* errorState); public readonly ulong UNITYTLS_INVALID_HANDLE; public readonly unitytls_tlsctx_protocolrange UNITYTLS_TLSCTX_PROTOCOLRANGE_DEFAULT; public unitytls_errorstate_create_t unitytls_errorstate_create; public unitytls_errorstate_raise_error_t unitytls_errorstate_raise_error; public unitytls_key_get_ref_t unitytls_key_get_ref; public unitytls_key_parse_der_t unitytls_key_parse_der; public unitytls_key_parse_pem_t unitytls_key_parse_pem; public unitytls_key_free_t unitytls_key_free; public unitytls_x509_export_der_t unitytls_x509_export_der; public unitytls_x509list_get_ref_t unitytls_x509list_get_ref; public unitytls_x509list_get_x509_t unitytls_x509list_get_x509; public unitytls_x509list_create_t unitytls_x509list_create; public unitytls_x509list_append_t unitytls_x509list_append; public unitytls_x509list_append_der_t unitytls_x509list_append_der; public unitytls_x509list_append_der_t unitytls_x509list_append_pem; public unitytls_x509list_free_t unitytls_x509list_free; public unitytls_x509verify_default_ca_t unitytls_x509verify_default_ca; public unitytls_x509verify_explicit_ca_t unitytls_x509verify_explicit_ca; public unitytls_tlsctx_create_server_t unitytls_tlsctx_create_server; public unitytls_tlsctx_create_client_t unitytls_tlsctx_create_client; public unitytls_tlsctx_server_require_client_authentication_t unitytls_tlsctx_server_require_client_authentication; public unitytls_tlsctx_set_certificate_callback_t unitytls_tlsctx_set_certificate_callback; public unitytls_tlsctx_set_trace_callback_t unitytls_tlsctx_set_trace_callback; public unitytls_tlsctx_set_x509verify_callback_t unitytls_tlsctx_set_x509verify_callback; public unitytls_tlsctx_set_supported_ciphersuites_t unitytls_tlsctx_set_supported_ciphersuites; public unitytls_tlsctx_get_ciphersuite_t unitytls_tlsctx_get_ciphersuite; public unitytls_tlsctx_get_protocol_t unitytls_tlsctx_get_protocol; public unitytls_tlsctx_process_handshake_t unitytls_tlsctx_process_handshake; public unitytls_tlsctx_read_t unitytls_tlsctx_read; public unitytls_tlsctx_write_t unitytls_tlsctx_write; public unitytls_tlsctx_notify_close_t unitytls_tlsctx_notify_close; public unitytls_tlsctx_free_t unitytls_tlsctx_free; public unitytls_random_generate_bytes_t unitytls_random_generate_bytes; } private static unitytls_interface_struct marshalledInterface; public static bool IsSupported => NativeInterface != null; public static unitytls_interface_struct NativeInterface { get { if (marshalledInterface == null) { IntPtr unityTlsInterface = GetUnityTlsInterface(); if (unityTlsInterface == IntPtr.Zero) { return null; } marshalledInterface = Marshal.PtrToStructure<unitytls_interface_struct>(unityTlsInterface); } return marshalledInterface; } } [MethodImpl(MethodImplOptions.InternalCall)] private static extern IntPtr GetUnityTlsInterface(); } internal class UnityTlsContext : MobileTlsContext { private const bool ActivateTracing = false; private unsafe UnityTls.unitytls_tlsctx* tlsContext = null; private unsafe UnityTls.unitytls_x509list* requestedClientCertChain = null; private unsafe UnityTls.unitytls_key* requestedClientKey = null; private UnityTls.unitytls_tlsctx_read_callback readCallback; private UnityTls.unitytls_tlsctx_write_callback writeCallback; private UnityTls.unitytls_tlsctx_trace_callback traceCallback; private UnityTls.unitytls_tlsctx_certificate_callback certificateCallback; private UnityTls.unitytls_tlsctx_x509verify_callback verifyCallback; private X509Certificate localClientCertificate; private X509Certificate2 remoteCertificate; private MonoTlsConnectionInfo connectioninfo; private bool isAuthenticated; private bool hasContext; private bool closedGraceful; private byte[] writeBuffer; private byte[] readBuffer; private GCHandle handle; private Exception lastException; public override bool HasContext => hasContext; public override bool IsAuthenticated => isAuthenticated; public override MonoTlsConnectionInfo ConnectionInfo => connectioninfo; internal override bool IsRemoteCertificateAvailable => remoteCertificate != null; internal override X509Certificate LocalClientCertificate => localClientCertificate; public override X509Certificate2 RemoteCertificate => remoteCertificate; public override TlsProtocols NegotiatedProtocol => ConnectionInfo.ProtocolVersion; public override bool CanRenegotiate => false; public unsafe UnityTlsContext(MobileAuthenticatedStream parent, MonoSslAuthenticationOptions options) : base(parent, options) { handle = GCHandle.Alloc(this); UnityTls.unitytls_errorstate errorState = UnityTls.NativeInterface.unitytls_errorstate_create(); UnityTls.unitytls_tlsctx_protocolrange supportedProtocols = new UnityTls.unitytls_tlsctx_protocolrange { min = UnityTlsConversions.GetMinProtocol(options.EnabledSslProtocols), max = UnityTlsConversions.GetMaxProtocol(options.EnabledSslProtocols) }; readCallback = ReadCallback; writeCallback = WriteCallback; UnityTls.unitytls_tlsctx_callbacks callbacks = new UnityTls.unitytls_tlsctx_callbacks { write = writeCallback, read = readCallback, data = (void*)(IntPtr)handle }; if (options.ServerMode) { ExtractNativeKeyAndChainFromManagedCertificate(options.ServerCertificate, &errorState, out var nativeCertChain, out var nativeKey); try { UnityTls.unitytls_x509list_ref unitytls_x509list_ref = UnityTls.NativeInterface.unitytls_x509list_get_ref(nativeCertChain, &errorState); UnityTls.unitytls_key_ref unitytls_key_ref = UnityTls.NativeInterface.unitytls_key_get_ref(nativeKey, &errorState); Mono.Unity.Debug.CheckAndThrow(errorState, "Failed to parse server key/certificate", (AlertDescription)80); tlsContext = UnityTls.NativeInterface.unitytls_tlsctx_create_server(supportedProtocols, callbacks, unitytls_x509list_ref.handle, unitytls_key_ref.handle, &errorState); if (base.AskForClientCertificate) { UnityTls.unitytls_x509list* list = null; try { list = UnityTls.NativeInterface.unitytls_x509list_create(&errorState); UnityTls.unitytls_x509list_ref clientAuthCAList = UnityTls.NativeInterface.unitytls_x509list_get_ref(list, &errorState); UnityTls.NativeInterface.unitytls_tlsctx_server_require_client_authentication(tlsContext, clientAuthCAList, &errorState); } finally { UnityTls.NativeInterface.unitytls_x509list_free(list); } } } finally { UnityTls.NativeInterface.unitytls_x509list_free(nativeCertChain); UnityTls.NativeInterface.unitytls_key_free(nativeKey); } } else { byte[] bytes = Encoding.UTF8.GetBytes(options.TargetHost); fixed (byte* cn = bytes) { tlsContext = UnityTls.NativeInterface.unitytls_tlsctx_create_client(supportedProtocols, callbacks, cn, (IntPtr)bytes.Length, &errorState); } certificateCallback = CertificateCallback; UnityTls.NativeInterface.unitytls_tlsctx_set_certificate_callback(tlsContext, certificateCallback, (void*)(IntPtr)handle, &errorState); } verifyCallback = VerifyCallback; UnityTls.NativeInterface.unitytls_tlsctx_set_x509verify_callback(tlsContext, verifyCallback, (void*)(IntPtr)handle, &errorState); Mono.Unity.Debug.CheckAndThrow(errorState, "Failed to create UnityTls context", (AlertDescription)80); hasContext = true; } private unsafe static void ExtractNativeKeyAndChainFromManagedCertificate(X509Certificate cert, UnityTls.unitytls_errorstate* errorState, out UnityTls.unitytls_x509list* nativeCertChain, out UnityTls.unitytls_key* nativeKey) { if (cert == null) { throw new ArgumentNullException("cert"); } if (!(cert is X509Certificate2 x509Certificate) || x509Certificate.PrivateKey == null) { throw new ArgumentException("Certificate does not have a private key", "cert"); } nativeCertChain = null; nativeKey = null; try { nativeCertChain = UnityTls.NativeInterface.unitytls_x509list_create(errorState); CertHelper.AddCertificateToNativeChain(nativeCertChain, cert, errorState); byte[] array = PrivateKeyInfo.Encode(x509Certificate.PrivateKey); fixed (byte* buffer = array) { nativeKey = UnityTls.NativeInterface.unitytls_key_parse_der(buffer, (IntPtr)array.Length, null, (IntPtr)0, errorState); } } catch { UnityTls.NativeInterface.unitytls_x509list_free(nativeCertChain); UnityTls.NativeInterface.unitytls_key_free(nativeKey); throw; } } public override void Flush() { } public unsafe override (int ret, bool wantMore) Read(byte[] buffer, int offset, int count) { int num = 0; lastException = null; UnityTls.unitytls_errorstate errorState = UnityTls.NativeInterface.unitytls_errorstate_create(); fixed (byte* ptr = buffer) { num = (int)UnityTls.NativeInterface.unitytls_tlsctx_read(tlsContext, ptr + offset, (IntPtr)count, &errorState); } if (lastException != null) { throw lastException; } switch (errorState.code) { case UnityTls.unitytls_error_code.UNITYTLS_SUCCESS: return (num, num < count); case UnityTls.unitytls_error_code.UNITYTLS_USER_WOULD_BLOCK: return (num, true); case UnityTls.unitytls_error_code.UNITYTLS_STREAM_CLOSED: return (0, false); default: if (!closedGraceful) { Mono.Unity.Debug.CheckAndThrow(errorState, "Failed to read data to TLS context", (AlertDescription)80); } return (0, false); } } public unsafe override (int ret, bool wantMore) Write(byte[] buffer, int offset, int count) { int num = 0; lastException = null; UnityTls.unitytls_errorstate errorState = UnityTls.NativeInterface.unitytls_errorstate_create(); fixed (byte* ptr = buffer) { num = (int)UnityTls.NativeInterface.unitytls_tlsctx_write(tlsContext, ptr + offset, (IntPtr)count, &errorState); } if (lastException != null) { throw lastException; } switch (errorState.code) { case UnityTls.unitytls_error_code.UNITYTLS_SUCCESS: return (num, num < count); case UnityTls.unitytls_error_code.UNITYTLS_USER_WOULD_BLOCK: return (num, true); case UnityTls.unitytls_error_code.UNITYTLS_STREAM_CLOSED: return (0, false); default: Mono.Unity.Debug.CheckAndThrow(errorState, "Failed to write data to TLS context", (AlertDescription)80); return (0, false); } } public override void Renegotiate() { throw new NotSupportedException(); } public override bool PendingRenegotiation() { return false; } public unsafe override void Shutdown() { if (base.Settings != null && base.Settings.SendCloseNotify) { UnityTls.unitytls_errorstate unitytls_errorstate = UnityTls.NativeInterface.unitytls_errorstate_create(); UnityTls.NativeInterface.unitytls_tlsctx_notify_close(tlsContext, &unitytls_errorstate); } UnityTls.NativeInterface.unitytls_x509list_free(requestedClientCertChain); UnityTls.NativeInterface.unitytls_key_free(requestedClientKey); UnityTls.NativeInterface.unitytls_tlsctx_free(tlsContext); tlsContext = null; hasContext = false; } protected override void Dispose(bool disposing) { try { if (disposing) { Shutdown(); localClientCertificate = null; remoteCertificate = null; if (localClientCertificate != null) { localClientCertificate.Dispose(); localClientCertificate = null; } if (remoteCertificate != null) { remoteCertificate.Dispose(); remoteCertificate = null; } connectioninfo = null; isAuthenticated = false; hasContext = false; } handle.Free(); } finally { base.Dispose(disposing); } } public unsafe override void StartHandshake() { if (base.Settings != null && base.Settings.EnabledCiphers != null) { UnityTls.unitytls_ciphersuite[] array = new UnityTls.unitytls_ciphersuite[base.Settings.EnabledCiphers.Length]; for (int i = 0; i < array.Length; i++) { array[i] = (UnityTls.unitytls_ciphersuite)base.Settings.EnabledCiphers[i]; } UnityTls.unitytls_errorstate errorState = UnityTls.NativeInterface.unitytls_errorstate_create(); fixed (UnityTls.unitytls_ciphersuite* supportedCiphersuites = array) { UnityTls.NativeInterface.unitytls_tlsctx_set_supported_ciphersuites(tlsContext, supportedCiphersuites, (IntPtr)array.Length, &errorState); } Mono.Unity.Debug.CheckAndThrow(errorState, "Failed to set list of supported ciphers", (AlertDescription)40); } } public unsafe override bool ProcessHandshake() { //IL_007c: Unknown result type (might be due to invalid IL or missing references) lastException = null; UnityTls.unitytls_errorstate errorState = UnityTls.NativeInterface.unitytls_errorstate_create(); UnityTls.unitytls_x509verify_result unitytls_x509verify_result = UnityTls.NativeInterface.unitytls_tlsctx_process_handshake(tlsContext, &errorState); if (errorState.code == UnityTls.unitytls_error_code.UNITYTLS_USER_WOULD_BLOCK) { return false; } if (lastException != null) { throw lastException; } if (base.IsServer && unitytls_x509verify_result == UnityTls.unitytls_x509verify_result.UNITYTLS_X509VERIFY_NOT_DONE) { Mono.Unity.Debug.CheckAndThrow(errorState, "Handshake failed", (AlertDescription)40); if (!ValidateCertificate(null, null)) { throw new TlsException((AlertDescription)40, "Verification failure during handshake"); } } else { Mono.Unity.Debug.CheckAndThrow(errorState, unitytls_x509verify_result, "Handshake failed", (AlertDescription)40); } return true; } public unsafe override void FinishHandshake() { //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_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Expected O, but got Unknown UnityTls.unitytls_errorstate unitytls_errorstate = UnityTls.NativeInterface.unitytls_errorstate_create(); UnityTls.unitytls_ciphersuite unitytls_ciphersuite = UnityTls.NativeInterface.unitytls_tlsctx_get_ciphersuite(tlsContext, &unitytls_errorstate); UnityTls.unitytls_protocol protocol = UnityTls.NativeInterface.unitytls_tlsctx_get_protocol(tlsContext, &unitytls_errorstate); connectioninfo = new MonoTlsConnectionInfo { CipherSuiteCode = (CipherSuiteCode)(ushort)unitytls_ciphersuite, ProtocolVersion = UnityTlsConversions.ConvertProtocolVersion(protocol), PeerDomainName = base.ServerName }; isAuthenticated = true; } [MonoPInvokeCallback(typeof(UnityTls.unitytls_tlsctx_write_callback))] private unsafe static IntPtr WriteCallback(void* userData, byte* data, IntPtr bufferLen, UnityTls.unitytls_errorstate* errorState) { return ((UnityTlsContext)((GCHandle)(IntPtr)userData).Target).WriteCallback(data, bufferLen, errorState); } private unsafe IntPtr WriteCallback(byte* data, IntPtr bufferLen, UnityTls.unitytls_errorstate* errorState) { try { if (writeBuffer == null || writeBuffer.Length < (int)bufferLen) { writeBuffer = new byte[(int)bufferLen]; } Marshal.Copy((IntPtr)data, writeBuffer, 0, (int)bufferLen); if (!base.Parent.InternalWrite(writeBuffer, 0, (int)bufferLen)) { UnityTls.NativeInterface.unitytls_errorstate_raise_error(errorState, UnityTls.unitytls_error_code.UNITYTLS_USER_WRITE_FAILED); return (IntPtr)0; } return bufferLen; } catch (Exception ex) { UnityTls.NativeInterface.unitytls_errorstate_raise_error(errorState, UnityTls.unitytls_error_code.UNITYTLS_USER_UNKNOWN_ERROR); if (lastException == null) { lastException = ex; } return (IntPtr)0; } } [MonoPInvokeCallback(typeof(UnityTls.unitytls_tlsctx_read_callback))] private unsafe static IntPtr ReadCallback(void* userData, byte* buffer, IntPtr bufferLen, UnityTls.unitytls_errorstate* errorState) { return ((UnityTlsContext)((GCHandle)(IntPtr)userData).Target).ReadCallback(buffer, bufferLen, errorState); } private unsafe IntPtr ReadCallback(byte* buffer, IntPtr bufferLen, UnityTls.unitytls_errorstate* errorState) { try { if (readBuffer == null || readBuffer.Length < (int)bufferLen) { readBuffer = new byte[(int)bufferLen]; } bool outWantMore; int num = base.Parent.InternalRead(readBuffer, 0, (int)bufferLen, out outWantMore); if (num < 0) { UnityTls.NativeInterface.unitytls_errorstate_raise_error(errorState, UnityTls.unitytls_error_code.UNITYTLS_USER_READ_FAILED); } else if (num > 0) { Marshal.Copy(readBuffer, 0, (IntPtr)buffer, (int)bufferLen); } else if (outWantMore) { UnityTls.NativeInterface.unitytls_errorstate_raise_error(errorState, UnityTls.unitytls_error_code.UNITYTLS_USER_WOULD_BLOCK); } else { closedGraceful = true; UnityTls.NativeInterface.unitytls_errorstate_raise_error(errorState, UnityTls.unitytls_error_code.UNITYTLS_USER_READ_FAILED); } return (IntPtr)num; } catch (Exception ex) { UnityTls.NativeInterface.unitytls_errorstate_raise_error(errorState, UnityTls.unitytls_error_code.UNITYTLS_USER_
BepInExPack\unstripped_corlib\UnityEngine.CoreModule.dll
Decompiled 2 months ago
The result has been truncated due to the large size, download it to view full contents!
#define UNITY_ASSERTIONS using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using JetBrains.Annotations; using Microsoft.CodeAnalysis; using Microsoft.Win32.SafeHandles; using Unity.Baselib.LowLevel; using Unity.Burst; using Unity.Burst.LowLevel; using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; using Unity.Content; using Unity.IL2CPP.CompilerServices; using Unity.Jobs; using Unity.Jobs.LowLevel.Unsafe; using Unity.Profiling; using Unity.Profiling.LowLevel; using Unity.Profiling.LowLevel.Unsafe; using UnityEngine; using UnityEngine.Assertions; using UnityEngine.Assertions.Comparers; using UnityEngine.Bindings; using UnityEngine.Diagnostics; using UnityEngine.Events; using UnityEngine.Experimental.Rendering; using UnityEngine.Internal; using UnityEngine.Networking.PlayerConnection; using UnityEngine.Playables; using UnityEngine.Profiling; using UnityEngine.Rendering; using UnityEngine.Rendering.RendererUtils; using UnityEngine.SceneManagement; using UnityEngine.Scripting; using UnityEngine.Scripting.APIUpdating; using UnityEngine.Serialization; using UnityEngineInternal; [assembly: InternalsVisibleTo("UnityEngine.ClothModule")] [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: InternalsVisibleTo("UnityEngine")] [assembly: InternalsVisibleTo("UnityEngine.SharedInternalsModule")] [assembly: InternalsVisibleTo("UnityEngine.CoreModule")] [assembly: InternalsVisibleTo("UnityEngine.AIModule")] [assembly: InternalsVisibleTo("UnityEngine.JSONSerializeModule")] [assembly: InternalsVisibleTo("UnityEngine.NVIDIAModule")] [assembly: InternalsVisibleTo("UnityEngine.InputModule")] [assembly: InternalsVisibleTo("UnityEngine.ARModule")] [assembly: InternalsVisibleTo("UnityEngine.AccessibilityModule")] [assembly: InternalsVisibleTo("UnityEngine.AndroidJNIModule")] [assembly: InternalsVisibleTo("UnityEngine.AnimationModule")] [assembly: InternalsVisibleTo("UnityEngine.HotReloadModule")] [assembly: InternalsVisibleTo("UnityEngine.PhysicsModule")] [assembly: InternalsVisibleTo("UnityEngine.ClusterInputModule")] [assembly: InternalsVisibleTo("UnityEngine.IMGUIModule")] [assembly: InternalsVisibleTo("UnityEngine.AssetBundleModule")] [assembly: InternalsVisibleTo("UnityEngine.ClusterRendererModule")] [assembly: InternalsVisibleTo("UnityEngine.TLSModule")] [assembly: InternalsVisibleTo("UnityEngine.UnityConnectModule")] [assembly: InternalsVisibleTo("UnityEngine.UnityAnalyticsCommonModule")] [assembly: InternalsVisibleTo("UnityEngine.UnityWebRequestModule")] [assembly: InternalsVisibleTo("UnityEngine.UnityAnalyticsModule")] [assembly: InternalsVisibleTo("UnityEngine.CrashReportingModule")] [assembly: InternalsVisibleTo("UnityEngine.DSPGraphModule")] [assembly: InternalsVisibleTo("UnityEngine.DirectorModule")] [assembly: InternalsVisibleTo("UnityEngine.GIModule")] [assembly: InternalsVisibleTo("UnityEngine.ImageConversionModule")] [assembly: InternalsVisibleTo("UnityEngine.GameCenterModule")] [assembly: InternalsVisibleTo("UnityEngine.GridModule")] [assembly: InternalsVisibleTo("UnityEngine.TextRenderingModule")] [assembly: InternalsVisibleTo("UnityEngine.InputLegacyModule")] [assembly: InternalsVisibleTo("UnityEngine.TextCoreFontEngineModule")] [assembly: InternalsVisibleTo("UnityEngine.TextCoreTextEngineModule")] [assembly: InternalsVisibleTo("UnityEngine.ContentLoadModule")] [assembly: InternalsVisibleTo("UnityEngine.AudioModule")] [assembly: InternalsVisibleTo("UnityEngine.LocalizationModule")] [assembly: InternalsVisibleTo("Unity.Analytics")] [assembly: InternalsVisibleTo("UnityEngine.UnityTestProtocolModule")] [assembly: InternalsVisibleTo("UnityEngine.StreamingModule")] [assembly: InternalsVisibleTo("UnityEngine.Physics2DModule")] [assembly: InternalsVisibleTo("UnityEngine.ProfilerModule")] [assembly: InternalsVisibleTo("UnityEngine.PropertiesModule")] [assembly: InternalsVisibleTo("UnityEngine.RuntimeInitializeOnLoadManagerInitializerModule")] [assembly: InternalsVisibleTo("UnityEngine.ScreenCaptureModule")] [assembly: InternalsVisibleTo("UnityEngine.SpriteMaskModule")] [assembly: InternalsVisibleTo("UnityEngine.UnityCurlModule")] [assembly: InternalsVisibleTo("UnityEngine.SpriteShapeModule")] [assembly: InternalsVisibleTo("UnityEngine.SubstanceModule")] [assembly: InternalsVisibleTo("UnityEngine.SubsystemsModule")] [assembly: InternalsVisibleTo("UnityEngine.TerrainModule")] [assembly: InternalsVisibleTo("UnityEngine.TerrainPhysicsModule")] [assembly: InternalsVisibleTo("UnityEngine.TilemapModule")] [assembly: InternalsVisibleTo("UnityEngine.UIModule")] [assembly: InternalsVisibleTo("UnityEngine.UIElementsModule")] [assembly: InternalsVisibleTo("UnityEngine.UnityWebRequestAudioModule")] [assembly: InternalsVisibleTo("UnityEngine.Cloud.Service")] [assembly: InternalsVisibleTo("UnityEngine.PerformanceReportingModule")] [assembly: InternalsVisibleTo("UnityEngine.Networking")] [assembly: InternalsVisibleTo("UnityEngine.ParticleSystemModule")] [assembly: InternalsVisibleTo("UnityEngine.UnityWebRequestAssetBundleModule")] [assembly: InternalsVisibleTo("UnityEngine.UnityWebRequestTextureModule")] [assembly: InternalsVisibleTo("UnityEngine.UnityWebRequestWWWModule")] [assembly: InternalsVisibleTo("UnityEngine.VFXModule")] [assembly: InternalsVisibleTo("UnityEngine.XRModule")] [assembly: InternalsVisibleTo("UnityEngine.VRModule")] [assembly: InternalsVisibleTo("UnityEngine.VehiclesModule")] [assembly: InternalsVisibleTo("UnityEngine.VideoModule")] [assembly: InternalsVisibleTo("UnityEngine.VirtualTexturingModule")] [assembly: InternalsVisibleTo("UnityEngine.WindModule")] [assembly: InternalsVisibleTo("UnityEngine.SwitchModule")] [assembly: InternalsVisibleTo("UnityEngine.XboxOneModule")] [assembly: InternalsVisibleTo("UnityEngine.PS4Module")] [assembly: InternalsVisibleTo("UnityEngine.PS4VRModule")] [assembly: InternalsVisibleTo("UnityEngine.PS5Module")] [assembly: InternalsVisibleTo("UnityEngine.PS5VRModule")] [assembly: InternalsVisibleTo("UnityEngine.Cloud")] [assembly: InternalsVisibleTo("UnityEngine.UnityAnalyticsCommon")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.014")] [assembly: InternalsVisibleTo("UnityEngine.UmbraModule")] [assembly: InternalsVisibleTo("Assembly-CSharp-testable")] [assembly: InternalsVisibleTo("UnityEngine.Advertisements")] [assembly: InternalsVisibleTo("UnityEngine.Purchasing")] [assembly: InternalsVisibleTo("UnityEngine.TestRunner")] [assembly: InternalsVisibleTo("Unity.Automation")] [assembly: InternalsVisibleTo("Unity.Burst")] [assembly: InternalsVisibleTo("Unity.Burst.Editor")] [assembly: InternalsVisibleTo("Unity.DeploymentTests.Services")] [assembly: InternalsVisibleTo("Unity.IntegrationTests")] [assembly: InternalsVisibleTo("Unity.IntegrationTests.UnityAnalytics")] [assembly: InternalsVisibleTo("Unity.IntegrationTests.Timeline")] [assembly: InternalsVisibleTo("Unity.IntegrationTests.Framework")] [assembly: InternalsVisibleTo("Unity.RuntimeTests")] [assembly: InternalsVisibleTo("Unity.RuntimeTests.Framework")] [assembly: InternalsVisibleTo("Unity.RuntimeTests.Framework.Tests")] [assembly: InternalsVisibleTo("Unity.PerformanceTests.RuntimeTestRunner.Tests")] [assembly: InternalsVisibleTo("Unity.RuntimeTests.AllIn1Runner")] [assembly: InternalsVisibleTo("Unity.Entities")] [assembly: InternalsVisibleTo("Unity.Timeline")] [assembly: InternalsVisibleTo("Assembly-CSharp-firstpass-testable")] [assembly: InternalsVisibleTo("Unity.Services.QoS")] [assembly: InternalsVisibleTo("UnityEngine.SpatialTracking")] [assembly: InternalsVisibleTo("Unity.WindowsMRAutomation")] [assembly: InternalsVisibleTo("Unity.RenderPipelines.Universal.2D.Internal")] [assembly: InternalsVisibleTo("Unity.2D.Sprite.Editor")] [assembly: InternalsVisibleTo("Unity.2D.Sprite.EditorTests")] [assembly: InternalsVisibleTo("Unity.UI.Builder.Editor")] [assembly: InternalsVisibleTo("UnityEditor.UIBuilderModule")] [assembly: InternalsVisibleTo("Unity.UI.Builder.EditorTests")] [assembly: InternalsVisibleTo("Unity.UIElements")] [assembly: InternalsVisibleTo("UnityEngine.UIElementsGameObjectsModule")] [assembly: InternalsVisibleTo("Unity.UIElements.Editor")] [assembly: InternalsVisibleTo("Unity.UIElements.PlayModeTests")] [assembly: InternalsVisibleTo("UnityEngine.UIElements.Tests")] [assembly: InternalsVisibleTo("Unity.UIElements.EditorTests")] [assembly: InternalsVisibleTo("UnityEngine.UI")] [assembly: InternalsVisibleTo("Unity.Networking.Transport")] [assembly: InternalsVisibleTo("Unity.ucg.QoS")] [assembly: InternalsVisibleTo("GoogleAR.UnityNative")] [assembly: InternalsVisibleTo("Unity.Logging")] [assembly: InternalsVisibleTo("UnityEngine.Analytics")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.015")] [assembly: InternalsVisibleTo("Unity.Runtime")] [assembly: InternalsVisibleTo("Unity.Core")] [assembly: InternalsVisibleTo("UnityEngine.Core.Runtime.Tests")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.001")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.002")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.003")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.004")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.005")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.006")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.007")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.008")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.009")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.010")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.011")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.012")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.013")] [assembly: InternalsVisibleTo("Unity.Collections")] [assembly: InternalsVisibleTo("Unity.Entities.Tests")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.016")] [assembly: InternalsVisibleTo("Unity.ObjectDispatcher.Tests")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.017")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.019")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.020")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.021")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.022")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.023")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.024")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridgeDev.001")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridgeDev.002")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridgeDev.003")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridgeDev.004")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridgeDev.005")] [assembly: InternalsVisibleTo("Unity.Subsystem.Registration")] [assembly: UnityEngineModuleAssembly] [assembly: InternalsVisibleTo("TestRuntime")] [assembly: InternalsVisibleTo("TestRuntime.FakingHDR")] [assembly: InternalsVisibleTo("Unity.RenderPipelines.GPUDriven.Runtime")] [assembly: InternalsVisibleTo("Unity.InternalAPIEngineBridge.018")] [assembly: InternalsVisibleTo("Unity.2D.Entities.Hybrid")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.0.0.0")] [module: UnverifiableCode] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] internal sealed class IsUnmanagedAttribute : Attribute { } } namespace AOT { [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public class MonoPInvokeCallbackAttribute : Attribute { public MonoPInvokeCallbackAttribute(Type type) { } } } namespace UnityEditor.Experimental { public class RenderSettings { [Obsolete("Use UnityEngine.Experimental.GlobalIllumination.useRadianceAmbientProbe instead. (UnityUpgradable) -> UnityEngine.Experimental.GlobalIllumination.RenderSettings.useRadianceAmbientProbe", true)] public static bool useRadianceAmbientProbe { get; set; } } } namespace UnityEngineInternal { public enum GITextureType { Charting, Albedo, Emissive, Irradiance, Directionality, Baked, BakedDirectional, InputWorkspace, BakedShadowMask, BakedAlbedo, BakedEmissive, BakedCharting, BakedTexelValidity, BakedUVOverlap, BakedLightmapCulling } [NativeHeader("Runtime/Export/GI/GIDebugVisualisation.bindings.h")] public static class GIDebugVisualisation { public static extern bool cycleMode { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] get; } public static extern bool pauseCycleMode { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] get; } public static extern GITextureType texType { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] get; [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] set; } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] public static extern void ResetRuntimeInputTextures(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] public static extern void PlayCycleMode(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] public static extern void PauseCycleMode(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] public static extern void StopCycleMode(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] public static extern void CycleSkipSystems(int skip); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] public static extern void CycleSkipInstances(int skip); } public enum MemorylessMode { Unused, Forced, Automatic } [NativeHeader("Runtime/Misc/PlayerSettings.h")] public class MemorylessManager { public static MemorylessMode depthMemorylessMode { get { return GetFramebufferDepthMemorylessMode(); } set { SetFramebufferDepthMemorylessMode(value); } } [MethodImpl(MethodImplOptions.InternalCall)] [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeMethod(Name = "GetFramebufferDepthMemorylessMode")] internal static extern MemorylessMode GetFramebufferDepthMemorylessMode(); [MethodImpl(MethodImplOptions.InternalCall)] [StaticAccessor(/*Could not decode attribute arguments.*/)] [NativeMethod(Name = "SetFramebufferDepthMemorylessMode")] internal static extern void SetFramebufferDepthMemorylessMode(MemorylessMode mode); } internal struct GraphicsDeviceDebugSettings { public float sleepAtStartOfGraphicsJobs; public float sleepBeforeTextureUpload; } [NativeHeader("Runtime/Export/Graphics/GraphicsDeviceDebug.bindings.h")] [StaticAccessor(/*Could not decode attribute arguments.*/)] internal static class GraphicsDeviceDebug { internal static GraphicsDeviceDebugSettings settings { get { get_settings_Injected(out var ret); return ret; } set { set_settings_Injected(ref value); } } [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void get_settings_Injected(out GraphicsDeviceDebugSettings ret); [MethodImpl(MethodImplOptions.InternalCall)] [SpecialName] private static extern void set_settings_Injected(ref GraphicsDeviceDebugSettings value); } internal enum LightmapType { NoLightmap = -1, StaticLightmap, DynamicLightmap } [StructLayout(LayoutKind.Sequential, Size = 1)] [Il2CppEagerStaticClassConstruction] public struct MathfInternal { public static volatile float FloatMinNormal = 1.1754944E-38f; public static volatile float FloatMinDenormal = float.Epsilon; public static bool IsFlushToZeroEnabled = FloatMinDenormal == 0f; } public sealed class APIUpdaterRuntimeServices { [Obsolete("Method is not meant to be used at runtime. Please, replace this call with GameObject.AddComponent<T>()/GameObject.AddComponent(Type).", true)] public static UnityEngine.Component AddComponent(GameObject go, string sourceInfo, string name) { throw new Exception(); } } public enum TypeInferenceRules { TypeReferencedByFirstArgument, TypeReferencedBySecondArgument, ArrayOfTypeReferencedByFirstArgument, TypeOfFirstArgument } [Serializable] [AttributeUsage(AttributeTargets.Method)] public class TypeInferenceRuleAttribute : Attribute { private readonly string _rule; public TypeInferenceRuleAttribute(TypeInferenceRules rule) : this(rule.ToString()) { } public TypeInferenceRuleAttribute(string rule) { _rule = rule; } public override string ToString() { return _rule; } } public class GenericStack : Stack { } } namespace Unity.Baselib { internal static class BaselibNativeLibrary { } internal struct ErrorState { private Binding.Baselib_ErrorState nativeErrorState; public Binding.Baselib_ErrorCode ErrorCode => nativeErrorState.code; public unsafe Binding.Baselib_ErrorState* NativeErrorStatePtr { get { fixed (Binding.Baselib_ErrorState* result = &nativeErrorState) { return result; } } } public void ThrowIfFailed() { if (ErrorCode != Binding.Baselib_ErrorCode.Success) { throw new BaselibException(this); } } public unsafe string Explain(Binding.Baselib_ErrorState_ExplainVerbosity verbosity = Binding.Baselib_ErrorState_ExplainVerbosity.ErrorType_SourceLocation_Explanation) { fixed (Binding.Baselib_ErrorState* errorState = &nativeErrorState) { uint num = Binding.Baselib_ErrorState_Explain(errorState, null, 0u, verbosity) + 1; IntPtr intPtr = Binding.Baselib_Memory_Allocate(new UIntPtr(num)); try { Binding.Baselib_ErrorState_Explain(errorState, (byte*)(void*)intPtr, num, verbosity); return Marshal.PtrToStringAnsi(intPtr); } finally { Binding.Baselib_Memory_Free(intPtr); } } } } internal class BaselibException : Exception { private readonly ErrorState errorState; public Binding.Baselib_ErrorCode ErrorCode => errorState.ErrorCode; internal BaselibException(ErrorState errorState) : base(errorState.Explain()) { this.errorState = errorState; } } } namespace Unity.Baselib.LowLevel { [NativeHeader("External/baselib/builds/CSharp/BindingsUnity/Baselib_ErrorState.gen.binding.h")] [NativeHeader("External/baselib/builds/CSharp/BindingsUnity/Baselib_NetworkAddress.gen.binding.h")] [NativeHeader("External/baselib/builds/CSharp/BindingsUnity/Baselib_ErrorCode.gen.binding.h")] [NativeHeader("External/baselib/builds/CSharp/BindingsUnity/Baselib_Thread.gen.binding.h")] [NativeHeader("External/baselib/builds/CSharp/BindingsUnity/Baselib_DynamicLibrary.gen.binding.h")] [NativeHeader("External/baselib/builds/CSharp/BindingsUnity/Baselib_RegisteredNetwork.gen.binding.h")] [NativeHeader("External/baselib/builds/CSharp/BindingsUnity/Baselib_Memory.gen.binding.h")] [NativeHeader("External/baselib/builds/CSharp/BindingsUnity/Baselib_Timer.gen.binding.h")] [NativeHeader("External/baselib/builds/CSharp/BindingsUnity/Baselib_FileIO.gen.binding.h")] [NativeHeader("External/baselib/builds/CSharp/BindingsUnity/Baselib_SourceLocation.gen.binding.h")] [NativeHeader("External/baselib/builds/CSharp/BindingsUnity/Baselib_Socket.gen.binding.h")] [NativeHeader("External/baselib/builds/CSharp/BindingsUnity/Baselib_ThreadLocalStorage.gen.binding.h")] internal static class Binding { public struct Baselib_DynamicLibrary_Handle { public IntPtr handle; } public enum Baselib_ErrorCode { Success = 0, OutOfMemory = 16777216, OutOfSystemResources = 16777217, InvalidAddressRange = 16777218, InvalidArgument = 16777219, InvalidBufferSize = 16777220, InvalidState = 16777221, NotSupported = 16777222, Timeout = 16777223, UnsupportedAlignment = 33554432, InvalidPageSize = 33554433, InvalidPageCount = 33554434, UnsupportedPageState = 33554435, ThreadCannotJoinSelf = 50331648, NetworkInitializationError = 67108864, AddressInUse = 67108865, AddressUnreachable = 67108866, AddressFamilyNotSupported = 67108867, Disconnected = 67108868, InvalidPathname = 83886080, RequestedAccessIsNotAllowed = 83886081, IOError = 83886082, FailedToOpenDynamicLibrary = 100663296, FunctionNotFound = 100663297, UnexpectedError = -1 } public enum Baselib_ErrorState_NativeErrorCodeType : byte { None, PlatformDefined } public enum Baselib_ErrorState_ExtraInformationType : byte { None, StaticString, GenerationCounter } public struct Baselib_ErrorState { public Baselib_SourceLocation sourceLocation; public ulong nativeErrorCode; public ulong extraInformation; public Baselib_ErrorCode code; public Baselib_ErrorState_NativeErrorCodeType nativeErrorCodeType; public Baselib_ErrorState_ExtraInformationType extraInformationType; } public enum Baselib_ErrorState_ExplainVerbosity { ErrorType, ErrorType_SourceLocation_Explanation } public struct Baselib_FileIO_EventQueue { public IntPtr handle; } public struct Baselib_FileIO_AsyncFile { public IntPtr handle; } public struct Baselib_FileIO_SyncFile { public IntPtr handle; } public enum Baselib_FileIO_OpenFlags : uint { Read = 1u, Write = 2u, OpenAlways = 4u, CreateAlways = 8u } public struct Baselib_FileIO_ReadRequest { public ulong offset; public IntPtr buffer; public ulong size; } public enum Baselib_FileIO_Priority { Normal, High } public enum Baselib_FileIO_EventQueue_ResultType { Baselib_FileIO_EventQueue_Callback = 1, Baselib_FileIO_EventQueue_OpenFile, Baselib_FileIO_EventQueue_ReadFile, Baselib_FileIO_EventQueue_CloseFile } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void EventQueueCallback(ulong arg0); public struct Baselib_FileIO_EventQueue_Result_Callback { public IntPtr callback; } public struct Baselib_FileIO_EventQueue_Result_OpenFile { public ulong fileSize; } public struct Baselib_FileIO_EventQueue_Result_ReadFile { public ulong bytesTransferred; } [StructLayout(LayoutKind.Explicit)] public struct Baselib_FileIO_EventQueue_Result { [FieldOffset(0)] public Baselib_FileIO_EventQueue_ResultType type; [FieldOffset(8)] public ulong userdata; [FieldOffset(16)] public Baselib_ErrorState errorState; [FieldOffset(64)] public Baselib_FileIO_EventQueue_Result_Callback callback; [FieldOffset(64)] [Ignore(DoesNotContributeToSize = true)] public Baselib_FileIO_EventQueue_Result_OpenFile openFile; [FieldOffset(64)] [Ignore(DoesNotContributeToSize = true)] public Baselib_FileIO_EventQueue_Result_ReadFile readFile; } public struct Baselib_Memory_PageSizeInfo { public ulong defaultPageSize; public ulong pageSizes0; public ulong pageSizes1; public ulong pageSizes2; public ulong pageSizes3; public ulong pageSizes4; public ulong pageSizes5; public ulong pageSizesLen; } public struct Baselib_Memory_PageAllocation { public IntPtr ptr; public ulong pageSize; public ulong pageCount; } public enum Baselib_Memory_PageState { Reserved = 0, NoAccess = 1, ReadOnly = 2, ReadWrite = 4, ReadOnly_Executable = 18, ReadWrite_Executable = 20 } public enum Baselib_NetworkAddress_Family { Invalid, IPv4, IPv6 } [StructLayout(LayoutKind.Explicit)] public struct Baselib_NetworkAddress { [FieldOffset(0)] public byte data0; [FieldOffset(1)] public byte data1; [FieldOffset(2)] public byte data2; [FieldOffset(3)] public byte data3; [FieldOffset(4)] public byte data4; [FieldOffset(5)] public byte data5; [FieldOffset(6)] public byte data6; [FieldOffset(7)] public byte data7; [FieldOffset(8)] public byte data8; [FieldOffset(9)] public byte data9; [FieldOffset(10)] public byte data10; [FieldOffset(11)] public byte data11; [FieldOffset(12)] public byte data12; [FieldOffset(13)] public byte data13; [FieldOffset(14)] public byte data14; [FieldOffset(15)] public byte data15; [FieldOffset(0)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_0; [FieldOffset(1)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_1; [FieldOffset(2)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_2; [FieldOffset(3)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_3; [FieldOffset(4)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_4; [FieldOffset(5)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_5; [FieldOffset(6)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_6; [FieldOffset(7)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_7; [FieldOffset(8)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_8; [FieldOffset(9)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_9; [FieldOffset(10)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_10; [FieldOffset(11)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_11; [FieldOffset(12)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_12; [FieldOffset(13)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_13; [FieldOffset(14)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_14; [FieldOffset(15)] [Ignore(DoesNotContributeToSize = true)] public byte ipv6_15; [FieldOffset(0)] [Ignore(DoesNotContributeToSize = true)] public byte ipv4_0; [FieldOffset(1)] [Ignore(DoesNotContributeToSize = true)] public byte ipv4_1; [FieldOffset(2)] [Ignore(DoesNotContributeToSize = true)] public byte ipv4_2; [FieldOffset(3)] [Ignore(DoesNotContributeToSize = true)] public byte ipv4_3; [FieldOffset(16)] public byte port0; [FieldOffset(17)] public byte port1; [FieldOffset(18)] public byte family; [FieldOffset(19)] public byte _padding; [FieldOffset(20)] public uint ipv6_scope_id; } public enum Baselib_NetworkAddress_AddressReuse { DoNotAllow, Allow } public struct Baselib_RegisteredNetwork_Buffer { public IntPtr id; public Baselib_Memory_PageAllocation allocation; } public struct Baselib_RegisteredNetwork_BufferSlice { public IntPtr id; public IntPtr data; public uint size; public uint offset; } public struct Baselib_RegisteredNetwork_Endpoint { public Baselib_RegisteredNetwork_BufferSlice slice; } public struct Baselib_RegisteredNetwork_Request { public Baselib_RegisteredNetwork_BufferSlice payload; public Baselib_RegisteredNetwork_Endpoint remoteEndpoint; public IntPtr requestUserdata; } public enum Baselib_RegisteredNetwork_CompletionStatus { Failed, Success } public struct Baselib_RegisteredNetwork_CompletionResult { public Baselib_RegisteredNetwork_CompletionStatus status; public uint bytesTransferred; public IntPtr requestUserdata; } public struct Baselib_RegisteredNetwork_Socket_UDP { public IntPtr handle; } public enum Baselib_RegisteredNetwork_ProcessStatus { NonePendingImmediately = 0, Done = 0, Pending = 1 } public enum Baselib_RegisteredNetwork_CompletionQueueStatus { NoResultsAvailable, ResultsAvailable } public struct Baselib_Socket_Handle { public IntPtr handle; } public enum Baselib_Socket_Protocol { UDP = 1, TCP } public struct Baselib_Socket_Message { public unsafe Baselib_NetworkAddress* address; public IntPtr data; public uint dataLen; } public enum Baselib_Socket_PollEvents { Readable = 1, Writable = 2, Connected = 4 } public struct Baselib_Socket_PollFd { public Baselib_Socket_Handle handle; public Baselib_Socket_PollEvents requestedEvents; public Baselib_Socket_PollEvents resultEvents; public unsafe Baselib_ErrorState* errorState; } public struct Baselib_SourceLocation { public unsafe byte* file; public unsafe byte* function; public uint lineNumber; } public struct Baselib_Timer_TickToNanosecondConversionRatio { public ulong ticksToNanosecondsNumerator; public ulong ticksToNanosecondsDenominator; } public static readonly UIntPtr Baselib_Memory_MaxAlignment = new UIntPtr(65536u); public static readonly UIntPtr Baselib_Memory_MinGuaranteedAlignment = new UIntPtr(8u); public const uint Baselib_NetworkAddress_IpMaxStringLength = 46u; public static readonly IntPtr Baselib_RegisteredNetwork_Buffer_Id_Invalid = IntPtr.Zero; public const uint Baselib_RegisteredNetwork_Endpoint_MaxSize = 28u; public static readonly IntPtr Baselib_Thread_InvalidId = IntPtr.Zero; public static readonly UIntPtr Baselib_Thread_MaxThreadNameLength = new UIntPtr(64u); public const uint Baselib_TLS_MinimumGuaranteedSlots = 100u; public const ulong Baselib_SecondsPerMinute = 60uL; public const ulong Baselib_MillisecondsPerSecond = 1000uL; public const ulong Baselib_MillisecondsPerMinute = 60000uL; public const ulong Baselib_MicrosecondsPerMillisecond = 1000uL; public const ulong Baselib_MicrosecondsPerSecond = 1000000uL; public const ulong Baselib_MicrosecondsPerMinute = 60000000uL; public const ulong Baselib_NanosecondsPerMicrosecond = 1000uL; public const ulong Baselib_NanosecondsPerMillisecond = 1000000uL; public const ulong Baselib_NanosecondsPerSecond = 1000000000uL; public const ulong Baselib_NanosecondsPerMinute = 60000000000uL; public const ulong Baselib_Timer_MaxNumberOfNanosecondsPerTick = 1000uL; public const double Baselib_Timer_MinNumberOfNanosecondsPerTick = 0.01; public const double Baselib_Timer_HighPrecisionTimerCrossThreadMontotonyTolerance_InNanoseconds = 100.0; public static readonly Baselib_Memory_PageAllocation Baselib_Memory_PageAllocation_Invalid = default(Baselib_Memory_PageAllocation); public static readonly Baselib_RegisteredNetwork_Socket_UDP Baselib_RegisteredNetwork_Socket_UDP_Invalid = default(Baselib_RegisteredNetwork_Socket_UDP); public static readonly Baselib_Socket_Handle Baselib_Socket_Handle_Invalid = new Baselib_Socket_Handle { handle = (IntPtr)(-1) }; public static readonly Baselib_DynamicLibrary_Handle Baselib_DynamicLibrary_Handle_Invalid = new Baselib_DynamicLibrary_Handle { handle = (IntPtr)(-1) }; public static readonly Baselib_FileIO_EventQueue Baselib_FileIO_EventQueue_Invalid = new Baselib_FileIO_EventQueue { handle = (IntPtr)0 }; public static readonly Baselib_FileIO_AsyncFile Baselib_FileIO_AsyncFile_Invalid = new Baselib_FileIO_AsyncFile { handle = (IntPtr)0 }; public static readonly Baselib_FileIO_SyncFile Baselib_FileIO_SyncFile_Invalid = new Baselib_FileIO_SyncFile { handle = (IntPtr)(-1) }; [FreeFunction(IsThreadSafe = true)] public unsafe static Baselib_DynamicLibrary_Handle Baselib_DynamicLibrary_OpenUtf8(byte* pathnameUtf8, Baselib_ErrorState* errorState) { Baselib_DynamicLibrary_OpenUtf8_Injected(pathnameUtf8, errorState, out var ret); return ret; } [FreeFunction(IsThreadSafe = true)] public unsafe static Baselib_DynamicLibrary_Handle Baselib_DynamicLibrary_OpenUtf16(char* pathnameUtf16, Baselib_ErrorState* errorState) { Baselib_DynamicLibrary_OpenUtf16_Injected(pathnameUtf16, errorState, out var ret); return ret; } [FreeFunction(IsThreadSafe = true)] public unsafe static Baselib_DynamicLibrary_Handle Baselib_DynamicLibrary_OpenProgramHandle(Baselib_ErrorState* errorState) { Baselib_DynamicLibrary_OpenProgramHandle_Injected(errorState, out var ret); return ret; } [FreeFunction(IsThreadSafe = true)] public unsafe static Baselib_DynamicLibrary_Handle Baselib_DynamicLibrary_FromNativeHandle(ulong handle, uint type, Baselib_ErrorState* errorState) { Baselib_DynamicLibrary_FromNativeHandle_Injected(handle, type, errorState, out var ret); return ret; } [FreeFunction(IsThreadSafe = true)] public unsafe static IntPtr Baselib_DynamicLibrary_GetFunction(Baselib_DynamicLibrary_Handle handle, byte* functionName, Baselib_ErrorState* errorState) { return Baselib_DynamicLibrary_GetFunction_Injected(ref handle, functionName, errorState); } [FreeFunction(IsThreadSafe = true)] public static void Baselib_DynamicLibrary_Close(Baselib_DynamicLibrary_Handle handle) { Baselib_DynamicLibrary_Close_Injected(ref handle); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public unsafe static extern uint Baselib_ErrorState_Explain(Baselib_ErrorState* errorState, byte* buffer, uint bufferLen, Baselib_ErrorState_ExplainVerbosity verbosity); [FreeFunction(IsThreadSafe = true)] public static Baselib_FileIO_EventQueue Baselib_FileIO_EventQueue_Create() { Baselib_FileIO_EventQueue_Create_Injected(out var ret); return ret; } [FreeFunction(IsThreadSafe = true)] public static void Baselib_FileIO_EventQueue_Free(Baselib_FileIO_EventQueue eq) { Baselib_FileIO_EventQueue_Free_Injected(ref eq); } [FreeFunction(IsThreadSafe = true)] public unsafe static ulong Baselib_FileIO_EventQueue_Dequeue(Baselib_FileIO_EventQueue eq, Baselib_FileIO_EventQueue_Result* results, ulong count, uint timeoutInMilliseconds) { return Baselib_FileIO_EventQueue_Dequeue_Injected(ref eq, results, count, timeoutInMilliseconds); } [FreeFunction(IsThreadSafe = true)] public static void Baselib_FileIO_EventQueue_Shutdown(Baselib_FileIO_EventQueue eq, uint threadCount) { Baselib_FileIO_EventQueue_Shutdown_Injected(ref eq, threadCount); } [FreeFunction(IsThreadSafe = true)] public unsafe static Baselib_FileIO_AsyncFile Baselib_FileIO_AsyncOpen(Baselib_FileIO_EventQueue eq, byte* pathname, ulong userdata, Baselib_FileIO_Priority priority) { Baselib_FileIO_AsyncOpen_Injected(ref eq, pathname, userdata, priority, out var ret); return ret; } [FreeFunction(IsThreadSafe = true)] public unsafe static void Baselib_FileIO_AsyncRead(Baselib_FileIO_AsyncFile file, Baselib_FileIO_ReadRequest* requests, ulong count, ulong userdata, Baselib_FileIO_Priority priority) { Baselib_FileIO_AsyncRead_Injected(ref file, requests, count, userdata, priority); } [FreeFunction(IsThreadSafe = true)] public static void Baselib_FileIO_AsyncClose(Baselib_FileIO_AsyncFile file) { Baselib_FileIO_AsyncClose_Injected(ref file); } [FreeFunction(IsThreadSafe = true)] public unsafe static Baselib_FileIO_SyncFile Baselib_FileIO_SyncOpen(byte* pathname, Baselib_FileIO_OpenFlags openFlags, Baselib_ErrorState* errorState) { Baselib_FileIO_SyncOpen_Injected(pathname, openFlags, errorState, out var ret); return ret; } [FreeFunction(IsThreadSafe = true)] public static Baselib_FileIO_SyncFile Baselib_FileIO_SyncFileFromNativeHandle(ulong handle, uint type) { Baselib_FileIO_SyncFileFromNativeHandle_Injected(handle, type, out var ret); return ret; } [FreeFunction(IsThreadSafe = true)] public unsafe static ulong Baselib_FileIO_SyncRead(Baselib_FileIO_SyncFile file, ulong offset, IntPtr buffer, ulong size, Baselib_ErrorState* errorState) { return Baselib_FileIO_SyncRead_Injected(ref file, offset, buffer, size, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static ulong Baselib_FileIO_SyncWrite(Baselib_FileIO_SyncFile file, ulong offset, IntPtr buffer, ulong size, Baselib_ErrorState* errorState) { return Baselib_FileIO_SyncWrite_Injected(ref file, offset, buffer, size, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static void Baselib_FileIO_SyncFlush(Baselib_FileIO_SyncFile file, Baselib_ErrorState* errorState) { Baselib_FileIO_SyncFlush_Injected(ref file, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static void Baselib_FileIO_SyncSetFileSize(Baselib_FileIO_SyncFile file, ulong size, Baselib_ErrorState* errorState) { Baselib_FileIO_SyncSetFileSize_Injected(ref file, size, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static ulong Baselib_FileIO_SyncGetFileSize(Baselib_FileIO_SyncFile file, Baselib_ErrorState* errorState) { return Baselib_FileIO_SyncGetFileSize_Injected(ref file, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static void Baselib_FileIO_SyncClose(Baselib_FileIO_SyncFile file, Baselib_ErrorState* errorState) { Baselib_FileIO_SyncClose_Injected(ref file, errorState); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public unsafe static extern void Baselib_Memory_GetPageSizeInfo(Baselib_Memory_PageSizeInfo* outPagesSizeInfo); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern IntPtr Baselib_Memory_Allocate(UIntPtr size); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern IntPtr Baselib_Memory_Reallocate(IntPtr ptr, UIntPtr newSize); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern void Baselib_Memory_Free(IntPtr ptr); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern IntPtr Baselib_Memory_AlignedAllocate(UIntPtr size, UIntPtr alignment); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern IntPtr Baselib_Memory_AlignedReallocate(IntPtr ptr, UIntPtr newSize, UIntPtr alignment); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern void Baselib_Memory_AlignedFree(IntPtr ptr); [FreeFunction(IsThreadSafe = true)] public unsafe static Baselib_Memory_PageAllocation Baselib_Memory_AllocatePages(ulong pageSize, ulong pageCount, ulong alignmentInMultipleOfPageSize, Baselib_Memory_PageState pageState, Baselib_ErrorState* errorState) { Baselib_Memory_AllocatePages_Injected(pageSize, pageCount, alignmentInMultipleOfPageSize, pageState, errorState, out var ret); return ret; } [FreeFunction(IsThreadSafe = true)] public unsafe static void Baselib_Memory_ReleasePages(Baselib_Memory_PageAllocation pageAllocation, Baselib_ErrorState* errorState) { Baselib_Memory_ReleasePages_Injected(ref pageAllocation, errorState); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public unsafe static extern void Baselib_Memory_SetPageState(IntPtr addressOfFirstPage, ulong pageSize, ulong pageCount, Baselib_Memory_PageState pageState, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public unsafe static extern void Baselib_NetworkAddress_Encode(Baselib_NetworkAddress* dstAddress, Baselib_NetworkAddress_Family family, byte* ip, ushort port, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public unsafe static extern void Baselib_NetworkAddress_Decode(Baselib_NetworkAddress* srcAddress, Baselib_NetworkAddress_Family* family, byte* ipAddressBuffer, uint ipAddressBufferLen, ushort* port, Baselib_ErrorState* errorState); [FreeFunction(IsThreadSafe = true)] public unsafe static Baselib_RegisteredNetwork_Buffer Baselib_RegisteredNetwork_Buffer_Register(Baselib_Memory_PageAllocation pageAllocation, Baselib_ErrorState* errorState) { Baselib_RegisteredNetwork_Buffer_Register_Injected(ref pageAllocation, errorState, out var ret); return ret; } [FreeFunction(IsThreadSafe = true)] public static void Baselib_RegisteredNetwork_Buffer_Deregister(Baselib_RegisteredNetwork_Buffer buffer) { Baselib_RegisteredNetwork_Buffer_Deregister_Injected(ref buffer); } [FreeFunction(IsThreadSafe = true)] public static Baselib_RegisteredNetwork_BufferSlice Baselib_RegisteredNetwork_BufferSlice_Create(Baselib_RegisteredNetwork_Buffer buffer, uint offset, uint size) { Baselib_RegisteredNetwork_BufferSlice_Create_Injected(ref buffer, offset, size, out var ret); return ret; } [FreeFunction(IsThreadSafe = true)] public static Baselib_RegisteredNetwork_BufferSlice Baselib_RegisteredNetwork_BufferSlice_Empty() { Baselib_RegisteredNetwork_BufferSlice_Empty_Injected(out var ret); return ret; } [FreeFunction(IsThreadSafe = true)] public unsafe static Baselib_RegisteredNetwork_Endpoint Baselib_RegisteredNetwork_Endpoint_Create(Baselib_NetworkAddress* srcAddress, Baselib_RegisteredNetwork_BufferSlice dstSlice, Baselib_ErrorState* errorState) { Baselib_RegisteredNetwork_Endpoint_Create_Injected(srcAddress, ref dstSlice, errorState, out var ret); return ret; } [FreeFunction(IsThreadSafe = true)] public static Baselib_RegisteredNetwork_Endpoint Baselib_RegisteredNetwork_Endpoint_Empty() { Baselib_RegisteredNetwork_Endpoint_Empty_Injected(out var ret); return ret; } [FreeFunction(IsThreadSafe = true)] public unsafe static void Baselib_RegisteredNetwork_Endpoint_GetNetworkAddress(Baselib_RegisteredNetwork_Endpoint endpoint, Baselib_NetworkAddress* dstAddress, Baselib_ErrorState* errorState) { Baselib_RegisteredNetwork_Endpoint_GetNetworkAddress_Injected(ref endpoint, dstAddress, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static Baselib_RegisteredNetwork_Socket_UDP Baselib_RegisteredNetwork_Socket_UDP_Create(Baselib_NetworkAddress* bindAddress, Baselib_NetworkAddress_AddressReuse endpointReuse, uint sendQueueSize, uint recvQueueSize, Baselib_ErrorState* errorState) { Baselib_RegisteredNetwork_Socket_UDP_Create_Injected(bindAddress, endpointReuse, sendQueueSize, recvQueueSize, errorState, out var ret); return ret; } [FreeFunction(IsThreadSafe = true)] public unsafe static uint Baselib_RegisteredNetwork_Socket_UDP_ScheduleRecv(Baselib_RegisteredNetwork_Socket_UDP socket, Baselib_RegisteredNetwork_Request* requests, uint requestsCount, Baselib_ErrorState* errorState) { return Baselib_RegisteredNetwork_Socket_UDP_ScheduleRecv_Injected(ref socket, requests, requestsCount, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static uint Baselib_RegisteredNetwork_Socket_UDP_ScheduleSend(Baselib_RegisteredNetwork_Socket_UDP socket, Baselib_RegisteredNetwork_Request* requests, uint requestsCount, Baselib_ErrorState* errorState) { return Baselib_RegisteredNetwork_Socket_UDP_ScheduleSend_Injected(ref socket, requests, requestsCount, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static Baselib_RegisteredNetwork_ProcessStatus Baselib_RegisteredNetwork_Socket_UDP_ProcessRecv(Baselib_RegisteredNetwork_Socket_UDP socket, Baselib_ErrorState* errorState) { return Baselib_RegisteredNetwork_Socket_UDP_ProcessRecv_Injected(ref socket, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static Baselib_RegisteredNetwork_ProcessStatus Baselib_RegisteredNetwork_Socket_UDP_ProcessSend(Baselib_RegisteredNetwork_Socket_UDP socket, Baselib_ErrorState* errorState) { return Baselib_RegisteredNetwork_Socket_UDP_ProcessSend_Injected(ref socket, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static Baselib_RegisteredNetwork_CompletionQueueStatus Baselib_RegisteredNetwork_Socket_UDP_WaitForCompletedRecv(Baselib_RegisteredNetwork_Socket_UDP socket, uint timeoutInMilliseconds, Baselib_ErrorState* errorState) { return Baselib_RegisteredNetwork_Socket_UDP_WaitForCompletedRecv_Injected(ref socket, timeoutInMilliseconds, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static Baselib_RegisteredNetwork_CompletionQueueStatus Baselib_RegisteredNetwork_Socket_UDP_WaitForCompletedSend(Baselib_RegisteredNetwork_Socket_UDP socket, uint timeoutInMilliseconds, Baselib_ErrorState* errorState) { return Baselib_RegisteredNetwork_Socket_UDP_WaitForCompletedSend_Injected(ref socket, timeoutInMilliseconds, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static uint Baselib_RegisteredNetwork_Socket_UDP_DequeueRecv(Baselib_RegisteredNetwork_Socket_UDP socket, Baselib_RegisteredNetwork_CompletionResult* results, uint resultsCount, Baselib_ErrorState* errorState) { return Baselib_RegisteredNetwork_Socket_UDP_DequeueRecv_Injected(ref socket, results, resultsCount, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static uint Baselib_RegisteredNetwork_Socket_UDP_DequeueSend(Baselib_RegisteredNetwork_Socket_UDP socket, Baselib_RegisteredNetwork_CompletionResult* results, uint resultsCount, Baselib_ErrorState* errorState) { return Baselib_RegisteredNetwork_Socket_UDP_DequeueSend_Injected(ref socket, results, resultsCount, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static void Baselib_RegisteredNetwork_Socket_UDP_GetNetworkAddress(Baselib_RegisteredNetwork_Socket_UDP socket, Baselib_NetworkAddress* dstAddress, Baselib_ErrorState* errorState) { Baselib_RegisteredNetwork_Socket_UDP_GetNetworkAddress_Injected(ref socket, dstAddress, errorState); } [FreeFunction(IsThreadSafe = true)] public static void Baselib_RegisteredNetwork_Socket_UDP_Close(Baselib_RegisteredNetwork_Socket_UDP socket) { Baselib_RegisteredNetwork_Socket_UDP_Close_Injected(ref socket); } [FreeFunction(IsThreadSafe = true)] public unsafe static Baselib_Socket_Handle Baselib_Socket_Create(Baselib_NetworkAddress_Family family, Baselib_Socket_Protocol protocol, Baselib_ErrorState* errorState) { Baselib_Socket_Create_Injected(family, protocol, errorState, out var ret); return ret; } [FreeFunction(IsThreadSafe = true)] public unsafe static void Baselib_Socket_Bind(Baselib_Socket_Handle socket, Baselib_NetworkAddress* address, Baselib_NetworkAddress_AddressReuse addressReuse, Baselib_ErrorState* errorState) { Baselib_Socket_Bind_Injected(ref socket, address, addressReuse, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static void Baselib_Socket_TCP_Connect(Baselib_Socket_Handle socket, Baselib_NetworkAddress* address, Baselib_NetworkAddress_AddressReuse addressReuse, Baselib_ErrorState* errorState) { Baselib_Socket_TCP_Connect_Injected(ref socket, address, addressReuse, errorState); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public unsafe static extern void Baselib_Socket_Poll(Baselib_Socket_PollFd* sockets, uint socketsCount, uint timeoutInMilliseconds, Baselib_ErrorState* errorState); [FreeFunction(IsThreadSafe = true)] public unsafe static void Baselib_Socket_GetAddress(Baselib_Socket_Handle socket, Baselib_NetworkAddress* address, Baselib_ErrorState* errorState) { Baselib_Socket_GetAddress_Injected(ref socket, address, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static void Baselib_Socket_TCP_Listen(Baselib_Socket_Handle socket, Baselib_ErrorState* errorState) { Baselib_Socket_TCP_Listen_Injected(ref socket, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static Baselib_Socket_Handle Baselib_Socket_TCP_Accept(Baselib_Socket_Handle socket, Baselib_ErrorState* errorState) { Baselib_Socket_TCP_Accept_Injected(ref socket, errorState, out var ret); return ret; } [FreeFunction(IsThreadSafe = true)] public unsafe static uint Baselib_Socket_UDP_Send(Baselib_Socket_Handle socket, Baselib_Socket_Message* messages, uint messagesCount, Baselib_ErrorState* errorState) { return Baselib_Socket_UDP_Send_Injected(ref socket, messages, messagesCount, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static uint Baselib_Socket_TCP_Send(Baselib_Socket_Handle socket, IntPtr data, uint dataLen, Baselib_ErrorState* errorState) { return Baselib_Socket_TCP_Send_Injected(ref socket, data, dataLen, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static uint Baselib_Socket_UDP_Recv(Baselib_Socket_Handle socket, Baselib_Socket_Message* messages, uint messagesCount, Baselib_ErrorState* errorState) { return Baselib_Socket_UDP_Recv_Injected(ref socket, messages, messagesCount, errorState); } [FreeFunction(IsThreadSafe = true)] public unsafe static uint Baselib_Socket_TCP_Recv(Baselib_Socket_Handle socket, IntPtr data, uint dataLen, Baselib_ErrorState* errorState) { return Baselib_Socket_TCP_Recv_Injected(ref socket, data, dataLen, errorState); } [FreeFunction(IsThreadSafe = true)] public static void Baselib_Socket_Close(Baselib_Socket_Handle socket) { Baselib_Socket_Close_Injected(ref socket); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern void Baselib_Thread_YieldExecution(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern IntPtr Baselib_Thread_GetCurrentThreadId(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern UIntPtr Baselib_TLS_Alloc(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern void Baselib_TLS_Free(UIntPtr handle); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern void Baselib_TLS_Set(UIntPtr handle, UIntPtr value); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern UIntPtr Baselib_TLS_Get(UIntPtr handle); [FreeFunction(IsThreadSafe = true)] public static Baselib_Timer_TickToNanosecondConversionRatio Baselib_Timer_GetTicksToNanosecondsConversionRatio() { Baselib_Timer_GetTicksToNanosecondsConversionRatio_Injected(out var ret); return ret; } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern ulong Baselib_Timer_GetHighPrecisionTimerTicks(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern void Baselib_Timer_WaitForAtLeast(uint timeInMilliseconds); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(IsThreadSafe = true)] public static extern double Baselib_Timer_GetTimeSinceStartupInSeconds(); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_DynamicLibrary_OpenUtf8_Injected(byte* pathnameUtf8, Baselib_ErrorState* errorState, out Baselib_DynamicLibrary_Handle ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_DynamicLibrary_OpenUtf16_Injected(char* pathnameUtf16, Baselib_ErrorState* errorState, out Baselib_DynamicLibrary_Handle ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_DynamicLibrary_OpenProgramHandle_Injected(Baselib_ErrorState* errorState, out Baselib_DynamicLibrary_Handle ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_DynamicLibrary_FromNativeHandle_Injected(ulong handle, uint type, Baselib_ErrorState* errorState, out Baselib_DynamicLibrary_Handle ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern IntPtr Baselib_DynamicLibrary_GetFunction_Injected(ref Baselib_DynamicLibrary_Handle handle, byte* functionName, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Baselib_DynamicLibrary_Close_Injected(ref Baselib_DynamicLibrary_Handle handle); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Baselib_FileIO_EventQueue_Create_Injected(out Baselib_FileIO_EventQueue ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Baselib_FileIO_EventQueue_Free_Injected(ref Baselib_FileIO_EventQueue eq); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern ulong Baselib_FileIO_EventQueue_Dequeue_Injected(ref Baselib_FileIO_EventQueue eq, Baselib_FileIO_EventQueue_Result* results, ulong count, uint timeoutInMilliseconds); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Baselib_FileIO_EventQueue_Shutdown_Injected(ref Baselib_FileIO_EventQueue eq, uint threadCount); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_FileIO_AsyncOpen_Injected(ref Baselib_FileIO_EventQueue eq, byte* pathname, ulong userdata, Baselib_FileIO_Priority priority, out Baselib_FileIO_AsyncFile ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_FileIO_AsyncRead_Injected(ref Baselib_FileIO_AsyncFile file, Baselib_FileIO_ReadRequest* requests, ulong count, ulong userdata, Baselib_FileIO_Priority priority); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Baselib_FileIO_AsyncClose_Injected(ref Baselib_FileIO_AsyncFile file); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_FileIO_SyncOpen_Injected(byte* pathname, Baselib_FileIO_OpenFlags openFlags, Baselib_ErrorState* errorState, out Baselib_FileIO_SyncFile ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Baselib_FileIO_SyncFileFromNativeHandle_Injected(ulong handle, uint type, out Baselib_FileIO_SyncFile ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern ulong Baselib_FileIO_SyncRead_Injected(ref Baselib_FileIO_SyncFile file, ulong offset, IntPtr buffer, ulong size, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern ulong Baselib_FileIO_SyncWrite_Injected(ref Baselib_FileIO_SyncFile file, ulong offset, IntPtr buffer, ulong size, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_FileIO_SyncFlush_Injected(ref Baselib_FileIO_SyncFile file, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_FileIO_SyncSetFileSize_Injected(ref Baselib_FileIO_SyncFile file, ulong size, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern ulong Baselib_FileIO_SyncGetFileSize_Injected(ref Baselib_FileIO_SyncFile file, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_FileIO_SyncClose_Injected(ref Baselib_FileIO_SyncFile file, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_Memory_AllocatePages_Injected(ulong pageSize, ulong pageCount, ulong alignmentInMultipleOfPageSize, Baselib_Memory_PageState pageState, Baselib_ErrorState* errorState, out Baselib_Memory_PageAllocation ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_Memory_ReleasePages_Injected(ref Baselib_Memory_PageAllocation pageAllocation, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_RegisteredNetwork_Buffer_Register_Injected(ref Baselib_Memory_PageAllocation pageAllocation, Baselib_ErrorState* errorState, out Baselib_RegisteredNetwork_Buffer ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Baselib_RegisteredNetwork_Buffer_Deregister_Injected(ref Baselib_RegisteredNetwork_Buffer buffer); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Baselib_RegisteredNetwork_BufferSlice_Create_Injected(ref Baselib_RegisteredNetwork_Buffer buffer, uint offset, uint size, out Baselib_RegisteredNetwork_BufferSlice ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Baselib_RegisteredNetwork_BufferSlice_Empty_Injected(out Baselib_RegisteredNetwork_BufferSlice ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_RegisteredNetwork_Endpoint_Create_Injected(Baselib_NetworkAddress* srcAddress, ref Baselib_RegisteredNetwork_BufferSlice dstSlice, Baselib_ErrorState* errorState, out Baselib_RegisteredNetwork_Endpoint ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Baselib_RegisteredNetwork_Endpoint_Empty_Injected(out Baselib_RegisteredNetwork_Endpoint ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_RegisteredNetwork_Endpoint_GetNetworkAddress_Injected(ref Baselib_RegisteredNetwork_Endpoint endpoint, Baselib_NetworkAddress* dstAddress, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_RegisteredNetwork_Socket_UDP_Create_Injected(Baselib_NetworkAddress* bindAddress, Baselib_NetworkAddress_AddressReuse endpointReuse, uint sendQueueSize, uint recvQueueSize, Baselib_ErrorState* errorState, out Baselib_RegisteredNetwork_Socket_UDP ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern uint Baselib_RegisteredNetwork_Socket_UDP_ScheduleRecv_Injected(ref Baselib_RegisteredNetwork_Socket_UDP socket, Baselib_RegisteredNetwork_Request* requests, uint requestsCount, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern uint Baselib_RegisteredNetwork_Socket_UDP_ScheduleSend_Injected(ref Baselib_RegisteredNetwork_Socket_UDP socket, Baselib_RegisteredNetwork_Request* requests, uint requestsCount, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern Baselib_RegisteredNetwork_ProcessStatus Baselib_RegisteredNetwork_Socket_UDP_ProcessRecv_Injected(ref Baselib_RegisteredNetwork_Socket_UDP socket, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern Baselib_RegisteredNetwork_ProcessStatus Baselib_RegisteredNetwork_Socket_UDP_ProcessSend_Injected(ref Baselib_RegisteredNetwork_Socket_UDP socket, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern Baselib_RegisteredNetwork_CompletionQueueStatus Baselib_RegisteredNetwork_Socket_UDP_WaitForCompletedRecv_Injected(ref Baselib_RegisteredNetwork_Socket_UDP socket, uint timeoutInMilliseconds, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern Baselib_RegisteredNetwork_CompletionQueueStatus Baselib_RegisteredNetwork_Socket_UDP_WaitForCompletedSend_Injected(ref Baselib_RegisteredNetwork_Socket_UDP socket, uint timeoutInMilliseconds, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern uint Baselib_RegisteredNetwork_Socket_UDP_DequeueRecv_Injected(ref Baselib_RegisteredNetwork_Socket_UDP socket, Baselib_RegisteredNetwork_CompletionResult* results, uint resultsCount, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern uint Baselib_RegisteredNetwork_Socket_UDP_DequeueSend_Injected(ref Baselib_RegisteredNetwork_Socket_UDP socket, Baselib_RegisteredNetwork_CompletionResult* results, uint resultsCount, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_RegisteredNetwork_Socket_UDP_GetNetworkAddress_Injected(ref Baselib_RegisteredNetwork_Socket_UDP socket, Baselib_NetworkAddress* dstAddress, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Baselib_RegisteredNetwork_Socket_UDP_Close_Injected(ref Baselib_RegisteredNetwork_Socket_UDP socket); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_Socket_Create_Injected(Baselib_NetworkAddress_Family family, Baselib_Socket_Protocol protocol, Baselib_ErrorState* errorState, out Baselib_Socket_Handle ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_Socket_Bind_Injected(ref Baselib_Socket_Handle socket, Baselib_NetworkAddress* address, Baselib_NetworkAddress_AddressReuse addressReuse, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_Socket_TCP_Connect_Injected(ref Baselib_Socket_Handle socket, Baselib_NetworkAddress* address, Baselib_NetworkAddress_AddressReuse addressReuse, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_Socket_GetAddress_Injected(ref Baselib_Socket_Handle socket, Baselib_NetworkAddress* address, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_Socket_TCP_Listen_Injected(ref Baselib_Socket_Handle socket, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void Baselib_Socket_TCP_Accept_Injected(ref Baselib_Socket_Handle socket, Baselib_ErrorState* errorState, out Baselib_Socket_Handle ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern uint Baselib_Socket_UDP_Send_Injected(ref Baselib_Socket_Handle socket, Baselib_Socket_Message* messages, uint messagesCount, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern uint Baselib_Socket_TCP_Send_Injected(ref Baselib_Socket_Handle socket, IntPtr data, uint dataLen, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern uint Baselib_Socket_UDP_Recv_Injected(ref Baselib_Socket_Handle socket, Baselib_Socket_Message* messages, uint messagesCount, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern uint Baselib_Socket_TCP_Recv_Injected(ref Baselib_Socket_Handle socket, IntPtr data, uint dataLen, Baselib_ErrorState* errorState); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Baselib_Socket_Close_Injected(ref Baselib_Socket_Handle socket); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Baselib_Timer_GetTicksToNanosecondsConversionRatio_Injected(out Baselib_Timer_TickToNanosecondConversionRatio ret); } } namespace Unity.Jobs { internal static class JobValidationInternal { [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] internal static void CheckReflectionDataCorrect<T>(IntPtr reflectionData) { } [BurstDiscard] [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] private static void CheckReflectionDataCorrectInternal<T>(IntPtr reflectionData, ref bool burstCompiled) { if (reflectionData == IntPtr.Zero) { throw new InvalidOperationException($"Reflection data was not set up by an Initialize() call. Support for burst compiled calls to Schedule depends on the Collections package.\n\nFor generic job types, please include [assembly: RegisterGenericJobType(typeof({typeof(T)}))] in your source file."); } burstCompiled = false; } } [JobProducerType(typeof(IJobExtensions.JobStruct<>))] public interface IJob { void Execute(); } public static class IJobExtensions { [StructLayout(LayoutKind.Sequential, Size = 1)] internal struct JobStruct<T> where T : struct, IJob { internal delegate void ExecuteJobFunction(ref T data, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex); internal static readonly BurstLike.SharedStatic<IntPtr> jobReflectionData = BurstLike.SharedStatic<IntPtr>.GetOrCreate<JobStruct<T>>(); [BurstDiscard] internal static void Initialize() { if (jobReflectionData.Data == IntPtr.Zero) { jobReflectionData.Data = JobsUtility.CreateJobReflectionData(typeof(T), new ExecuteJobFunction(Execute)); } } public static void Execute(ref T data, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex) { data.Execute(); } } public static void EarlyJobInit<T>() where T : struct, IJob { JobStruct<T>.Initialize(); } private static IntPtr GetReflectionData<T>() where T : struct, IJob { JobStruct<T>.Initialize(); return JobStruct<T>.jobReflectionData.Data; } public unsafe static JobHandle Schedule<T>(this T jobData, JobHandle dependsOn = default(JobHandle)) where T : struct, IJob { JobsUtility.JobScheduleParameters parameters = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), GetReflectionData<T>(), dependsOn, ScheduleMode.Single); return JobsUtility.Schedule(ref parameters); } public unsafe static void Run<T>(this T jobData) where T : struct, IJob { JobsUtility.JobScheduleParameters parameters = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), GetReflectionData<T>(), default(JobHandle), ScheduleMode.Run); JobsUtility.Schedule(ref parameters); } public unsafe static JobHandle ScheduleByRef<T>(this ref T jobData, JobHandle dependsOn = default(JobHandle)) where T : struct, IJob { JobsUtility.JobScheduleParameters parameters = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), GetReflectionData<T>(), dependsOn, ScheduleMode.Single); return JobsUtility.Schedule(ref parameters); } public unsafe static void RunByRef<T>(this ref T jobData) where T : struct, IJob { JobsUtility.JobScheduleParameters parameters = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), GetReflectionData<T>(), default(JobHandle), ScheduleMode.Run); JobsUtility.Schedule(ref parameters); } } [JobProducerType(typeof(IJobForExtensions.ForJobStruct<>))] public interface IJobFor { void Execute(int index); } public static class IJobForExtensions { [StructLayout(LayoutKind.Sequential, Size = 1)] internal struct ForJobStruct<T> where T : struct, IJobFor { public delegate void ExecuteJobFunction(ref T data, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex); internal static readonly BurstLike.SharedStatic<IntPtr> jobReflectionData = BurstLike.SharedStatic<IntPtr>.GetOrCreate<ForJobStruct<T>>(); [BurstDiscard] internal static void Initialize() { if (jobReflectionData.Data == IntPtr.Zero) { jobReflectionData.Data = JobsUtility.CreateJobReflectionData(typeof(T), new ExecuteJobFunction(Execute)); } } public static void Execute(ref T jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex) { int beginIndex; int endIndex; while (JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out beginIndex, out endIndex)) { int num = endIndex; for (int i = beginIndex; i < num; i++) { jobData.Execute(i); } } } } public static void EarlyJobInit<T>() where T : struct, IJobFor { ForJobStruct<T>.Initialize(); } private static IntPtr GetReflectionData<T>() where T : struct, IJobFor { ForJobStruct<T>.Initialize(); return ForJobStruct<T>.jobReflectionData.Data; } public unsafe static JobHandle Schedule<T>(this T jobData, int arrayLength, JobHandle dependency) where T : struct, IJobFor { JobsUtility.JobScheduleParameters parameters = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), GetReflectionData<T>(), dependency, ScheduleMode.Single); return JobsUtility.ScheduleParallelFor(ref parameters, arrayLength, arrayLength); } public unsafe static JobHandle ScheduleParallel<T>(this T jobData, int arrayLength, int innerloopBatchCount, JobHandle dependency) where T : struct, IJobFor { JobsUtility.JobScheduleParameters parameters = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), GetReflectionData<T>(), dependency, ScheduleMode.Batched); return JobsUtility.ScheduleParallelFor(ref parameters, arrayLength, innerloopBatchCount); } public unsafe static void Run<T>(this T jobData, int arrayLength) where T : struct, IJobFor { JobsUtility.JobScheduleParameters parameters = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), GetReflectionData<T>(), default(JobHandle), ScheduleMode.Run); JobsUtility.ScheduleParallelFor(ref parameters, arrayLength, arrayLength); } public unsafe static JobHandle ScheduleByRef<T>(this ref T jobData, int arrayLength, JobHandle dependency) where T : struct, IJobFor { JobsUtility.JobScheduleParameters parameters = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), GetReflectionData<T>(), dependency, ScheduleMode.Single); return JobsUtility.ScheduleParallelFor(ref parameters, arrayLength, arrayLength); } public unsafe static JobHandle ScheduleParallelByRef<T>(this ref T jobData, int arrayLength, int innerloopBatchCount, JobHandle dependency) where T : struct, IJobFor { JobsUtility.JobScheduleParameters parameters = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), GetReflectionData<T>(), dependency, ScheduleMode.Batched); return JobsUtility.ScheduleParallelFor(ref parameters, arrayLength, innerloopBatchCount); } public unsafe static void RunByRef<T>(this ref T jobData, int arrayLength) where T : struct, IJobFor { JobsUtility.JobScheduleParameters parameters = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), GetReflectionData<T>(), default(JobHandle), ScheduleMode.Run); JobsUtility.ScheduleParallelFor(ref parameters, arrayLength, arrayLength); } } [JobProducerType(typeof(IJobParallelForExtensions.ParallelForJobStruct<>))] public interface IJobParallelFor { void Execute(int index); } public static class IJobParallelForExtensions { [StructLayout(LayoutKind.Sequential, Size = 1)] internal struct ParallelForJobStruct<T> where T : struct, IJobParallelFor { public delegate void ExecuteJobFunction(ref T data, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex); internal static readonly BurstLike.SharedStatic<IntPtr> jobReflectionData = BurstLike.SharedStatic<IntPtr>.GetOrCreate<ParallelForJobStruct<T>>(); [BurstDiscard] internal static void Initialize() { if (jobReflectionData.Data == IntPtr.Zero) { jobReflectionData.Data = JobsUtility.CreateJobReflectionData(typeof(T), new ExecuteJobFunction(Execute)); } } public static void Execute(ref T jobData, IntPtr additionalPtr, IntPtr bufferRangePatchData, ref JobRanges ranges, int jobIndex) { int beginIndex; int endIndex; while (JobsUtility.GetWorkStealingRange(ref ranges, jobIndex, out beginIndex, out endIndex)) { int num = endIndex; for (int i = beginIndex; i < num; i++) { jobData.Execute(i); } } } } public static void EarlyJobInit<T>() where T : struct, IJobParallelFor { ParallelForJobStruct<T>.Initialize(); } private static IntPtr GetReflectionData<T>() where T : struct, IJobParallelFor { ParallelForJobStruct<T>.Initialize(); return ParallelForJobStruct<T>.jobReflectionData.Data; } public unsafe static JobHandle Schedule<T>(this T jobData, int arrayLength, int innerloopBatchCount, JobHandle dependsOn = default(JobHandle)) where T : struct, IJobParallelFor { JobsUtility.JobScheduleParameters parameters = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), GetReflectionData<T>(), dependsOn, ScheduleMode.Batched); return JobsUtility.ScheduleParallelFor(ref parameters, arrayLength, innerloopBatchCount); } public unsafe static void Run<T>(this T jobData, int arrayLength) where T : struct, IJobParallelFor { JobsUtility.JobScheduleParameters parameters = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), GetReflectionData<T>(), default(JobHandle), ScheduleMode.Run); JobsUtility.ScheduleParallelFor(ref parameters, arrayLength, arrayLength); } public unsafe static JobHandle ScheduleByRef<T>(this ref T jobData, int arrayLength, int innerloopBatchCount, JobHandle dependsOn = default(JobHandle)) where T : struct, IJobParallelFor { JobsUtility.JobScheduleParameters parameters = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), GetReflectionData<T>(), dependsOn, ScheduleMode.Batched); return JobsUtility.ScheduleParallelFor(ref parameters, arrayLength, innerloopBatchCount); } public unsafe static void RunByRef<T>(this ref T jobData, int arrayLength) where T : struct, IJobParallelFor { JobsUtility.JobScheduleParameters parameters = new JobsUtility.JobScheduleParameters(UnsafeUtility.AddressOf(ref jobData), GetReflectionData<T>(), default(JobHandle), ScheduleMode.Run); JobsUtility.ScheduleParallelFor(ref parameters, arrayLength, arrayLength); } } [NativeType(Header = "Runtime/Jobs/ScriptBindings/JobsBindings.h")] public struct JobHandle : IEquatable<JobHandle> { internal ulong jobGroup; internal int version; public bool IsCompleted => ScheduleBatchedJobsAndIsCompleted(ref this); public void Complete() { if (jobGroup != 0) { ScheduleBatchedJobsAndComplete(ref this); } } public unsafe static void CompleteAll(ref JobHandle job0, ref JobHandle job1) { JobHandle* ptr = stackalloc JobHandle[2]; *ptr = job0; ptr[1] = job1; ScheduleBatchedJobsAndCompleteAll(ptr, 2); job0 = default(JobHandle); job1 = default(JobHandle); } public unsafe static void CompleteAll(ref JobHandle job0, ref JobHandle job1, ref JobHandle job2) { JobHandle* ptr = stackalloc JobHandle[3]; *ptr = job0; ptr[1] = job1; ptr[2] = job2; ScheduleBatchedJobsAndCompleteAll(ptr, 3); job0 = default(JobHandle); job1 = default(JobHandle); job2 = default(JobHandle); } public unsafe static void CompleteAll(NativeArray<JobHandle> jobs) { ScheduleBatchedJobsAndCompleteAll(jobs.GetUnsafeReadOnlyPtr(), jobs.Length); } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("ScheduleBatchedScriptingJobs", IsFreeFunction = true, IsThreadSafe = true)] public static extern void ScheduleBatchedJobs(); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("ScheduleBatchedScriptingJobsAndComplete", IsFreeFunction = true, IsThreadSafe = true, ThrowsException = true)] private static extern void ScheduleBatchedJobsAndComplete(ref JobHandle job); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("ScheduleBatchedScriptingJobsAndIsCompleted", IsFreeFunction = true, IsThreadSafe = true, ThrowsException = true)] private static extern bool ScheduleBatchedJobsAndIsCompleted(ref JobHandle job); [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod("ScheduleBatchedScriptingJobsAndCompleteAll", IsFreeFunction = true, IsThreadSafe = true, ThrowsException = true)] private unsafe static extern void ScheduleBatchedJobsAndCompleteAll(void* jobs, int count); public static JobHandle CombineDependencies(JobHandle job0, JobHandle job1) { return CombineDependenciesInternal2(ref job0, ref job1); } public static JobHandle CombineDependencies(JobHandle job0, JobHandle job1, JobHandle job2) { return CombineDependenciesInternal3(ref job0, ref job1, ref job2); } public unsafe static JobHandle CombineDependencies(NativeArray<JobHandle> jobs) { return CombineDependenciesInternalPtr(jobs.GetUnsafeReadOnlyPtr(), jobs.Length); } public unsafe static JobHandle CombineDependencies(NativeSlice<JobHandle> jobs) { return CombineDependenciesInternalPtr(jobs.GetUnsafeReadOnlyPtr(), jobs.Length); } [NativeMethod(IsFreeFunction = true, IsThreadSafe = true, ThrowsException = true)] private static JobHandle CombineDependenciesInternal2(ref JobHandle job0, ref JobHandle job1) { CombineDependenciesInternal2_Injected(ref job0, ref job1, out var ret); return ret; } [NativeMethod(IsFreeFunction = true, IsThreadSafe = true, ThrowsException = true)] private static JobHandle CombineDependenciesInternal3(ref JobHandle job0, ref JobHandle job1, ref JobHandle job2) { CombineDependenciesInternal3_Injected(ref job0, ref job1, ref job2, out var ret); return ret; } [NativeMethod(IsFreeFunction = true, IsThreadSafe = true, ThrowsException = true)] internal unsafe static JobHandle CombineDependenciesInternalPtr(void* jobs, int count) { CombineDependenciesInternalPtr_Injected(jobs, count, out var ret); return ret; } [NativeMethod(IsFreeFunction = true, IsThreadSafe = true)] public static bool CheckFenceIsDependencyOrDidSyncFence(JobHandle jobHandle, JobHandle dependsOn) { return CheckFenceIsDependencyOrDidSyncFence_Injected(ref jobHandle, ref dependsOn); } public bool Equals(JobHandle other) { return jobGroup == other.jobGroup; } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void CombineDependenciesInternal2_Injected(ref JobHandle job0, ref JobHandle job1, out JobHandle ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void CombineDependenciesInternal3_Injected(ref JobHandle job0, ref JobHandle job1, ref JobHandle job2, out JobHandle ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void CombineDependenciesInternalPtr_Injected(void* jobs, int count, out JobHandle ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool CheckFenceIsDependencyOrDidSyncFence_Injected(ref JobHandle jobHandle, ref JobHandle dependsOn); } } namespace Unity.Jobs.LowLevel.Unsafe { public struct BatchQueryJob<CommandT, ResultT> where CommandT : struct where ResultT : struct { [Unity.Collections.ReadOnly] internal NativeArray<CommandT> commands; internal NativeArray<ResultT> results; public BatchQueryJob(NativeArray<CommandT> commands, NativeArray<ResultT> results) { this.commands = commands; this.results = results; } } [StructLayout(LayoutKind.Sequential, Size = 1)] public struct BatchQueryJobStruct<T> where T : struct { internal static IntPtr jobReflectionData; public static IntPtr Initialize() { if (jobReflectionData == IntPtr.Zero) { jobReflectionData = JobsUtility.CreateJobReflectionData(typeof(T), null); } return jobReflectionData; } } public static class JobHandleUnsafeUtility { public unsafe static JobHandle CombineDependencies(JobHandle* jobs, int count) { return JobHandle.CombineDependenciesInternalPtr(jobs, count); } } [AttributeUsage(AttributeTargets.Interface)] public sealed class JobProducerTypeAttribute : Attribute { public Type ProducerType { get; } public JobProducerTypeAttribute(Type producerType) { ProducerType = producerType; } } public struct JobRanges { internal int BatchSize; internal int NumJobs; public int TotalIterationCount; internal IntPtr StartEndIndex; } public enum ScheduleMode { Run = 0, [Obsolete("Batched is obsolete, use Parallel or Single depending on job type. (UnityUpgradable) -> Parallel", false)] Batched = 1, Parallel = 1, Single = 2 } [Obsolete("Reflection data is now universal between job types. The parameter can be removed.", false)] public enum JobType { Single, ParallelFor } [NativeType(Header = "Runtime/Jobs/ScriptBindings/JobsBindings.h")] [NativeHeader("Runtime/Jobs/JobSystem.h")] public static class JobsUtility { public struct JobScheduleParameters { public JobHandle Dependency; public int ScheduleMode; public IntPtr ReflectionData; public IntPtr JobDataPtr; public unsafe JobScheduleParameters(void* i_jobData, IntPtr i_reflectionData, JobHandle i_dependency, ScheduleMode i_scheduleMode) { Dependency = i_dependency; JobDataPtr = (IntPtr)i_jobData; ReflectionData = i_reflectionData; ScheduleMode = (int)i_scheduleMode; } } internal delegate void PanicFunction_(); public const int MaxJobThreadCount = 128; public const int CacheLineSize = 64; internal static PanicFunction_ PanicFunction; public static extern bool IsExecutingJob { [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(IsFreeFunction = true, IsThreadSafe = true)] get; } public static extern bool JobDebuggerEnabled { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] get; [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] set; } public static extern bool JobCompilerEnabled { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] get; [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction] set; } public static extern int JobWorkerMaximumCount { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("JobSystem::GetJobQueueMaximumThreadCount")] get; } public static int JobWorkerCount { get { return GetJobQueueWorkerThreadCount(); } set { if (value < 0 || value > JobWorkerMaximumCount) { throw new ArgumentOutOfRangeException("JobWorkerCount", $"Invalid JobWorkerCount {value} must be in the range 0 -> {JobWorkerMaximumCount}"); } SetJobQueueMaximumActiveThreadCount(value); } } public static extern int ThreadIndex { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetJobWorkerIndex", IsThreadSafe = true)] [BurstAuthorizedExternalMethod] get; } public static extern int ThreadIndexCount { [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("GetJobWorkerIndexCount", IsThreadSafe = true)] [BurstAuthorizedExternalMethod] get; } internal static bool JobBatchingEnabled => GetJobBatchingEnabled(); public unsafe static void GetJobRange(ref JobRanges ranges, int jobIndex, out int beginIndex, out int endIndex) { int* ptr = (int*)(void*)ranges.StartEndIndex; beginIndex = ptr[jobIndex * 2]; endIndex = ptr[jobIndex * 2 + 1]; } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(IsFreeFunction = true, IsThreadSafe = true)] public static extern bool GetWorkStealingRange(ref JobRanges ranges, int jobIndex, out int beginIndex, out int endIndex); [FreeFunction("ScheduleManagedJob", ThrowsException = true, IsThreadSafe = true)] public static JobHandle Schedule(ref JobScheduleParameters parameters) { Schedule_Injected(ref parameters, out var ret); return ret; } [FreeFunction("ScheduleManagedJobParallelFor", ThrowsException = true, IsThreadSafe = true)] public static JobHandle ScheduleParallelFor(ref JobScheduleParameters parameters, int arrayLength, int innerloopBatchCount) { ScheduleParallelFor_Injected(ref parameters, arrayLength, innerloopBatchCount, out var ret); return ret; } [FreeFunction("ScheduleManagedJobParallelForDeferArraySize", ThrowsException = true, IsThreadSafe = true)] public unsafe static JobHandle ScheduleParallelForDeferArraySize(ref JobScheduleParameters parameters, int innerloopBatchCount, void* listData, void* listDataAtomicSafetyHandle) { ScheduleParallelForDeferArraySize_Injected(ref parameters, innerloopBatchCount, listData, listDataAtomicSafetyHandle, out var ret); return ret; } [FreeFunction("ScheduleManagedJobParallelForTransform", ThrowsException = true)] public static JobHandle ScheduleParallelForTransform(ref JobScheduleParameters parameters, IntPtr transfromAccesssArray) { ScheduleParallelForTransform_Injected(ref parameters, transfromAccesssArray, out var ret); return ret; } [FreeFunction("ScheduleManagedJobParallelForTransformReadOnly", ThrowsException = true)] public static JobHandle ScheduleParallelForTransformReadOnly(ref JobScheduleParameters parameters, IntPtr transfromAccesssArray, int innerloopBatchCount) { ScheduleParallelForTransformReadOnly_Injected(ref parameters, transfromAccesssArray, innerloopBatchCount, out var ret); return ret; } [MethodImpl(MethodImplOptions.InternalCall)] [NativeMethod(IsThreadSafe = true, IsFreeFunction = true)] [Conditional("ENABLE_UNITY_COLLECTIONS_CHECKS")] public unsafe static extern void PatchBufferMinMaxRanges(IntPtr bufferRangePatchData, void* jobdata, int startIndex, int rangeSize); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction(ThrowsException = true, IsThreadSafe = true)] private static extern IntPtr CreateJobReflectionData(Type wrapperJobType, Type userJobType, object managedJobFunction0, object managedJobFunction1, object managedJobFunction2); [Obsolete("JobType is obsolete. The parameter should be removed. (UnityUpgradable) -> !1")] public static IntPtr CreateJobReflectionData(Type type, JobType jobType, object managedJobFunction0, object managedJobFunction1 = null, object managedJobFunction2 = null) { return CreateJobReflectionData(type, type, managedJobFunction0, managedJobFunction1, managedJobFunction2); } public static IntPtr CreateJobReflectionData(Type type, object managedJobFunction0, object managedJobFunction1 = null, object managedJobFunction2 = null) { return CreateJobReflectionData(type, type, managedJobFunction0, managedJobFunction1, managedJobFunction2); } [Obsolete("JobType is obsolete. The parameter should be removed. (UnityUpgradable) -> !2")] public static IntPtr CreateJobReflectionData(Type wrapperJobType, Type userJobType, JobType jobType, object managedJobFunction0) { return CreateJobReflectionData(wrapperJobType, userJobType, managedJobFunction0, null, null); } public static IntPtr CreateJobReflectionData(Type wrapperJobType, Type userJobType, object managedJobFunction0) { return CreateJobReflectionData(wrapperJobType, userJobType, managedJobFunction0, null, null); } [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("JobSystem::GetJobQueueWorkerThreadCount")] private static extern int GetJobQueueWorkerThreadCount(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("JobSystem::ForceSetJobQueueWorkerThreadCount")] private static extern void SetJobQueueMaximumActiveThreadCount(int count); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("JobSystem::ResetJobQueueWorkerThreadCount")] public static extern void ResetJobWorkerCount(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("IsJobQueueBatchingEnabled")] private static extern bool GetJobBatchingEnabled(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("JobDebuggerGetSystemIdCellPtr")] internal static extern IntPtr GetSystemIdCellPtr(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("JobDebuggerClearSystemIds")] internal static extern void ClearSystemIds(); [MethodImpl(MethodImplOptions.InternalCall)] [FreeFunction("JobDebuggerGetSystemIdMappings")] internal unsafe static extern int GetSystemIdMappings(JobHandle* handles, int* systemIds, int maxCount); [RequiredByNativeCode] private static void InvokePanicFunction() { PanicFunction?.Invoke(); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void Schedule_Injected(ref JobScheduleParameters parameters, out JobHandle ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void ScheduleParallelFor_Injected(ref JobScheduleParameters parameters, int arrayLength, int innerloopBatchCount, out JobHandle ret); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void ScheduleParallelForDeferArraySize_Injected(ref JobScheduleParameters parameters, int innerloopBatchCount, void* listData, void* listDataAtomicSafetyHandle, out JobHandle ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void ScheduleParallelForTransform_Injected(ref JobScheduleParameters parameters, IntPtr transfromAccesssArray, out JobHandle ret); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void ScheduleParallelForTransformReadOnly_Injected(ref JobScheduleParameters parameters, IntPtr transfromAccesssArray, int innerloopBatchCount, out JobHandle ret); } } namespace Unity.IL2CPP.CompilerServices { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false, AllowMultiple = false)] internal class Il2CppEagerStaticClassConstructionAttribute : Attribute { } } namespace Unity.Profiling { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method, AllowMultiple = false)] [RequiredByNativeCode] public sealed class IgnoredByDeepProfilerAttribute : Attribute { } [StructLayout(LayoutKind.Explicit, Size = 2)] [UsedByNativeCode] public readonly struct ProfilerCategory { [FieldOffset(0)] private readonly ushort m_CategoryId; public unsafe string Name { get { ProfilerCategoryDescription categoryDescription = ProfilerUnsafeUtility.GetCategoryDescription(m_CategoryId); return ProfilerUnsafeUtility.Utf8ToString(categoryDescription.NameUtf8, categoryDescription.NameUtf8Len); } } public Color32 Color => ProfilerUnsafeUtility.GetCategoryDescription(m_CategoryId).Color; public static ProfilerCategory Render => new ProfilerCategory(0); public static ProfilerCategory Scripts => new ProfilerCategory(1); public static ProfilerCategory Gui => new ProfilerCategory(4); public static ProfilerCategory Physics => new ProfilerCategory(5); public static ProfilerCategory Physics2D => new ProfilerCategory(33); public static ProfilerCategory Animation => new ProfilerCategory(6); public static ProfilerCategory Ai => new ProfilerCategory(7); public static ProfilerCategory Audio => new ProfilerCategory(8); public static ProfilerCategory Video => new ProfilerCategory(11); public static ProfilerCategory Particles => new ProfilerCategory(12); public static ProfilerCategory Lighting => new ProfilerCategory(13); public static ProfilerCategory Network => new ProfilerCategory(14); public static ProfilerCategory Loading => new ProfilerCategory(15); public static ProfilerCategory Vr => new ProfilerCategory(22); public static ProfilerCategory Input => new ProfilerCategory(30); public static ProfilerCategory Memory => new ProfilerCategory(23); public static ProfilerCategory VirtualTexturing => new ProfilerCategory(31); public static ProfilerCategory FileIO => new ProfilerCategory(25); public static ProfilerCategory Internal => new ProfilerCategory(24); internal static ProfilerCategory Any => new ProfilerCategory(ushort.MaxValue); internal static ProfilerCategory GPU => new ProfilerCategory(32); public ProfilerCategory(string categoryName) { m_CategoryId = ProfilerUnsafeUtility.CreateCategory(categoryName, ProfilerCategoryColor.Scripts); } public ProfilerCategory(string categoryName, ProfilerCategoryColor color) { m_CategoryId = ProfilerUnsafeUtility.CreateCategory(categoryName, color); } internal ProfilerCategory(ushort category) { m_CategoryId = category; } public override string ToString() { return Name; } public static implicit operator ushort(ProfilerCategory category) { return category.m_CategoryId; } } [Flags] public enum ProfilerCategoryFlags : ushort { None = 0, Builtin = 1 } public enum ProfilerCategoryColor : ushort { Render, Scripts, BurstJobs, Other, Physics, Animation, Audio, AudioJob, AudioUpdateJob, Lighting, GC, VSync, Memory, Internal, UI, Build, Input } [IgnoredByDeepProfiler] [UsedByNativeCode] public struct ProfilerMarker { [UsedByNativeCode] [IgnoredByDeepProfiler] public struct AutoScope : IDisposable { [NativeDisableUnsafePtrRestriction] internal readonly IntPtr m_Ptr; [MethodImpl(MethodImplOptions.AggressiveInlining)] internal AutoScope(IntPtr markerPtr) { m_Ptr = markerPtr; if (m_Ptr != IntPtr.Zero) { ProfilerUnsafeUtility.BeginSample(markerPtr); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Dispose() { if (m_Ptr != IntPtr.Zero) { ProfilerUnsafeUtility.EndSample(m_Ptr); } } } [NonSerialized] [NativeDisableUnsafePtrRestriction] internal readonly IntPtr m_Ptr; public IntPtr Handle => m_Ptr; [MethodImpl(MethodImplOptions.AggressiveInlining)] public ProfilerMarker(string name) { m_Ptr = ProfilerUnsafeUtility.CreateMarker(name, 1, MarkerFlags.Default, 0); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe ProfilerMarker(char* name, int nameLen) { m_Ptr = ProfilerUnsafeUtility.CreateMarker(name, nameLen, 1, MarkerFlags.Default, 0); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ProfilerMarker(ProfilerCategory category, string name) { m_Ptr = ProfilerUnsafeUtility.CreateMarker(name, category, MarkerFlags.Default, 0); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe ProfilerMarker(ProfilerCategory category, char* name, int nameLen) { m_Ptr = ProfilerUnsafeUtility.CreateMarker(name, nameLen, category, MarkerFlags.Default, 0); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ProfilerMarker(ProfilerCategory category, string name, MarkerFlags flags) { m_Ptr = ProfilerUnsafeUtility.CreateMarker(name, category, flags, 0); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe ProfilerMarker(ProfilerCategory category, char* name, int nameLen, MarkerFlags flags) { m_Ptr = ProfilerUnsafeUtility.CreateMarker(name, nameLen, category, flags, 0); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Pure] [Conditional("ENABLE_PROFILER")] public void Begin() { ProfilerUnsafeUtility.BeginSample(m_Ptr); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Conditional("ENABLE_PROFILER")] public void Begin(UnityEngine.Object contextUnityObject) { ProfilerUnsafeUtility.Internal_BeginWithObject(m_Ptr, contextUnityObject); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Conditional("ENABLE_PROFILER")] [Pure] public void End() { ProfilerUnsafeUtility.EndSample(m_Ptr); } [Conditional("ENABLE_PROFILER")] internal void GetName(ref string name) { name = ProfilerUnsafeUtility.Internal_GetName(m_Ptr); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Pure] public AutoScope Auto() { return new AutoScope(m_Ptr); } } public enum ProfilerFlowEventType : byte { Begin, ParallelNext, End, Next } public enum ProfilerMarkerDataUnit : byte { Undefined, TimeNanoseconds, Bytes, Count, Percent, FrequencyHz } [Flags] public enum ProfilerCounterOptions : ushort { None = 0, FlushOnEndOfFrame = 2, ResetToZeroOnFlush = 4 } internal struct ProfilerMarkerWithStringData { public struct AutoScope : IDisposable { private IntPtr _marker; [MethodImpl(MethodImplOptions.AggressiveInlining)] internal AutoScope(IntPtr marker) { _marker = marker; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Pure] public void Dispose() { if (_marker != IntPtr.Zero) { ProfilerUnsafeUtility.EndSample(_marker); } } } private const MethodImplOptions AggressiveInlining = MethodImplOptions.AggressiveInlining; private IntPtr _marker; public static ProfilerMarkerWithStringData Create(string name, string parameterName) { IntPtr intPtr = ProfilerUnsafeUtility.CreateMarker(name, 16, MarkerFlags.Default, 1); ProfilerUnsafeUtility.SetMarkerMetadata(intPtr, 0, parameterName, 9, 0); return new ProfilerMarkerWithStringData { _marker = intPtr }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Pure] public AutoScope Auto(bool enabled, Func<string> parameterValue) { if (enabled) { return Auto(parameterValue()); } return new AutoScope(IntPtr.Zero); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Pure] public unsafe AutoScope Auto(string value) { if (value == null) { throw new ArgumentNullException("value"); } fixed (char* ptr = value) { ProfilerMarkerData profilerMarkerData = new ProfilerMarkerData { Type = 9, Size = (uint)(value.Length * 2 + 2) }; profilerMarkerData.Ptr = ptr; ProfilerUnsafeUtility.BeginSampleWithMetadata(_marker, 1, &profilerMarkerData); } return new AutoScope(_marker); } } [Flags] public enum ProfilerRecorderOptions { None = 0, StartImmediately = 1, KeepAliveDuringDomainReload = 2, CollectOnlyOnCurrentThread = 4, WrapAroundWhenCapacityReached = 8, SumAllSamplesInFrame = 0x10, GpuRecorder = 0x40, Default = 0x18 } [DebuggerDisplay("Value = {Value}; Count = {Count}")] [UsedByNativeCode] public struct ProfilerRecorderSample { private long value; private long count; private long refValue; public long Value => value; public long Count => count; } [DebuggerDisplay("Count = {Count}")] [NativeHeader("Runtime/Profiler/ScriptBindings/ProfilerRecorder.bindings.h")] [DebuggerTypeProxy(typeof(ProfilerRecorderDebugView))] [UsedByNativeCode] public struct ProfilerRecorder : IDisposable { internal enum ControlOptions { Start = 0, Stop = 1, Reset = 2, Release = 4, SetFilterToCurrentThread = 5, SetToCollectFromAllThreads = 6 } internal enum CountOptions { Count, MaxCount } internal ulong handle; internal const ProfilerRecorderOptions SharedRecorder = (ProfilerRecorderOptions)128; public bool Valid => handle != 0L && GetValid(this); public ProfilerMarkerDataType DataType { get { CheckInitializedAndThrow(); return GetValueDataType(this); } } public ProfilerMarkerDataUnit UnitType { get { CheckInitializedAndThrow(); return GetValueUnitType(this); } } public long CurrentValue { get { CheckInitializedAndThrow(); return GetCurrentValue(this); } } public double CurrentValueAsDouble { get { CheckInitializedAndThrow(); return GetCurrentValueAsDouble(this); } } public long LastValue { get { CheckInitializedAndThrow(); return GetLastValue(this); } } public double LastValueAsDouble { get { CheckInitializedAndThrow(); return GetLastValueAsDouble(this); } } public int Capacity { get { CheckInitializedAndThrow(); return GetCount(this, CountOptions.MaxCount); } } public int Count { get { CheckInitializedAndThrow(); return GetCount(this, CountOptions.Count); } } public bool IsRunning { get { CheckInitializedAndThrow(); return GetRunning(this); } } public bool WrappedAround { get { CheckInitializedAndThrow(); return GetWrapped(this); } } internal ProfilerRecorder(ProfilerRecorderOptions options) { this = Create(default(ProfilerRecorderHandle), 0, options); } public ProfilerRecorder(string statName, int capacity = 1, ProfilerRecorderOptions options = ProfilerRecorderOptions.Default) : this(ProfilerCategory.Any, statName, capacity, options) { } public ProfilerRecorder(string categoryName, string statName, int capacity = 1, ProfilerRecorderOptions options = ProfilerRecorderOptions.Default) : this(new ProfilerCategory(categoryName), statName, capacity, options) { } public ProfilerRecorder(ProfilerCategory category, string statName, int capacity = 1, ProfilerRecorderOptions options = ProfilerRecorderOptions.Default) { ProfilerRecorderHandle byName = ProfilerRecorderHandle.GetByName(category, statName); this = Create(byName, capacity, options); } public unsafe ProfilerRecorder(ProfilerCategory category, char* statName, int statNameLen, int capacity = 1, ProfilerRecorderOptions options = ProfilerRecorderOptions.Default) { ProfilerRecorderHandle byName = ProfilerRecorderHandle.GetByName(category, statName, statNameLen); this = Create(byName, capacity, options); } public ProfilerRecorder(ProfilerMarker marker, int capacity = 1, ProfilerRecorderOptions options = ProfilerRecorderOptions.Default) { this = Create(ProfilerRecorderHandle.Get(marker), capacity, options); } public ProfilerRecorder(ProfilerRecorderHandle statHandle, int capacity = 1, ProfilerRecorderOptions options = ProfilerRecorderOptions.Default) { this = Create(statHandle, capacity, options); } public unsafe static ProfilerRecorder StartNew(ProfilerCategory category, string statName, int capacity = 1, ProfilerRecorderOptions options = ProfilerRecorderOptions.Default) { fixed (char* statName2 = statName) { return new ProfilerRecorder(category, statName2, statName.Length, capacity, options | ProfilerRecorderOptions.StartImmediately); } } public static ProfilerRecorder StartNew(ProfilerMarker marker, int capacity = 1, ProfilerRecorderOptions options = ProfilerRecorderOptions.Default) { return new ProfilerRecorder(marker, capacity, options | ProfilerRecorderOptions.StartImmediately); } internal static ProfilerRecorder StartNew() { return Create(default(ProfilerRecorderHandle), 0, ProfilerRecorderOptions.StartImmediately); } public void Start() { CheckInitializedAndThr