using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.ConsoleUtil; using BepInEx.Logging; using BepInEx.Unix; using HarmonyLib; using HarmonyLib.Tools; using Microsoft.Win32.SafeHandles; using Mono.Cecil; using MonoMod.Utils; using UnityEngine; using UnityInjector.ConsoleUtil; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: ComVisible(false)] [assembly: Guid("4ffba620-f5ed-47f9-b90c-dad1316fd9b9")] [assembly: InternalsVisibleTo("BepInEx.Preloader")] [assembly: InternalsVisibleTo("BepInExTests")] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("BepInEx")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyCopyright("Copyright © Bepis 2018")] [assembly: AssemblyDescription("Unity plugin injection framework")] [assembly: AssemblyFileVersion("5.4.23.2")] [assembly: AssemblyInformationalVersion("5.4.23.2+9cfc06ef463876e0f463f6f9a84c92d7ac346989")] [assembly: AssemblyProduct("BepInEx")] [assembly: AssemblyTitle("BepInEx")] [assembly: AssemblyVersion("5.4.23.2")] namespace UnityEngine { internal sealed class UnityLogWriter { [MethodImpl(MethodImplOptions.InternalCall)] public static extern void WriteStringToUnityLogImpl(string s); [MethodImpl(MethodImplOptions.InternalCall)] public static extern void WriteStringToUnityLog(string s); } } namespace UnityInjector.ConsoleUtil { internal static class SafeConsole { private delegate ConsoleColor GetColorDelegate(); private delegate void SetColorDelegate(ConsoleColor value); private delegate string GetStringDelegate(); private delegate void SetStringDelegate(string value); private static GetColorDelegate _getBackgroundColor; private static SetColorDelegate _setBackgroundColor; private static GetColorDelegate _getForegroundColor; private static SetColorDelegate _setForegroundColor; private static GetStringDelegate _getTitle; private static SetStringDelegate _setTitle; public static bool BackgroundColorExists { get; private set; } public static ConsoleColor BackgroundColor { get { return _getBackgroundColor(); } set { _setBackgroundColor(value); } } public static bool ForegroundColorExists { get; private set; } public static ConsoleColor ForegroundColor { get { return _getForegroundColor(); } set { _setForegroundColor(value); } } public static bool TitleExists { get; private set; } public static string Title { get { return _getTitle(); } set { _setTitle(value); } } static SafeConsole() { Type typeFromHandle = typeof(Console); InitColors(typeFromHandle); } private static void InitColors(Type tConsole) { MethodInfo method = tConsole.GetMethod("get_ForegroundColor", BindingFlags.Static | BindingFlags.Public); MethodInfo method2 = tConsole.GetMethod("set_ForegroundColor", BindingFlags.Static | BindingFlags.Public); MethodInfo method3 = tConsole.GetMethod("get_BackgroundColor", BindingFlags.Static | BindingFlags.Public); MethodInfo method4 = tConsole.GetMethod("set_BackgroundColor", BindingFlags.Static | BindingFlags.Public); MethodInfo method5 = tConsole.GetMethod("get_Title", BindingFlags.Static | BindingFlags.Public); MethodInfo method6 = tConsole.GetMethod("set_Title", BindingFlags.Static | BindingFlags.Public); _setForegroundColor = ((method2 != null) ? ((SetColorDelegate)Delegate.CreateDelegate(typeof(SetColorDelegate), method2)) : ((SetColorDelegate)delegate { })); _setBackgroundColor = ((method4 != null) ? ((SetColorDelegate)Delegate.CreateDelegate(typeof(SetColorDelegate), method4)) : ((SetColorDelegate)delegate { })); _getForegroundColor = ((method != null) ? ((GetColorDelegate)Delegate.CreateDelegate(typeof(GetColorDelegate), method)) : ((GetColorDelegate)(() => ConsoleColor.Gray))); _getBackgroundColor = ((method3 != null) ? ((GetColorDelegate)Delegate.CreateDelegate(typeof(GetColorDelegate), method3)) : ((GetColorDelegate)(() => ConsoleColor.Black))); _getTitle = ((method5 != null) ? ((GetStringDelegate)Delegate.CreateDelegate(typeof(GetStringDelegate), method5)) : ((GetStringDelegate)(() => string.Empty))); _setTitle = ((method6 != null) ? ((SetStringDelegate)Delegate.CreateDelegate(typeof(SetStringDelegate), method6)) : ((SetStringDelegate)delegate { })); BackgroundColorExists = _setBackgroundColor != null && _getBackgroundColor != null; ForegroundColorExists = _setForegroundColor != null && _getForegroundColor != null; TitleExists = _setTitle != null && _getTitle != null; } } internal class ConsoleEncoding : Encoding { private byte[] _byteBuffer = new byte[256]; private char[] _charBuffer = new char[256]; private byte[] _zeroByte = new byte[0]; private char[] _zeroChar = new char[0]; private readonly uint _codePage; public override int CodePage => (int)_codePage; public static Encoding OutputEncoding => new ConsoleEncoding(ConsoleCodePage); public static uint ConsoleCodePage { get { return GetConsoleOutputCP(); } set { SetConsoleOutputCP(value); } } private void ExpandByteBuffer(int count) { if (_byteBuffer.Length < count) { _byteBuffer = new byte[count]; } } private void ExpandCharBuffer(int count) { if (_charBuffer.Length < count) { _charBuffer = new char[count]; } } private void ReadByteBuffer(byte[] bytes, int index, int count) { for (int i = 0; i < count; i++) { bytes[index + i] = _byteBuffer[i]; } } private void ReadCharBuffer(char[] chars, int index, int count) { for (int i = 0; i < count; i++) { chars[index + i] = _charBuffer[i]; } } private void WriteByteBuffer(byte[] bytes, int index, int count) { ExpandByteBuffer(count); for (int i = 0; i < count; i++) { _byteBuffer[i] = bytes[index + i]; } } private void WriteCharBuffer(char[] chars, int index, int count) { ExpandCharBuffer(count); for (int i = 0; i < count; i++) { _charBuffer[i] = chars[index + i]; } } public static uint GetActiveCodePage() { return GetACP(); } private ConsoleEncoding(uint codePage) { _codePage = codePage; } public static ConsoleEncoding GetEncoding(uint codePage) { return new ConsoleEncoding(codePage); } public override int GetByteCount(char[] chars, int index, int count) { WriteCharBuffer(chars, index, count); return WideCharToMultiByte(_codePage, 0u, _charBuffer, count, _zeroByte, 0, IntPtr.Zero, IntPtr.Zero); } public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { int byteCount = GetByteCount(chars, charIndex, charCount); WriteCharBuffer(chars, charIndex, charCount); ExpandByteBuffer(byteCount); int result = WideCharToMultiByte(_codePage, 0u, chars, charCount, _byteBuffer, byteCount, IntPtr.Zero, IntPtr.Zero); ReadByteBuffer(bytes, byteIndex, byteCount); return result; } public override int GetCharCount(byte[] bytes, int index, int count) { WriteByteBuffer(bytes, index, count); return MultiByteToWideChar(_codePage, 0u, bytes, count, _zeroChar, 0); } public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { int charCount = GetCharCount(bytes, byteIndex, byteCount); WriteByteBuffer(bytes, byteIndex, byteCount); ExpandCharBuffer(charCount); int result = MultiByteToWideChar(_codePage, 0u, bytes, byteCount, _charBuffer, charCount); ReadCharBuffer(chars, charIndex, charCount); return result; } public override int GetMaxByteCount(int charCount) { return charCount * 2; } public override int GetMaxCharCount(int byteCount) { return byteCount; } [DllImport("kernel32.dll")] private static extern uint GetConsoleOutputCP(); [DllImport("kernel32.dll")] private static extern uint GetACP(); [DllImport("kernel32.dll", SetLastError = true)] private static extern int MultiByteToWideChar(uint codePage, uint dwFlags, [In][MarshalAs(UnmanagedType.LPArray)] byte[] lpMultiByteStr, int cbMultiByte, [Out][MarshalAs(UnmanagedType.LPWStr)] char[] lpWideCharStr, int cchWideChar); [DllImport("kernel32.dll")] private static extern IntPtr SetConsoleOutputCP(uint codepage); [DllImport("kernel32.dll", SetLastError = true)] private static extern int WideCharToMultiByte(uint codePage, uint dwFlags, [In][MarshalAs(UnmanagedType.LPWStr)] char[] lpWideCharStr, int cchWideChar, [Out][MarshalAs(UnmanagedType.LPArray)] byte[] lpMultiByteStr, int cbMultiByte, IntPtr lpDefaultChar, IntPtr lpUsedDefaultChar); } internal class ConsoleWindow { [UnmanagedFunctionPointer(CallingConvention.Winapi)] [return: MarshalAs(UnmanagedType.Bool)] private delegate bool SetForegroundWindowDelegate(IntPtr hWnd); [UnmanagedFunctionPointer(CallingConvention.Winapi)] private delegate IntPtr GetForegroundWindowDelegate(); [UnmanagedFunctionPointer(CallingConvention.Winapi)] private delegate IntPtr GetSystemMenuDelegate(IntPtr hwnd, bool bRevert); [UnmanagedFunctionPointer(CallingConvention.Winapi)] private delegate bool DeleteMenuDelegate(IntPtr hMenu, uint uPosition, uint uFlags); private const uint SC_CLOSE = 61536u; private const uint MF_BYCOMMAND = 0u; private const uint LOAD_LIBRARY_SEARCH_SYSTEM32 = 2048u; public static IntPtr ConsoleOutHandle; public static IntPtr OriginalStdoutHandle; private static bool methodsInited; private static SetForegroundWindowDelegate setForeground; private static GetForegroundWindowDelegate getForeground; private static GetSystemMenuDelegate getSystemMenu; private static DeleteMenuDelegate deleteMenu; public static bool IsAttached { get; private set; } public static string Title { set { if (IsAttached) { if (value == null) { throw new ArgumentNullException("value"); } if (value.Length > 24500) { throw new InvalidOperationException("Console title too long"); } if (!SetConsoleTitle(value)) { throw new InvalidOperationException("Console title invalid"); } } } } public static void Attach() { if (!IsAttached) { Initialize(); if (OriginalStdoutHandle == IntPtr.Zero) { OriginalStdoutHandle = GetStdHandle(-11); } IntPtr hWnd = getForeground(); IntPtr consoleWindow = GetConsoleWindow(); if (GetConsoleWindow() == IntPtr.Zero && !AllocConsole()) { throw new Exception("AllocConsole() failed"); } setForeground(hWnd); ConsoleOutHandle = CreateFile("CONOUT$", 3221225472u, 2, IntPtr.Zero, 3, 0, IntPtr.Zero); Kon.conOut = ConsoleOutHandle; if (!SetStdHandle(-11, ConsoleOutHandle)) { throw new Exception("SetStdHandle() failed"); } if (OriginalStdoutHandle != IntPtr.Zero && ConsoleManager.ConfigConsoleOutRedirectType.Value == ConsoleManager.ConsoleOutRedirectType.ConsoleOut) { CloseHandle(OriginalStdoutHandle); } IsAttached = true; } } public static void PreventClose() { if (IsAttached) { Initialize(); IntPtr consoleWindow = GetConsoleWindow(); IntPtr intPtr = getSystemMenu(consoleWindow, bRevert: false); if (intPtr != IntPtr.Zero) { deleteMenu(intPtr, 61536u, 0u); } } } public static void Detach() { if (IsAttached) { if (!CloseHandle(ConsoleOutHandle)) { throw new Exception("CloseHandle() failed"); } ConsoleOutHandle = IntPtr.Zero; if (!FreeConsole()) { throw new Exception("FreeConsole() failed"); } if (!SetStdHandle(-11, OriginalStdoutHandle)) { throw new Exception("SetStdHandle() failed"); } IsAttached = false; } } private static void Initialize() { if (!methodsInited) { methodsInited = true; IntPtr hModule = LoadLibraryEx("user32.dll", IntPtr.Zero, 2048u); setForeground = DynDll.AsDelegate(GetProcAddress(hModule, "SetForegroundWindow")); getForeground = DynDll.AsDelegate(GetProcAddress(hModule, "GetForegroundWindow")); getSystemMenu = DynDll.AsDelegate(GetProcAddress(hModule, "GetSystemMenu")); deleteMenu = DynDll.AsDelegate(GetProcAddress(hModule, "DeleteMenu")); } } [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr GetProcAddress(IntPtr hModule, string procName); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool AllocConsole(); [DllImport("kernel32.dll")] private static extern IntPtr GetConsoleWindow(); [DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)] private static extern bool CloseHandle(IntPtr handle); [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern IntPtr CreateFile(string fileName, uint desiredAccess, int shareMode, IntPtr securityAttributes, int creationDisposition, int flagsAndAttributes, IntPtr templateFile); [DllImport("kernel32.dll")] private static extern bool FreeConsole(); [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr GetStdHandle(int nStdHandle); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool SetStdHandle(int nStdHandle, IntPtr hConsoleOutput); [DllImport("kernel32.dll", BestFitMapping = true, CharSet = CharSet.Auto, SetLastError = true)] private static extern bool SetConsoleTitle(string title); [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr LoadLibraryEx(string lpLibFileName, IntPtr hFile, uint dwFlags); } } namespace BepInEx { internal static class ConsoleManager { public enum ConsoleOutRedirectType { [Description("Auto")] Auto, [Description("Console Out")] ConsoleOut, [Description("Standard Out")] StandardOut } private const uint SHIFT_JIS_CP = 932u; private static readonly bool? EnableConsoleArgOverride; private const string ENABLE_CONSOLE_ARG = "--enable-console"; public static readonly ConfigEntry ConfigConsoleEnabled; public static readonly ConfigEntry ConfigPreventClose; public static readonly ConfigEntry ConfigConsoleShiftJis; public static readonly ConfigEntry ConfigConsoleOutRedirectType; internal static IConsoleDriver Driver { get; set; } public static bool ConsoleActive => Driver?.ConsoleActive ?? false; public static TextWriter StandardOutStream => Driver?.StandardOut; public static TextWriter ConsoleStream => Driver?.ConsoleOut; public static bool ConsoleEnabled => EnableConsoleArgOverride ?? ConfigConsoleEnabled.Value; static ConsoleManager() { ConfigConsoleEnabled = ConfigFile.CoreConfig.Bind("Logging.Console", "Enabled", defaultValue: false, "Enables showing a console for log output."); ConfigPreventClose = ConfigFile.CoreConfig.Bind("Logging.Console", "PreventClose", defaultValue: false, "If enabled, will prevent closing the console (either by deleting the close button or in other platform-specific way)."); ConfigConsoleShiftJis = ConfigFile.CoreConfig.Bind("Logging.Console", "ShiftJisEncoding", defaultValue: false, "If true, console is set to the Shift-JIS encoding, otherwise UTF-8 encoding."); ConfigConsoleOutRedirectType = ConfigFile.CoreConfig.Bind("Logging.Console", "StandardOutType", ConsoleOutRedirectType.Auto, new StringBuilder().AppendLine("Hints console manager on what handle to assign as StandardOut. Possible values:").AppendLine("Auto - lets BepInEx decide how to redirect console output").AppendLine("ConsoleOut - prefer redirecting to console output; if possible, closes original standard output") .AppendLine("StandardOut - prefer redirecting to standard output; if possible, closes console out") .ToString()); try { string[] commandLineArgs = Environment.GetCommandLineArgs(); for (int i = 0; i < commandLineArgs.Length; i++) { string text = commandLineArgs[i]; if (text == "--enable-console" && i + 1 < commandLineArgs.Length && bool.TryParse(commandLineArgs[i + 1], out var result)) { EnableConsoleArgOverride = result; } } } catch (Exception) { } } public static void Initialize(bool alreadyActive) { if (PlatformHelper.Is((Platform)8)) { Driver = new LinuxConsoleDriver(); } else if (PlatformHelper.Is((Platform)37)) { Driver = new WindowsConsoleDriver(); } Driver.Initialize(alreadyActive); } private static void DriverCheck() { if (Driver == null) { throw new InvalidOperationException("Driver has not been initialized"); } } public static void CreateConsole() { if (!ConsoleActive) { DriverCheck(); uint codepage = (ConfigConsoleShiftJis.Value ? 932u : ((uint)Encoding.UTF8.CodePage)); Driver.CreateConsole(codepage); if (ConfigPreventClose.Value) { Driver.PreventClose(); } } } public static void DetachConsole() { if (ConsoleActive) { DriverCheck(); Driver.DetachConsole(); } } public static void SetConsoleTitle(string title) { DriverCheck(); Driver.SetConsoleTitle(title); } public static void SetConsoleColor(ConsoleColor color) { DriverCheck(); Driver.SetConsoleColor(color); } } internal interface IConsoleDriver { TextWriter StandardOut { get; } TextWriter ConsoleOut { get; } bool ConsoleActive { get; } bool ConsoleIsExternal { get; } void PreventClose(); void Initialize(bool alreadyActive); void CreateConsole(uint codepage); void DetachConsole(); void SetConsoleColor(ConsoleColor color); void SetConsoleTitle(string title); } internal class WindowsConsoleDriver : IConsoleDriver { private static readonly ConstructorInfo FileStreamCtor = new ConstructorInfo[2] { AccessTools.Constructor(typeof(FileStream), new Type[2] { typeof(SafeFileHandle), typeof(FileAccess) }, false), AccessTools.Constructor(typeof(FileStream), new Type[2] { typeof(IntPtr), typeof(FileAccess) }, false) }.FirstOrDefault((ConstructorInfo m) => m != null); public TextWriter StandardOut { get; private set; } public TextWriter ConsoleOut { get; private set; } public bool ConsoleActive { get; private set; } public bool ConsoleIsExternal => true; public void PreventClose() { ConsoleWindow.PreventClose(); } public void Initialize(bool alreadyActive) { ConsoleActive = alreadyActive; StandardOut = Console.Out; } private static FileStream OpenFileStream(IntPtr handle) { SafeFileHandle safeFileHandle = new SafeFileHandle(handle, ownsHandle: false); object[] args = AccessTools.ActualParameters((MethodBase)FileStreamCtor, new object[3] { safeFileHandle, safeFileHandle.DangerousGetHandle(), FileAccess.Write }); return (FileStream)Activator.CreateInstance(typeof(FileStream), args); } public void CreateConsole(uint codepage) { ConsoleWindow.Attach(); ConsoleEncoding.ConsoleCodePage = codepage; IntPtr outHandle = GetOutHandle(); if (outHandle == IntPtr.Zero) { StandardOut = TextWriter.Null; ConsoleOut = TextWriter.Null; return; } FileStream stream = OpenFileStream(outHandle); StandardOut = new StreamWriter(stream, Utility.UTF8NoBom) { AutoFlush = true }; FileStream stream2 = OpenFileStream(ConsoleWindow.ConsoleOutHandle); ConsoleOut = new StreamWriter(stream2, ConsoleEncoding.OutputEncoding) { AutoFlush = true }; ConsoleActive = true; } private IntPtr GetOutHandle() { return ConsoleManager.ConfigConsoleOutRedirectType.Value switch { ConsoleManager.ConsoleOutRedirectType.ConsoleOut => ConsoleWindow.ConsoleOutHandle, ConsoleManager.ConsoleOutRedirectType.StandardOut => ConsoleWindow.OriginalStdoutHandle, _ => (ConsoleWindow.OriginalStdoutHandle != IntPtr.Zero) ? ConsoleWindow.OriginalStdoutHandle : ConsoleWindow.ConsoleOutHandle, }; } public void DetachConsole() { ConsoleWindow.Detach(); ConsoleOut.Close(); ConsoleOut = null; ConsoleActive = false; } public void SetConsoleColor(ConsoleColor color) { SafeConsole.ForegroundColor = color; Kon.ForegroundColor = color; } public void SetConsoleTitle(string title) { ConsoleWindow.Title = title; } } [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public class BepInPlugin : Attribute { public string GUID { get; protected set; } public string Name { get; protected set; } public Version Version { get; protected set; } public BepInPlugin(string GUID, string Name, string Version) { this.GUID = GUID; this.Name = Name; try { this.Version = new Version(Version); } catch { this.Version = null; } } internal static BepInPlugin FromCecilType(TypeDefinition td) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) CustomAttribute val = MetadataHelper.GetCustomAttributes(td, inherit: false).FirstOrDefault(); if (val == null) { return null; } CustomAttributeArgument val2 = val.ConstructorArguments[0]; string gUID = (string)((CustomAttributeArgument)(ref val2)).Value; val2 = val.ConstructorArguments[1]; string name = (string)((CustomAttributeArgument)(ref val2)).Value; val2 = val.ConstructorArguments[2]; return new BepInPlugin(gUID, name, (string)((CustomAttributeArgument)(ref val2)).Value); } } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class BepInDependency : Attribute, ICacheable { [Flags] public enum DependencyFlags { HardDependency = 1, SoftDependency = 2 } public string DependencyGUID { get; protected set; } public DependencyFlags Flags { get; protected set; } public Version MinimumVersion { get; protected set; } public BepInDependency(string DependencyGUID, DependencyFlags Flags = DependencyFlags.HardDependency) { this.DependencyGUID = DependencyGUID; this.Flags = Flags; MinimumVersion = new Version(); } public BepInDependency(string DependencyGUID, string MinimumDependencyVersion) : this(DependencyGUID) { MinimumVersion = new Version(MinimumDependencyVersion); } internal static IEnumerable FromCecilType(TypeDefinition td) { IEnumerable customAttributes = MetadataHelper.GetCustomAttributes(td, inherit: true); return customAttributes.Select(delegate(CustomAttribute customAttribute) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) CustomAttributeArgument val = customAttribute.ConstructorArguments[0]; string dependencyGUID = (string)((CustomAttributeArgument)(ref val)).Value; val = customAttribute.ConstructorArguments[1]; object value = ((CustomAttributeArgument)(ref val)).Value; return (value is string minimumDependencyVersion) ? new BepInDependency(dependencyGUID, minimumDependencyVersion) : new BepInDependency(dependencyGUID, (DependencyFlags)value); }).ToList(); } void ICacheable.Save(BinaryWriter bw) { bw.Write(DependencyGUID); bw.Write((int)Flags); bw.Write(MinimumVersion.ToString()); } void ICacheable.Load(BinaryReader br) { DependencyGUID = br.ReadString(); Flags = (DependencyFlags)br.ReadInt32(); MinimumVersion = new Version(br.ReadString()); } } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class BepInIncompatibility : Attribute, ICacheable { public string IncompatibilityGUID { get; protected set; } public BepInIncompatibility(string IncompatibilityGUID) { this.IncompatibilityGUID = IncompatibilityGUID; } internal static IEnumerable FromCecilType(TypeDefinition td) { IEnumerable customAttributes = MetadataHelper.GetCustomAttributes(td, inherit: true); return customAttributes.Select(delegate(CustomAttribute customAttribute) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) CustomAttributeArgument val = customAttribute.ConstructorArguments[0]; string incompatibilityGUID = (string)((CustomAttributeArgument)(ref val)).Value; return new BepInIncompatibility(incompatibilityGUID); }).ToList(); } void ICacheable.Save(BinaryWriter bw) { bw.Write(IncompatibilityGUID); } void ICacheable.Load(BinaryReader br) { IncompatibilityGUID = br.ReadString(); } } [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class BepInProcess : Attribute { public string ProcessName { get; protected set; } public BepInProcess(string ProcessName) { this.ProcessName = ProcessName; } internal static List FromCecilType(TypeDefinition td) { IEnumerable customAttributes = MetadataHelper.GetCustomAttributes(td, inherit: true); return customAttributes.Select(delegate(CustomAttribute customAttribute) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) CustomAttributeArgument val = customAttribute.ConstructorArguments[0]; return new BepInProcess((string)((CustomAttributeArgument)(ref val)).Value); }).ToList(); } } public static class MetadataHelper { internal static IEnumerable GetCustomAttributes(TypeDefinition td, bool inherit) where T : Attribute { List list = new List(); Type type = typeof(T); TypeDefinition val = td; do { list.AddRange(((IEnumerable)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(Type pluginType) where T : Attribute { return (T[])pluginType.GetCustomAttributes(typeof(T), inherit: true); } public static IEnumerable GetAttributes(object plugin) where T : Attribute { return GetAttributes(plugin.GetType()); } public static IEnumerable GetDependencies(Type plugin) { return plugin.GetCustomAttributes(typeof(BepInDependency), inherit: true).Cast(); } } internal class BuildInfoAttribute : Attribute { public string Info { get; } public BuildInfoAttribute(string info) { Info = info; } } public abstract class BaseUnityPlugin : MonoBehaviour { public PluginInfo Info { get; } protected ManualLogSource Logger { get; } public ConfigFile Config { get; } protected BaseUnityPlugin() { BepInPlugin metadata = MetadataHelper.GetMetadata(this); if (metadata == null) { throw new InvalidOperationException("Can't create an instance of " + ((object)this).GetType().FullName + " because it inherits from BaseUnityPlugin and the BepInPlugin attribute is missing."); } if (!Chainloader.IsEditor && Chainloader.PluginInfos.TryGetValue(metadata.GUID, out var value)) { Info = value; } else { Info = new PluginInfo { Metadata = metadata, Instance = this, Dependencies = MetadataHelper.GetDependencies(((object)this).GetType()), Processes = MetadataHelper.GetAttributes(((object)this).GetType()), Location = ((object)this).GetType().Assembly.Location }; } Logger = BepInEx.Logging.Logger.CreateLogSource(metadata.Name); string text = (Chainloader.IsEditor ? "." : Paths.ConfigPath); Config = new ConfigFile(Utility.CombinePaths(text, metadata.GUID + ".cfg"), saveOnInit: false, metadata); } } public class PluginInfo : ICacheable { public BepInPlugin Metadata { get; internal set; } public IEnumerable Processes { get; internal set; } public IEnumerable Dependencies { get; internal set; } public IEnumerable Incompatibilities { get; internal set; } public string Location { get; internal set; } public BaseUnityPlugin Instance { get; internal set; } internal string TypeName { get; set; } internal Version TargettedBepInExVersion { get; set; } void ICacheable.Save(BinaryWriter bw) { bw.Write(TypeName); bw.Write(Metadata.GUID); bw.Write(Metadata.Name); bw.Write(Metadata.Version.ToString()); List list = Processes.ToList(); bw.Write(list.Count); foreach (BepInProcess item in list) { bw.Write(item.ProcessName); } List list2 = Dependencies.ToList(); bw.Write(list2.Count); foreach (BepInDependency item2 in list2) { ((ICacheable)item2).Save(bw); } List list3 = Incompatibilities.ToList(); bw.Write(list3.Count); foreach (BepInIncompatibility item3 in list3) { ((ICacheable)item3).Save(bw); } bw.Write(TargettedBepInExVersion.ToString(4)); } void ICacheable.Load(BinaryReader br) { TypeName = br.ReadString(); Metadata = new BepInPlugin(br.ReadString(), br.ReadString(), br.ReadString()); int num = br.ReadInt32(); List list = new List(num); for (int i = 0; i < num; i++) { list.Add(new BepInProcess(br.ReadString())); } Processes = list; int num2 = br.ReadInt32(); List list2 = new List(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 list3 = new List(num3); for (int k = 0; k < num3; k++) { BepInIncompatibility bepInIncompatibility = new BepInIncompatibility(""); ((ICacheable)bepInIncompatibility).Load(br); list3.Add(bepInIncompatibility); } Incompatibilities = list3; TargettedBepInExVersion = new Version(br.ReadString()); } public override string ToString() { return $"{Metadata?.Name} {Metadata?.Version}"; } } public static class Paths { public static string[] DllSearchPaths { get; private set; } public static string BepInExAssemblyDirectory { get; private set; } public static string BepInExAssemblyPath { get; private set; } public static string BepInExRootPath { get; private set; } public static string ExecutablePath { get; private set; } public static string GameRootPath { get; private set; } public static string ManagedPath { get; private set; } public static string ConfigPath { get; private set; } public static string BepInExConfigPath { get; private set; } public static string CachePath { get; private set; } public static string PatcherPluginPath { get; private set; } public static string PluginPath { get; private set; } public static string ProcessName { get; private set; } internal static void SetExecutablePath(string executablePath, string bepinRootPath = null, string managedPath = null, string[] dllSearchPath = null) { ExecutablePath = executablePath; ProcessName = Path.GetFileNameWithoutExtension(executablePath); GameRootPath = (PlatformHelper.Is((Platform)73) ? Utility.ParentDirectory(executablePath, 4) : Path.GetDirectoryName(executablePath)); ManagedPath = managedPath ?? Utility.CombinePaths(GameRootPath, ProcessName + "_Data", "Managed"); BepInExRootPath = bepinRootPath ?? Path.Combine(GameRootPath, "BepInEx"); ConfigPath = Path.Combine(BepInExRootPath, "config"); BepInExConfigPath = Path.Combine(ConfigPath, "BepInEx.cfg"); PluginPath = Path.Combine(BepInExRootPath, "plugins"); PatcherPluginPath = Path.Combine(BepInExRootPath, "patchers"); BepInExAssemblyDirectory = Path.Combine(BepInExRootPath, "core"); BepInExAssemblyPath = Path.Combine(BepInExAssemblyDirectory, Assembly.GetExecutingAssembly().GetName().Name + ".dll"); CachePath = Path.Combine(BepInExRootPath, "cache"); DllSearchPaths = (dllSearchPath ?? new string[0]).Concat(new string[1] { ManagedPath }).Distinct().ToArray(); } internal static void SetManagedPath(string managedPath) { if (managedPath != null) { ManagedPath = managedPath; } } internal static void SetPluginPath(string pluginPath) { PluginPath = Utility.CombinePaths(BepInExRootPath, pluginPath); } } public sealed class ThreadingHelper : MonoBehaviour, ISynchronizeInvoke { private sealed class InvokeResult : IAsyncResult { internal bool ExceptionThrown; public bool IsCompleted { get; private set; } public WaitHandle AsyncWaitHandle { get; } public object AsyncState { get; private set; } public bool CompletedSynchronously { get; private set; } public InvokeResult() { AsyncWaitHandle = new EventWaitHandle(initialState: false, EventResetMode.ManualReset); } public void Finish(object result, bool completedSynchronously) { AsyncState = result; CompletedSynchronously = completedSynchronously; IsCompleted = true; ((EventWaitHandle)AsyncWaitHandle).Set(); } } private readonly object _invokeLock = new object(); private Action _invokeList; private Thread _mainThread; public static ThreadingHelper Instance { get; private set; } public static ISynchronizeInvoke SynchronizingObject => Instance; public bool InvokeRequired => _mainThread == null || _mainThread != Thread.CurrentThread; internal static void Initialize() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected O, but got Unknown GameObject val = new GameObject("BepInEx_ThreadingHelper"); if (Chainloader.ConfigHideBepInExGOs.Value) { ((Object)val).hideFlags = (HideFlags)61; } Object.DontDestroyOnLoad((Object)(object)val); Instance = val.AddComponent(); } public void StartSyncInvoke(Action action) { if (action == null) { throw new ArgumentNullException("action"); } lock (_invokeLock) { _invokeList = (Action)Delegate.Combine(_invokeList, action); } } private void Update() { if (_mainThread == null) { _mainThread = Thread.CurrentThread; } if (_invokeList == null) { return; } Action invokeList; lock (_invokeLock) { invokeList = _invokeList; _invokeList = null; } foreach (Action item in invokeList.GetInvocationList().Cast()) { try { item(); } catch (Exception ex) { LogInvocationException(ex); } } } public void StartAsyncInvoke(Func action) { if (!ThreadPool.QueueUserWorkItem(DoWork)) { throw new NotSupportedException("Failed to queue the action on ThreadPool"); } void DoWork(object _) { try { Action action2 = action(); if (action2 != null) { StartSyncInvoke(action2); } } catch (Exception ex) { LogInvocationException(ex); } } } private static void LogInvocationException(Exception ex) { Logger.Log(LogLevel.Error, ex); if (ex.InnerException != null) { Logger.Log(LogLevel.Error, "INNER: " + ex.InnerException); } } IAsyncResult ISynchronizeInvoke.BeginInvoke(Delegate method, object[] args) { InvokeResult result = new InvokeResult(); if (!InvokeRequired) { result.Finish(Invoke(), completedSynchronously: true); } else { StartSyncInvoke(delegate { result.Finish(Invoke(), completedSynchronously: false); }); } return result; object Invoke() { try { return method.DynamicInvoke(args); } catch (Exception result2) { result.ExceptionThrown = true; return result2; } } } object ISynchronizeInvoke.EndInvoke(IAsyncResult result) { InvokeResult invokeResult = (InvokeResult)result; invokeResult.AsyncWaitHandle.WaitOne(); if (invokeResult.ExceptionThrown) { throw (Exception)invokeResult.AsyncState; } return invokeResult.AsyncState; } object ISynchronizeInvoke.Invoke(Delegate method, object[] args) { IAsyncResult result = ((ISynchronizeInvoke)this).BeginInvoke(method, args); return ((ISynchronizeInvoke)this).EndInvoke(result); } } public static class ThreadingExtensions { public static IEnumerable RunParallel(this IEnumerable data, Func work, int workerCount = -1) { foreach (TOut item in data.ToList().RunParallel(work)) { yield return item; } } public static IEnumerable RunParallel(this IList data, Func 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 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 list = new List(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 enumerable; if (doneItems != null) { enumerable = list.Concat(doneItems); } else { IEnumerable enumerable2 = list; enumerable = enumerable2; } doneItems = enumerable; int num = doneCount; doneCount = num + 1; are.Set(); } }); } while (true) { are.WaitOne(); IEnumerable toOutput; bool isDone; lock (lockObj) { toOutput = doneItems; doneItems = null; isDone = doneCount == workerCount; } if (toOutput != null) { foreach (TOut item in toOutput) { yield return item; } } if (isDone) { break; } toOutput = null; } if (exceptionThrown != null) { throw new TargetInvocationException("An exception was thrown inside one of the threads", exceptionThrown); } } } public static class UnityInput { private static IInputSystem _current; public static IInputSystem Current { get { if (_current != null) { return _current; } try { try { Input.GetKeyDown((KeyCode)97); _current = new LegacyInputSystem(); Logger.LogDebug("[UnityInput] Using LegacyInputSystem"); } catch (InvalidOperationException) { _current = new NewInputSystem(); Logger.LogDebug("[UnityInput] Using NewInputSystem"); } } catch (Exception arg) { Logger.LogWarning($"[UnityInput] Failed to detect available input systems - {arg}"); _current = new NullInputSystem(); } return _current; } } public static bool LegacyInputSystemAvailable => Current is LegacyInputSystem; } public interface IInputSystem { Vector3 mousePosition { get; } Vector2 mouseScrollDelta { get; } bool mousePresent { get; } bool anyKey { get; } bool anyKeyDown { get; } IEnumerable SupportedKeyCodes { get; } bool GetKey(string name); bool GetKey(KeyCode key); bool GetKeyDown(string name); bool GetKeyDown(KeyCode key); bool GetKeyUp(string name); bool GetKeyUp(KeyCode key); bool GetMouseButton(int button); bool GetMouseButtonDown(int button); bool GetMouseButtonUp(int button); void ResetInputAxes(); } internal class NewInputSystem : IInputSystem { private delegate bool GetButtonDelegate(KeyCode key); private delegate Vector2 GetMouseVectorDelegate(); private delegate bool GetMouseStateDelegate(); private static bool initialized; private static readonly Dictionary keyCodeToIndex = new Dictionary(); private static readonly Dictionary keyToKeyCodeNameRemap = new Dictionary { ["LeftCtrl"] = "LeftControl", ["RightCtrl"] = "RightControl", ["LeftMeta"] = "LeftApple", ["RightMeta"] = "RightApple", ["ContextMenu"] = "Menu", ["PrintScreen"] = "Print", ["Enter"] = "Return" }; private static GetButtonDelegate _getKey; private static GetButtonDelegate _getKeyDown; private static GetButtonDelegate _getKeyUp; private static GetButtonDelegate _getMouseButton; private static GetButtonDelegate _getMouseButtonDown; private static GetButtonDelegate _getMouseButtonUp; private static GetMouseVectorDelegate _getMousePosition; private static GetMouseVectorDelegate _getMouseScrollDelta; private static GetMouseStateDelegate _getMousePresent; private static GetMouseStateDelegate _getKeyboardAnyKeyIsPressed; private static GetMouseStateDelegate _getKeyboardAnyKeyWasPressedThisFrame; public Vector3 mousePosition => Vector2.op_Implicit(_getMousePosition()); public Vector2 mouseScrollDelta => _getMouseScrollDelta(); public bool mousePresent => _getMousePresent(); public bool anyKey { get { if (_getKeyboardAnyKeyIsPressed()) { return true; } return GetMouseButton(0) || GetMouseButton(1) || GetMouseButton(2) || GetMouseButton(3) || GetMouseButton(4); } } public bool anyKeyDown { get { if (_getKeyboardAnyKeyWasPressedThisFrame()) { return true; } return GetMouseButtonDown(0) || GetMouseButtonDown(1) || GetMouseButtonDown(2) || GetMouseButtonDown(3) || GetMouseButtonDown(4); } } public IEnumerable SupportedKeyCodes => keyCodeToIndex.Keys.ToArray(); public NewInputSystem() { Init(); } private static void Init() { //IL_02d3: Unknown result type (might be due to invalid IL or missing references) //IL_02da: Expected O, but got Unknown //IL_00d7: Unknown result type (might be due to invalid IL or missing references) if (initialized) { return; } Assembly assembly = Assembly.Load("Unity.InputSystem"); Type type = assembly.GetType("UnityEngine.InputSystem.Key"); foreach (object value3 in Enum.GetValues(type)) { string text = value3.ToString(); int value = (int)value3; string value2; if (text.StartsWith("Numpad")) { text = text.Replace("Numpad", "Keypad"); } else if (text.StartsWith("Digit")) { text = text.Replace("Digit", "Alpha"); } else if (keyToKeyCodeNameRemap.TryGetValue(text, out value2)) { text = value2; } if (TryEnumParse(text, out var val)) { keyCodeToIndex[val] = value; } else { Logger.LogDebug("[UnityInput] Unknown key name: " + text + ", skipping remapping"); } } FieldInfo keyCodeToIndexField = AccessTools.Field(typeof(NewInputSystem), "keyCodeToIndex"); MethodInfo tryGetValueMethod = AccessTools.Method(typeof(Dictionary), "TryGetValue", (Type[])null, (Type[])null); Type type2 = assembly.GetType("UnityEngine.InputSystem.Keyboard"); MethodInfo currentProperty = AccessTools.PropertyGetter(type2, "current"); MethodInfo indexer = AccessTools.Method(type2, "get_Item", new Type[1] { type }, (Type[])null); Type buttonControlType = assembly.GetType("UnityEngine.InputSystem.Controls.ButtonControl"); _getKey = GenerateKeyGetter("InputSystemGetKey", "isPressed"); _getKeyDown = GenerateKeyGetter("InputSystemGetKeyDown", "wasPressedThisFrame"); _getKeyUp = GenerateKeyGetter("InputSystemGetKeyUp", "wasReleasedThisFrame"); Type mouseType = assembly.GetType("UnityEngine.InputSystem.Mouse"); MethodInfo mouseCurrentProperty = AccessTools.PropertyGetter(mouseType, "current"); string[] source = new string[5] { "leftButton", "rightButton", "middleButton", "backButton", "forwardButton" }; MethodInfo[] buttonPropertyGetters = source.Select((string p) => AccessTools.PropertyGetter(mouseType, p)).ToArray(); _getMouseButton = GenerateMouseGetter("InputSystemGetMouseButton", "isPressed"); _getMouseButtonDown = GenerateMouseGetter("InputSystemGetMouseButtonDown", "wasPressedThisFrame"); _getMouseButtonUp = GenerateMouseGetter("InputSystemGetMouseButtonUp", "wasReleasedThisFrame"); _getMousePosition = GetPositionDelegate("InputSystemGetMousePosition", "position"); _getMouseScrollDelta = GetPositionDelegate("InputSystemGetMouseScrollDelta", "scroll"); DynamicMethodDefinition val2 = new DynamicMethodDefinition("InputSystemGetMouseEnabled", typeof(bool), Type.EmptyTypes); ILGenerator iLGenerator = val2.GetILGenerator(); iLGenerator.Emit(OpCodes.Call, mouseCurrentProperty); iLGenerator.Emit(OpCodes.Callvirt, AccessTools.PropertyGetter(mouseType, "enabled")); iLGenerator.Emit(OpCodes.Ret); _getMousePresent = Extensions.CreateDelegate((MethodBase)val2.Generate()); MethodInfo anyKeyProperty = AccessTools.PropertyGetter(type2, "anyKey"); _getKeyboardAnyKeyIsPressed = GetAnyKeyDelegate("InputSystemGetKeyboardAnyKeyIsPressed", "isPressed"); _getKeyboardAnyKeyWasPressedThisFrame = GetAnyKeyDelegate("InputSystemGetKeyboardAnyKeyWasPressedThisFrame", "wasPressedThisFrame"); initialized = true; GetButtonDelegate GenerateKeyGetter(string name, string property) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Expected O, but got Unknown MethodInfo meth4 = AccessTools.PropertyGetter(buttonControlType, property); DynamicMethodDefinition val6 = new DynamicMethodDefinition(name, typeof(bool), new Type[1] { typeof(KeyCode) }); ILGenerator iLGenerator4 = val6.GetILGenerator(); LocalBuilder local = iLGenerator4.DeclareLocal(typeof(int)); Label label2 = iLGenerator4.DefineLabel(); iLGenerator4.Emit(OpCodes.Ldsfld, keyCodeToIndexField); iLGenerator4.Emit(OpCodes.Ldarg_0); iLGenerator4.Emit(OpCodes.Ldloca, local); iLGenerator4.Emit(OpCodes.Callvirt, tryGetValueMethod); iLGenerator4.Emit(OpCodes.Brfalse, label2); iLGenerator4.Emit(OpCodes.Call, currentProperty); iLGenerator4.Emit(OpCodes.Ldloc, local); iLGenerator4.Emit(OpCodes.Callvirt, indexer); iLGenerator4.Emit(OpCodes.Callvirt, meth4); iLGenerator4.Emit(OpCodes.Ret); iLGenerator4.MarkLabel(label2); iLGenerator4.Emit(OpCodes.Ldc_I4_0); iLGenerator4.Emit(OpCodes.Ret); return Extensions.CreateDelegate((MethodBase)val6.Generate()); } GetButtonDelegate GenerateMouseGetter(string name, string property) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Expected O, but got Unknown MethodInfo meth3 = AccessTools.PropertyGetter(buttonControlType, property); DynamicMethodDefinition val5 = new DynamicMethodDefinition(name, typeof(bool), new Type[1] { typeof(KeyCode) }); ILGenerator il = val5.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldc_I4, 323); il.Emit(OpCodes.Sub); Label[] array = buttonPropertyGetters.Select((MethodInfo _) => il.DefineLabel()).ToArray(); Label label = il.DefineLabel(); il.Emit(OpCodes.Switch, array); il.Emit(OpCodes.Br, label); for (int i = 0; i < array.Length; i++) { il.MarkLabel(array[i]); il.Emit(OpCodes.Call, mouseCurrentProperty); il.Emit(OpCodes.Callvirt, buttonPropertyGetters[i]); il.Emit(OpCodes.Callvirt, meth3); il.Emit(OpCodes.Ret); } il.MarkLabel(label); il.Emit(OpCodes.Ldc_I4_0); il.Emit(OpCodes.Ret); return Extensions.CreateDelegate((MethodBase)val5.Generate()); } GetMouseStateDelegate GetAnyKeyDelegate(string name, string property) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Expected O, but got Unknown MethodInfo meth = AccessTools.PropertyGetter(buttonControlType, property); DynamicMethodDefinition val3 = new DynamicMethodDefinition(name, typeof(bool), Type.EmptyTypes); ILGenerator iLGenerator2 = val3.GetILGenerator(); iLGenerator2.Emit(OpCodes.Call, currentProperty); iLGenerator2.Emit(OpCodes.Callvirt, anyKeyProperty); iLGenerator2.Emit(OpCodes.Callvirt, meth); iLGenerator2.Emit(OpCodes.Ret); return Extensions.CreateDelegate((MethodBase)val3.Generate()); } GetMouseVectorDelegate GetPositionDelegate(string name, string property) { //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Expected O, but got Unknown MethodInfo methodInfo = AccessTools.PropertyGetter(mouseType, property); MethodInfo meth2 = AccessTools.Method(methodInfo.ReturnType, "ReadValue", (Type[])null, (Type[])null); DynamicMethodDefinition val4 = new DynamicMethodDefinition(name, typeof(Vector2), Type.EmptyTypes); ILGenerator iLGenerator3 = val4.GetILGenerator(); iLGenerator3.Emit(OpCodes.Call, mouseCurrentProperty); iLGenerator3.Emit(OpCodes.Callvirt, methodInfo); iLGenerator3.Emit(OpCodes.Callvirt, meth2); iLGenerator3.Emit(OpCodes.Ret); return Extensions.CreateDelegate((MethodBase)val4.Generate()); } } public bool GetKey(string name) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return _getKey(GetKeyCode(name)); } public bool GetKey(KeyCode key) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) return _getKey(key); } public bool GetKeyDown(string name) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return _getKeyDown(GetKeyCode(name)); } public bool GetKeyDown(KeyCode key) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) return _getKeyDown(key); } public bool GetKeyUp(string name) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return _getKeyUp(GetKeyCode(name)); } public bool GetKeyUp(KeyCode key) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) return _getKeyUp(key); } public bool GetMouseButton(int button) { return _getMouseButton((KeyCode)(323 + button)); } public bool GetMouseButtonDown(int button) { return _getMouseButtonDown((KeyCode)(323 + button)); } public bool GetMouseButtonUp(int button) { return _getMouseButtonUp((KeyCode)(323 + button)); } public void ResetInputAxes() { } private static KeyCode GetKeyCode(string name) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) return (KeyCode)Enum.Parse(typeof(KeyCode), name, ignoreCase: true); } private static bool TryEnumParse(string name, out T val) { try { val = (T)Enum.Parse(typeof(T), name, ignoreCase: true); return true; } catch (Exception) { val = default(T); return false; } } } internal class LegacyInputSystem : IInputSystem { public Vector3 mousePosition => Input.mousePosition; public Vector2 mouseScrollDelta => Input.mouseScrollDelta; public bool mousePresent => Input.mousePresent; public bool anyKey => Input.anyKey; public bool anyKeyDown => Input.anyKeyDown; public IEnumerable SupportedKeyCodes { get; } = (KeyCode[])Enum.GetValues(typeof(KeyCode)); public bool GetKey(string name) { return Input.GetKey(name); } public bool GetKey(KeyCode key) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return Input.GetKey(key); } public bool GetKeyDown(string name) { return Input.GetKeyDown(name); } public bool GetKeyDown(KeyCode key) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return Input.GetKeyDown(key); } public bool GetKeyUp(string name) { return Input.GetKeyUp(name); } public bool GetKeyUp(KeyCode key) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return Input.GetKeyUp(key); } public bool GetMouseButton(int button) { return Input.GetMouseButton(button); } public bool GetMouseButtonDown(int button) { return Input.GetMouseButtonDown(button); } public bool GetMouseButtonUp(int button) { return Input.GetMouseButtonUp(button); } public void ResetInputAxes() { Input.ResetInputAxes(); } } internal class NullInputSystem : IInputSystem { private static readonly KeyCode[] NoKeys = (KeyCode[])(object)new KeyCode[0]; public Vector3 mousePosition => Vector3.zero; public Vector2 mouseScrollDelta => Vector2.zero; public bool mousePresent => false; public bool anyKey => false; public bool anyKeyDown => false; public IEnumerable SupportedKeyCodes => NoKeys; public bool GetKey(string name) { return false; } public bool GetKey(KeyCode key) { return false; } public bool GetKeyDown(string name) { return false; } public bool GetKeyDown(KeyCode key) { return false; } public bool GetKeyUp(string name) { return false; } public bool GetKeyUp(KeyCode key) { return false; } public bool GetMouseButton(int button) { return false; } public bool GetMouseButtonDown(int button) { return false; } public bool GetMouseButtonUp(int button) { return false; } public void ResetInputAxes() { } } public static class Utility { private static bool? sreEnabled; public static bool CLRSupportsDynamicAssemblies => CheckSRE(); public static Encoding UTF8NoBom { get; } = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); private static bool CheckSRE() { if (sreEnabled.HasValue) { return sreEnabled.Value; } try { new CustomAttributeBuilder(null, new object[0]); } catch (PlatformNotSupportedException) { sreEnabled = false; return sreEnabled.Value; } catch (ArgumentNullException) { } sreEnabled = true; return sreEnabled.Value; } public static bool TryDo(Action action, out Exception exception) { exception = null; try { action(); return true; } catch (Exception ex) { exception = ex; return false; } } public static string CombinePaths(params string[] parts) { return parts.Aggregate(Path.Combine); } public static string ParentDirectory(string path, int levels = 1) { for (int i = 0; i < levels; i++) { path = Path.GetDirectoryName(path); } return path; } public static bool SafeParseBool(string input, bool defaultValue = false) { bool result; return bool.TryParse(input, out result) ? result : defaultValue; } public static string ConvertToWWWFormat(string path) { return "file://" + path.Replace('\\', '/'); } public static bool IsNullOrWhiteSpace(this string self) { return self?.All(char.IsWhiteSpace) ?? true; } public static IEnumerable TopologicalSort(IEnumerable nodes, Func> dependencySelector) { List sorted_list = new List(); HashSet visited = new HashSet(); HashSet sorted = new HashSet(); foreach (TNode node in nodes) { Stack stack2 = new Stack(); if (!Visit(node, stack2)) { throw new Exception("Cyclic Dependency:\r\n" + stack2.Select((TNode x) => $" - {x}").Aggregate((string a, string b) => a + "\r\n" + b)); } } return sorted_list; bool Visit(TNode node, Stack stack) { if (visited.Contains(node)) { if (!sorted.Contains(node)) { return false; } } else { visited.Add(node); stack.Push(node); foreach (TNode item in dependencySelector(node)) { if (!Visit(item, stack)) { return false; } } sorted.Add(node); sorted_list.Add(node); stack.Pop(); } return true; } } private static bool TryResolveDllAssembly(AssemblyName assemblyName, string directory, Func loader, out T assembly) where T : class { assembly = null; List list = new List { directory }; list.AddRange(Directory.GetDirectories(directory, "*", SearchOption.AllDirectories)); foreach (string item in list) { string text = Path.Combine(item, assemblyName.Name + ".dll"); if (!File.Exists(text)) { continue; } try { assembly = loader(text); } catch (Exception) { continue; } return true; } return false; } public static bool IsSubtypeOf(this TypeDefinition self, Type td) { if (((MemberReference)self).FullName == td.FullName) { return true; } int result; if (((MemberReference)self).FullName != "System.Object") { TypeReference baseType = self.BaseType; result = (((baseType == null) ? null : baseType.Resolve()?.IsSubtypeOf(td)).GetValueOrDefault() ? 1 : 0); } else { result = 0; } return (byte)result != 0; } public static bool TryResolveDllAssembly(AssemblyName assemblyName, string directory, out Assembly assembly) { return TryResolveDllAssembly(assemblyName, directory, (Func)Assembly.LoadFile, out assembly); } public static bool TryResolveDllAssembly(AssemblyName assemblyName, string directory, ReaderParameters readerParameters, out AssemblyDefinition assembly) { return TryResolveDllAssembly(assemblyName, directory, (Func)((string s) => AssemblyDefinition.ReadAssembly(s, readerParameters)), out assembly); } public static bool TryOpenFileStream(string path, FileMode mode, out FileStream fileStream, FileAccess access = FileAccess.ReadWrite, FileShare share = FileShare.Read) { try { fileStream = new FileStream(path, mode, access, share); return true; } catch (IOException) { fileStream = null; return false; } } public static bool TryParseAssemblyName(string fullName, out AssemblyName assemblyName) { try { assemblyName = new AssemblyName(fullName); return true; } catch (Exception) { assemblyName = null; return false; } } public static IEnumerable GetUniqueFilesInDirectories(IEnumerable directories, string pattern = "*") { Dictionary dictionary = new Dictionary(StringComparer.InvariantCultureIgnoreCase); foreach (string directory in directories) { string[] files = Directory.GetFiles(directory, pattern); foreach (string text in files) { string fileName = Path.GetFileName(text); if (!dictionary.ContainsKey(fileName)) { dictionary[fileName] = text; } } } return dictionary.Values; } } } namespace BepInEx.Logging { public class ConsoleLogListener : ILogListener, IDisposable { private static readonly ConfigEntry ConfigConsoleDisplayedLevel = ConfigFile.CoreConfig.Bind("Logging.Console", "LogLevels", LogLevel.Fatal | LogLevel.Error | LogLevel.Warning | LogLevel.Message | LogLevel.Info, "Which log levels to show in the console output."); internal bool WriteUnityLogs { get; set; } = true; public void LogEvent(object sender, LogEventArgs eventArgs) { if ((WriteUnityLogs || !(sender is UnityLogSource)) && (eventArgs.Level & ConfigConsoleDisplayedLevel.Value) != 0) { ConsoleManager.SetConsoleColor(eventArgs.Level.GetConsoleColor()); ConsoleManager.ConsoleStream?.Write(eventArgs.ToStringLine()); ConsoleManager.SetConsoleColor(ConsoleColor.Gray); } } public void Dispose() { } } public class DiskLogListener : ILogListener, IDisposable { public LogLevel DisplayedLogLevel { get; set; } public TextWriter LogWriter { get; protected set; } public Timer FlushTimer { get; protected set; } public bool WriteFromUnityLog { get; set; } public string FileFullPath { get; protected set; } public DiskLogListener(string localPath, LogLevel displayedLogLevel = LogLevel.Info, bool appendLog = false, bool includeUnityLog = false) { WriteFromUnityLog = includeUnityLog; DisplayedLogLevel = displayedLogLevel; int num = 1; string text = Path.Combine(Paths.BepInExRootPath, localPath); FileStream fileStream; while (!Utility.TryOpenFileStream(text, appendLog ? FileMode.Append : FileMode.Create, out fileStream, FileAccess.Write)) { if (num == 5) { Logger.LogError("Couldn't open a log file for writing. Skipping log file creation"); return; } Logger.LogWarning("Couldn't open log file '" + localPath + "' for writing, trying another..."); localPath = $"LogOutput.log.{num++}"; text = Path.Combine(Paths.BepInExRootPath, localPath); } LogWriter = TextWriter.Synchronized(new StreamWriter(fileStream, Utility.UTF8NoBom)); FileFullPath = text; FlushTimer = new Timer(delegate { LogWriter?.Flush(); }, null, 2000, 2000); } public void LogEvent(object sender, LogEventArgs eventArgs) { if ((WriteFromUnityLog || !(eventArgs.Source is UnityLogSource)) && (eventArgs.Level & DisplayedLogLevel) != 0) { LogWriter.WriteLine(eventArgs.ToString()); } } public void Dispose() { FlushTimer?.Dispose(); LogWriter?.Flush(); LogWriter?.Dispose(); } ~DiskLogListener() { Dispose(); } } internal class HarmonyLogSource : ILogSource, IDisposable { private static readonly ConfigEntry LogChannels = ConfigFile.CoreConfig.Bind("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 LevelMap = new Dictionary { [(LogChannel)2] = LogLevel.Info, [(LogChannel)8] = LogLevel.Warning, [(LogChannel)16] = LogLevel.Error, [(LogChannel)4] = LogLevel.Debug }; public string SourceName { get; } = "HarmonyX"; public event EventHandler LogEvent; public HarmonyLogSource() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) Logger.ChannelFilter = LogChannels.Value; Logger.MessageReceived += HandleHarmonyMessage; } private void HandleHarmonyMessage(object sender, LogEventArgs e) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) if (LevelMap.TryGetValue(e.LogChannel, out var value)) { this.LogEvent?.Invoke(this, new LogEventArgs(e.Message, value, this)); } } public void Dispose() { Logger.MessageReceived -= HandleHarmonyMessage; } } public interface ILogListener : IDisposable { void LogEvent(object sender, LogEventArgs eventArgs); } public interface ILogSource : IDisposable { string SourceName { get; } event EventHandler LogEvent; } public class LogEventArgs : EventArgs { public object Data { get; protected set; } public LogLevel Level { get; protected set; } public ILogSource Source { get; protected set; } public LogEventArgs(object data, LogLevel level, ILogSource source) { Data = data; Level = level; Source = source; } public override string ToString() { return $"[{Level,-7}:{Source.SourceName,10}] {Data}"; } public string ToStringLine() { return ToString() + Environment.NewLine; } } public static class Logger { private sealed class LogSourceCollection : ThreadSafeCollection, ICollection, IEnumerable, IEnumerable { public override void Add(ILogSource item) { if (item == null) { throw new ArgumentNullException("item", "Log sources cannot be null when added to the source list."); } lock (Lock) { item.LogEvent += InternalLogEvent; List list = new List(BaseList.Count + 1); list.AddRange(BaseList); list.Add(item); BaseList = list; } } public override void Clear() { if (base.Count == 0) { return; } lock (Lock) { for (int i = 0; i < BaseList.Count; i++) { BaseList[i].LogEvent -= InternalLogEvent; } BaseList = new List(0); } } public override bool Remove(ILogSource item) { if (item == null) { return false; } lock (Lock) { bool flag = base.Remove(item); if (flag) { item.LogEvent -= InternalLogEvent; } return flag; } } } private sealed class LogListenerCollection : ThreadSafeCollection { public void SendLogEvent(object sender, LogEventArgs eventArgs) { List baseList = BaseList; for (int i = 0; i < baseList.Count; i++) { baseList[i].LogEvent(sender, eventArgs); } } } private class ThreadSafeCollection : ICollection, IEnumerable, IEnumerable where T : class { protected readonly object Lock = new object(); protected List BaseList = new List(0); public int Count => BaseList.Count; public bool IsReadOnly => false; public IEnumerator GetEnumerator() { return BaseList.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return BaseList.GetEnumerator(); } public virtual void Add(T item) { if (item == null) { throw new ArgumentNullException("item", "item can't be null"); } lock (Lock) { List list = new List(BaseList.Count + 1); list.AddRange(BaseList); list.Add(item); BaseList = list; } } public virtual void Clear() { if (Count == 0) { return; } lock (Lock) { BaseList = new List(0); } } public bool Contains(T item) { return BaseList.Contains(item); } public void CopyTo(T[] array, int arrayIndex) { BaseList.CopyTo(array, arrayIndex); } public virtual bool Remove(T item) { if (item == null) { return false; } lock (Lock) { List list = new List(BaseList.Count); bool result = false; for (int i = 0; i < BaseList.Count; i++) { T val = BaseList[i]; if (val.Equals(item)) { result = true; } else { list.Add(val); } } BaseList = list; return result; } } } private static readonly LogListenerCollection _Listeners = new LogListenerCollection(); private static readonly ManualLogSource InternalLogSource = CreateLogSource("BepInEx"); private static bool internalLogsInitialized; public static ICollection Listeners => _Listeners; public static ICollection Sources { get; } = new LogSourceCollection(); internal static void InitializeInternalLoggers() { if (!internalLogsInitialized) { Sources.Add(new HarmonyLogSource()); internalLogsInitialized = true; } } internal static void InternalLogEvent(object sender, LogEventArgs eventArgs) { _Listeners.SendLogEvent(sender, eventArgs); } internal static void Log(LogLevel level, object data) { InternalLogSource.Log(level, data); } internal static void LogFatal(object data) { Log(LogLevel.Fatal, data); } internal static void LogError(object data) { Log(LogLevel.Error, data); } internal static void LogWarning(object data) { Log(LogLevel.Warning, data); } internal static void LogMessage(object data) { Log(LogLevel.Message, data); } internal static void LogInfo(object data) { Log(LogLevel.Info, data); } internal static void LogDebug(object data) { Log(LogLevel.Debug, data); } public static ManualLogSource CreateLogSource(string sourceName) { ManualLogSource manualLogSource = new ManualLogSource(sourceName); Sources.Add(manualLogSource); return manualLogSource; } } [Flags] public enum LogLevel { None = 0, Fatal = 1, Error = 2, Warning = 4, Message = 8, Info = 0x10, Debug = 0x20, All = 0x3F } public static class LogLevelExtensions { public static LogLevel GetHighestLevel(this LogLevel levels) { Array values = Enum.GetValues(typeof(LogLevel)); Array.Sort(values); foreach (LogLevel item in values) { if ((levels & item) != 0) { return item; } } return LogLevel.None; } public static ConsoleColor GetConsoleColor(this LogLevel level) { level = level.GetHighestLevel(); return level switch { LogLevel.Fatal => ConsoleColor.Red, LogLevel.Error => ConsoleColor.DarkRed, LogLevel.Warning => ConsoleColor.Yellow, LogLevel.Message => ConsoleColor.White, LogLevel.Debug => ConsoleColor.DarkGray, _ => ConsoleColor.Gray, }; } } public class ManualLogSource : ILogSource, IDisposable { public string SourceName { get; } public event EventHandler LogEvent; public ManualLogSource(string sourceName) { SourceName = sourceName; } public void Log(LogLevel level, object data) { this.LogEvent?.Invoke(this, new LogEventArgs(data, level, this)); } public void LogFatal(object data) { Log(LogLevel.Fatal, data); } public void LogError(object data) { Log(LogLevel.Error, data); } public void LogWarning(object data) { Log(LogLevel.Warning, data); } public void LogMessage(object data) { Log(LogLevel.Message, data); } public void LogInfo(object data) { Log(LogLevel.Info, data); } public void LogDebug(object data) { Log(LogLevel.Debug, data); } public void Dispose() { } } public class TraceLogSource : TraceListener { private static TraceLogSource traceListener; public static bool IsListening { get; protected set; } protected ManualLogSource LogSource { get; } public static ILogSource CreateSource() { if (traceListener == null) { traceListener = new TraceLogSource(); Trace.Listeners.Add(traceListener); IsListening = true; } return traceListener.LogSource; } protected TraceLogSource() { LogSource = new ManualLogSource("Trace"); } public override void Write(string message) { LogSource.LogInfo(message); } public override void WriteLine(string message) { LogSource.LogInfo(message); } public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args) { TraceEvent(eventCache, source, eventType, id, string.Format(format, args)); } public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message) { LogSource.Log(eventType switch { TraceEventType.Critical => LogLevel.Fatal, TraceEventType.Error => LogLevel.Error, TraceEventType.Warning => LogLevel.Warning, TraceEventType.Information => LogLevel.Info, _ => LogLevel.Debug, }, (message ?? "").Trim()); } } public class UnityLogListener : ILogListener, IDisposable { internal static readonly Action WriteStringToUnityLog; private ConfigEntry LogConsoleToUnity = ConfigFile.CoreConfig.Bind("Logging", "LogConsoleToUnityLog", defaultValue: false, new StringBuilder().AppendLine("If enabled, writes Standard Output messages to Unity log").AppendLine("NOTE: By default, Unity does so automatically. Only use this option if no console messages are visible in Unity log").ToString()); static UnityLogListener() { MethodInfo[] methods = typeof(UnityLogWriter).GetMethods(BindingFlags.Static | BindingFlags.Public); foreach (MethodInfo methodInfo in methods) { try { methodInfo.Invoke(null, new object[1] { "" }); } catch { continue; } WriteStringToUnityLog = (Action)Delegate.CreateDelegate(typeof(Action), methodInfo); break; } if (WriteStringToUnityLog == null) { Logger.LogError("Unable to start Unity log writer"); } } public void LogEvent(object sender, LogEventArgs eventArgs) { if (!(eventArgs.Source is UnityLogSource) && (LogConsoleToUnity.Value || eventArgs.Source.SourceName != "Console")) { WriteStringToUnityLog?.Invoke(eventArgs.ToStringLine()); } } public void Dispose() { } } public class UnityLogSource : ILogSource, IDisposable { private bool disposed = false; public string SourceName { get; } = "Unity Log"; public event EventHandler LogEvent; private static event EventHandler InternalUnityLogMessage; public UnityLogSource() { InternalUnityLogMessage += UnityLogMessageHandler; } private void UnityLogMessageHandler(object sender, LogEventArgs eventArgs) { LogEventArgs e = new LogEventArgs(eventArgs.Data, eventArgs.Level, this); this.LogEvent?.Invoke(this, e); } public void Dispose() { if (!disposed) { InternalUnityLogMessage -= UnityLogMessageHandler; disposed = true; } } static UnityLogSource() { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Expected O, but got Unknown LogCallback val = new LogCallback(OnUnityLogMessageReceived); EventInfo @event = typeof(Application).GetEvent("logMessageReceived", BindingFlags.Static | BindingFlags.Public); if (@event != null) { @event.AddEventHandler(null, (Delegate?)(object)val); return; } MethodInfo method = typeof(Application).GetMethod("RegisterLogCallback", BindingFlags.Static | BindingFlags.Public); method.Invoke(null, new object[1] { val }); } private static void OnUnityLogMessageReceived(string message, string stackTrace, LogType type) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Expected I4, but got Unknown //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Invalid comparison between Unknown and I4 LogLevel level; switch ((int)type) { case 0: case 1: case 4: level = LogLevel.Error; break; case 2: level = LogLevel.Warning; break; default: level = LogLevel.Info; break; } if ((int)type == 4) { message = message + "\nStack trace:\n" + stackTrace; } UnityLogSource.InternalUnityLogMessage?.Invoke(null, new LogEventArgs(message, level, null)); } } } namespace BepInEx.ConsoleUtil { internal class Kon { private struct CONSOLE_SCREEN_BUFFER_INFO { internal COORD dwSize; internal COORD dwCursorPosition; internal short wAttributes; internal SMALL_RECT srWindow; internal COORD dwMaximumWindowSize; } private struct COORD { internal short X; internal short Y; } private struct SMALL_RECT { internal short Left; internal short Top; internal short Right; internal short Bottom; } private static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); internal static IntPtr conOut = IntPtr.Zero; public static ConsoleColor ForegroundColor { get { return GetConsoleColor(isBackground: false); } set { SetConsoleColor(isBackground: false, value); } } public static ConsoleColor BackgroundColor { get { return GetConsoleColor(isBackground: true); } set { SetConsoleColor(isBackground: true, value); } } [DllImport("kernel32.dll", SetLastError = true)] private static extern bool GetConsoleScreenBufferInfo(IntPtr hConsoleOutput, out CONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool SetConsoleTextAttribute(IntPtr hConsoleOutput, short attributes); [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr GetStdHandle(int nStdHandle); private static short ConsoleColorToColorAttribute(short color, bool isBackground) { if (((uint)color & 0xFFFFFFF0u) != 0) { throw new ArgumentException("Arg_InvalidConsoleColor"); } if (isBackground) { color <<= 4; } return color; } private static CONSOLE_SCREEN_BUFFER_INFO GetBufferInfo(bool throwOnNoConsole, out bool succeeded) { succeeded = false; if (!(conOut == INVALID_HANDLE_VALUE)) { if (!GetConsoleScreenBufferInfo(conOut, out var lpConsoleScreenBufferInfo)) { bool consoleScreenBufferInfo = GetConsoleScreenBufferInfo(GetStdHandle(-12), out lpConsoleScreenBufferInfo); if (!consoleScreenBufferInfo) { consoleScreenBufferInfo = GetConsoleScreenBufferInfo(GetStdHandle(-10), out lpConsoleScreenBufferInfo); } if (!consoleScreenBufferInfo && Marshal.GetLastWin32Error() == 6 && !throwOnNoConsole) { return default(CONSOLE_SCREEN_BUFFER_INFO); } } succeeded = true; return lpConsoleScreenBufferInfo; } if (!throwOnNoConsole) { return default(CONSOLE_SCREEN_BUFFER_INFO); } throw new Exception("IO.IO_NoConsole"); } private static void SetConsoleColor(bool isBackground, ConsoleColor c) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) ((CodeAccessPermission)new UIPermission((UIPermissionWindow)2)).Demand(); short num = ConsoleColorToColorAttribute((short)c, isBackground); bool succeeded; CONSOLE_SCREEN_BUFFER_INFO bufferInfo = GetBufferInfo(throwOnNoConsole: false, out succeeded); if (succeeded) { short wAttributes = bufferInfo.wAttributes; wAttributes &= (short)(isBackground ? (-241) : (-16)); wAttributes = (short)((ushort)wAttributes | (ushort)num); SetConsoleTextAttribute(conOut, wAttributes); } } private static ConsoleColor GetConsoleColor(bool isBackground) { bool succeeded; CONSOLE_SCREEN_BUFFER_INFO bufferInfo = GetBufferInfo(throwOnNoConsole: false, out succeeded); if (!succeeded) { return (!isBackground) ? ConsoleColor.Gray : ConsoleColor.Black; } return ColorAttributeToConsoleColor((short)(bufferInfo.wAttributes & 0xF0)); } private static ConsoleColor ColorAttributeToConsoleColor(short c) { if ((short)((uint)c & 0xFFu) != 0) { c >>= 4; } return (ConsoleColor)c; } public static void ResetConsoleColor() { SetConsoleColor(isBackground: true, ConsoleColor.Black); SetConsoleColor(isBackground: false, ConsoleColor.Gray); } } } namespace BepInEx.Unix { internal static class ConsoleWriter { private static Func cStreamWriterConstructor; private static Func CStreamWriterConstructor { get { if (cStreamWriterConstructor != null) { return cStreamWriterConstructor; } Type cStreamWriter = AccessTools.TypeByName("System.IO.CStreamWriter"); int[][] source = new int[2][] { new int[3] { 0, 1, 2 }, new int[2] { 0, 1 } }; cStreamWriterConstructor = source.Select(GetCtor).FirstOrDefault((Func f) => f != null); if (cStreamWriterConstructor == null) { throw new AmbiguousMatchException("Failed to find suitable constructor for CStreamWriter"); } return cStreamWriterConstructor; Func GetCtor(int[] perm) { Type[] parameters = new Type[3] { typeof(Stream), typeof(Encoding), typeof(bool) }; ConstructorInfo ctor = AccessTools.Constructor(cStreamWriter, perm.Select((int i) => parameters[i]).ToArray(), false); if (ctor != null) { return delegate(Stream stream, Encoding encoding, bool l) { object[] vals = new object[3] { stream, encoding, l }; return (StreamWriter)ctor.Invoke(perm.Select((int i) => vals[i]).ToArray()); }; } return null; } } } public static TextWriter CreateConsoleStreamWriter(Stream stream, Encoding encoding, bool leaveOpen) { StreamWriter streamWriter = CStreamWriterConstructor(stream, encoding, leaveOpen); streamWriter.AutoFlush = true; return streamWriter; } } internal class LinuxConsoleDriver : IConsoleDriver { private static readonly ConfigEntry ForceCustomTtyDriverConfig; public static bool UseMonoTtyDriver { get; } public TextWriter StandardOut { get; private set; } public TextWriter ConsoleOut { get; private set; } public bool ConsoleActive { get; private set; } public bool ConsoleIsExternal => false; public bool StdoutRedirected { get; private set; } public TtyInfo TtyInfo { get; private set; } static LinuxConsoleDriver() { ForceCustomTtyDriverConfig = ConfigFile.CoreConfig.Bind("Logging.Console", "ForceBepInExTTYDriver", defaultValue: false, "If enabled, forces to use custom BepInEx TTY driver for handling terminal output on unix."); UseMonoTtyDriver = false; if (!ForceCustomTtyDriverConfig.Value) { Type type = typeof(Console).Assembly.GetType("System.ConsoleDriver"); if (type != null) { UseMonoTtyDriver = typeof(Console).Assembly.GetType("System.ParameterizedStrings") != null; } } } public void PreventClose() { } public void Initialize(bool alreadyActive) { ConsoleActive = true; StdoutRedirected = UnixStreamHelper.isatty(1) != 1; Stream stream = UnixStreamHelper.CreateDuplicateStream(1); if (UseMonoTtyDriver && !StdoutRedirected) { TextWriter textWriter = ConsoleWriter.CreateConsoleStreamWriter(stream, Console.Out.Encoding, leaveOpen: true); StandardOut = TextWriter.Synchronized(textWriter); object value = AccessTools.Field(AccessTools.TypeByName("System.ConsoleDriver"), "driver").GetValue(null); AccessTools.Field(AccessTools.TypeByName("System.TermInfoDriver"), "stdout").SetValue(value, textWriter); } else { StreamWriter streamWriter = new StreamWriter(stream, Console.Out.Encoding); streamWriter.AutoFlush = true; StandardOut = TextWriter.Synchronized(streamWriter); TtyInfo = TtyHandler.GetTtyInfo(); } ConsoleOut = StandardOut; } public void CreateConsole(uint codepage) { Logger.LogWarning("An external console currently cannot be spawned on a Unix platform."); } public void DetachConsole() { throw new PlatformNotSupportedException("Cannot detach console on a Unix platform"); } public void SetConsoleColor(ConsoleColor color) { if (!StdoutRedirected) { if (UseMonoTtyDriver) { SafeConsole.ForegroundColor = color; } else { ConsoleOut.Write(TtyInfo.GetAnsiCode(color)); } } } public void SetConsoleTitle(string title) { if (!StdoutRedirected) { if (UseMonoTtyDriver && SafeConsole.TitleExists) { SafeConsole.Title = title; } else { ConsoleOut.Write("\u001b]2;" + title.Replace("\\", "\\\\") + "\a"); } } } } internal class TtyInfo { public string TerminalType { get; set; } = "default"; public int MaxColors { get; set; } public string[] ForegroundColorStrings { get; set; } public static TtyInfo Default { get; } = new TtyInfo { MaxColors = 0 }; public string GetAnsiCode(ConsoleColor color) { if (MaxColors <= 0 || ForegroundColorStrings == null) { return string.Empty; } int num = (int)color % MaxColors; return ForegroundColorStrings[num]; } } internal static class TtyHandler { private static readonly string[] ncursesLocations = new string[4] { "/usr/share/terminfo", "/etc/terminfo", "/usr/lib/terminfo", "/lib/terminfo" }; private static string TryTermInfoDir(string dir, string term) { string text = $"{dir}/{(int)term[0]:x}/{term}"; if (File.Exists(text)) { return text; } text = Utility.CombinePaths(dir, term.Substring(0, 1), term); if (File.Exists(text)) { return text; } return null; } private static string FindTermInfoPath(string term) { if (string.IsNullOrEmpty(term)) { return null; } string environmentVariable = Environment.GetEnvironmentVariable("TERMINFO"); if (environmentVariable != null && Directory.Exists(environmentVariable)) { string text = TryTermInfoDir(environmentVariable, term); if (text != null) { return text; } } string[] array = ncursesLocations; foreach (string text2 in array) { if (Directory.Exists(text2)) { string text3 = TryTermInfoDir(text2, term); if (text3 != null) { return text3; } } } return null; } public static TtyInfo GetTtyInfo(string terminal = null) { terminal = terminal ?? Environment.GetEnvironmentVariable("TERM"); string text = FindTermInfoPath(terminal); if (text == null) { return TtyInfo.Default; } byte[] buffer = File.ReadAllBytes(text); TtyInfo ttyInfo = TtyInfoParser.Parse(buffer); ttyInfo.TerminalType = terminal; return ttyInfo; } } internal static class TtyInfoParser { internal enum TermInfoNumbers { MaxColors = 13 } internal enum TermInfoStrings { SetAForeground = 359 } private static readonly int[] ansiColorMapping = new int[16] { 0, 4, 2, 6, 1, 5, 3, 7, 8, 12, 10, 14, 9, 13, 11, 15 }; public static TtyInfo Parse(byte[] buffer) { int num; switch (GetInt16(buffer, 0)) { case 282: num = 2; break; case 542: num = 4; break; default: return TtyInfo.Default; } int @int = GetInt16(buffer, 4); int int2 = GetInt16(buffer, 6); int int3 = GetInt16(buffer, 8); int num2 = 12 + GetString(buffer, 12).Length + 1; num2 += @int; num2 += num2 % 2; int offset = num2 + num * 13; TtyInfo ttyInfo = new TtyInfo(); ttyInfo.MaxColors = GetInteger(num, buffer, offset); ttyInfo.ForegroundColorStrings = ansiColorMapping.Select((int x) => $"\u001b[{((x > 7) ? (82 + x) : (30 + x))}m").ToArray(); return ttyInfo; } private static int GetInt32(byte[] buffer, int offset) { return buffer[offset] | (buffer[offset + 1] << 8) | (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24); } private static short GetInt16(byte[] buffer, int offset) { return (short)(buffer[offset] | (buffer[offset + 1] << 8)); } private static int GetInteger(int intSize, byte[] buffer, int offset) { return (intSize == 2) ? GetInt16(buffer, offset) : GetInt32(buffer, offset); } private static string GetString(byte[] buffer, int offset) { int i; for (i = 0; buffer[offset + i] != 0; i++) { } return Encoding.ASCII.GetString(buffer, offset, i); } } internal class UnixStream : Stream { public override bool CanRead => Access == FileAccess.Read || Access == FileAccess.ReadWrite; public override bool CanSeek => false; public override bool CanWrite => Access == FileAccess.Write || Access == FileAccess.ReadWrite; public override long Length { get { throw new InvalidOperationException(); } } public override long Position { get { throw new InvalidOperationException(); } set { throw new InvalidOperationException(); } } public FileAccess Access { get; } public IntPtr FileHandle { get; } public UnixStream(int fileDescriptor, FileAccess access) { Access = access; int fd = UnixStreamHelper.dup(fileDescriptor); FileHandle = UnixStreamHelper.fdopen(fd, (access == FileAccess.Write) ? "w" : "r"); } public override void Flush() { UnixStreamHelper.fflush(FileHandle); } public override long Seek(long offset, SeekOrigin origin) { throw new InvalidOperationException(); } public override void SetLength(long value) { throw new InvalidOperationException(); } public override int Read(byte[] buffer, int offset, int count) { GCHandle gCHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned); IntPtr intPtr = UnixStreamHelper.fread(new IntPtr(gCHandle.AddrOfPinnedObject().ToInt64() + offset), (IntPtr)count, (IntPtr)1, FileHandle); gCHandle.Free(); return intPtr.ToInt32(); } public override void Write(byte[] buffer, int offset, int count) { GCHandle gCHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned); UnixStreamHelper.fwrite(new IntPtr(gCHandle.AddrOfPinnedObject().ToInt64() + offset), (IntPtr)count, (IntPtr)1, FileHandle); gCHandle.Free(); } private void ReleaseUnmanagedResources() { UnixStreamHelper.fclose(FileHandle); } protected override void Dispose(bool disposing) { ReleaseUnmanagedResources(); base.Dispose(disposing); } ~UnixStream() { Dispose(disposing: false); } } internal static class UnixStreamHelper { public delegate int dupDelegate(int fd); public delegate IntPtr fdopenDelegate(int fd, string mode); public delegate IntPtr freadDelegate(IntPtr ptr, IntPtr size, IntPtr nmemb, IntPtr stream); public delegate int fwriteDelegate(IntPtr ptr, IntPtr size, IntPtr nmemb, IntPtr stream); public delegate int fcloseDelegate(IntPtr stream); public delegate int fflushDelegate(IntPtr stream); public delegate int isattyDelegate(int fd); [DynDllImport("libc", new string[] { })] public static dupDelegate dup; [DynDllImport("libc", new string[] { })] public static fdopenDelegate fdopen; [DynDllImport("libc", new string[] { })] public static freadDelegate fread; [DynDllImport("libc", new string[] { })] public static fwriteDelegate fwrite; [DynDllImport("libc", new string[] { })] public static fcloseDelegate fclose; [DynDllImport("libc", new string[] { })] public static fflushDelegate fflush; [DynDllImport("libc", new string[] { })] public static isattyDelegate isatty; static UnixStreamHelper() { Dictionary> dictionary = new Dictionary> { ["libc"] = new List { DynDllMapping.op_Implicit("libc.so.6"), DynDllMapping.op_Implicit("libc"), DynDllMapping.op_Implicit("/usr/lib/libSystem.dylib") } }; DynDll.ResolveDynDllImports(typeof(UnixStreamHelper), dictionary); } public static Stream CreateDuplicateStream(int fileDescriptor) { int fileDescriptor2 = dup(fileDescriptor); return new UnixStream(fileDescriptor2, FileAccess.Write); } } } namespace BepInEx.Configuration { public abstract class AcceptableValueBase { public Type ValueType { get; } protected AcceptableValueBase(Type valueType) { ValueType = valueType; } public abstract object Clamp(object value); public abstract bool IsValid(object value); public abstract string ToDescriptionString(); } public class AcceptableValueList : AcceptableValueBase where T : IEquatable { public virtual T[] AcceptableValues { get; } public AcceptableValueList(params T[] acceptableValues) : base(typeof(T)) { if (acceptableValues == null) { throw new ArgumentNullException("acceptableValues"); } if (acceptableValues.Length == 0) { throw new ArgumentException("At least one acceptable value is needed", "acceptableValues"); } AcceptableValues = acceptableValues; } public override object Clamp(object value) { if (IsValid(value)) { return value; } return AcceptableValues[0]; } public override bool IsValid(object value) { int result; if (value is T) { T v = (T)value; result = (AcceptableValues.Any((T x) => x.Equals(v)) ? 1 : 0); } else { result = 0; } return (byte)result != 0; } public override string ToDescriptionString() { return "# Acceptable values: " + string.Join(", ", AcceptableValues.Select((T x) => x.ToString()).ToArray()); } } public class AcceptableValueRange : AcceptableValueBase where T : IComparable { public virtual T MinValue { get; } public virtual T MaxValue { get; } public AcceptableValueRange(T minValue, T maxValue) : base(typeof(T)) { if (maxValue == null) { throw new ArgumentNullException("maxValue"); } if (minValue == null) { throw new ArgumentNullException("minValue"); } if (minValue.CompareTo(maxValue) >= 0) { throw new ArgumentException("minValue has to be lower than maxValue"); } MinValue = minValue; MaxValue = maxValue; } public override object Clamp(object value) { if (MinValue.CompareTo(value) > 0) { return MinValue; } if (MaxValue.CompareTo(value) < 0) { return MaxValue; } return value; } public override bool IsValid(object value) { return MinValue.CompareTo(value) <= 0 && MaxValue.CompareTo(value) >= 0; } public override string ToDescriptionString() { return $"# Acceptable value range: From {MinValue} to {MaxValue}"; } } public class ConfigDefinition : IEquatable { private static readonly char[] _invalidConfigChars = new char[8] { '=', '\n', '\t', '\\', '"', '\'', '[', ']' }; public string Section { get; } public string Key { get; } public ConfigDefinition(string section, string key) { CheckInvalidConfigChars(section, "section"); CheckInvalidConfigChars(key, "key"); Key = key; Section = section; } private static void CheckInvalidConfigChars(string val, string name) { if (val == null) { throw new ArgumentNullException(name); } if (val != val.Trim()) { throw new ArgumentException("Cannot use whitespace characters at start or end of section and key names", name); } if (val.Any((char c) => _invalidConfigChars.Contains(c))) { throw new ArgumentException("Cannot use any of the following characters in section and key names: = \\n \\t \\ \" ' [ ]", name); } } [Obsolete("description argument is no longer used, put it in a ConfigDescription instead")] public ConfigDefinition(string section, string key, string description) { Key = key ?? ""; Section = section ?? ""; } public bool Equals(ConfigDefinition other) { if (other == null) { return false; } return string.Equals(Key, other.Key) && string.Equals(Section, other.Section); } public override bool Equals(object obj) { if (obj == null) { return false; } if (this == obj) { return true; } return Equals(obj as ConfigDefinition); } public override int GetHashCode() { int num = ((Key != null) ? Key.GetHashCode() : 0); return (num * 397) ^ ((Section != null) ? Section.GetHashCode() : 0); } public static bool operator ==(ConfigDefinition left, ConfigDefinition right) { return object.Equals(left, right); } public static bool operator !=(ConfigDefinition left, ConfigDefinition right) { return !object.Equals(left, right); } public override string ToString() { return Section + "." + Key; } } public class ConfigDescription { public string Description { get; } public AcceptableValueBase AcceptableValues { get; } public object[] Tags { get; } public static ConfigDescription Empty { get; } = new ConfigDescription("", null); public ConfigDescription(string description, AcceptableValueBase acceptableValues = null, params object[] tags) { AcceptableValues = acceptableValues; Tags = tags; Description = description ?? throw new ArgumentNullException("description"); } } public sealed class ConfigEntry : ConfigEntryBase { private T _typedValue; public T Value { get { return _typedValue; } set { value = ClampValue(value); if (!object.Equals(_typedValue, value)) { _typedValue = value; OnSettingChanged(this); } } } public override object BoxedValue { get { return Value; } set { Value = (T)value; } } public event EventHandler SettingChanged; internal ConfigEntry(ConfigFile configFile, ConfigDefinition definition, T defaultValue, ConfigDescription configDescription) : base(configFile, definition, typeof(T), defaultValue, configDescription) { configFile.SettingChanged += delegate(object sender, SettingChangedEventArgs args) { if (args.ChangedSetting == this) { this.SettingChanged?.Invoke(sender, args); } }; } } public abstract class ConfigEntryBase { public ConfigFile ConfigFile { get; } public ConfigDefinition Definition { get; } public ConfigDescription Description { get; } public Type SettingType { get; } public object DefaultValue { get; } public abstract object BoxedValue { get; set; } internal ConfigEntryBase(ConfigFile configFile, ConfigDefinition definition, Type settingType, object defaultValue, ConfigDescription configDescription) { ConfigFile = configFile ?? throw new ArgumentNullException("configFile"); Definition = definition ?? throw new ArgumentNullException("definition"); SettingType = settingType ?? throw new ArgumentNullException("settingType"); Description = configDescription ?? ConfigDescription.Empty; if (Description.AcceptableValues != null && !SettingType.IsAssignableFrom(Description.AcceptableValues.ValueType)) { throw new ArgumentException("configDescription.AcceptableValues is for a different type than the type of this setting"); } DefaultValue = defaultValue; BoxedValue = defaultValue; } public string GetSerializedValue() { return TomlTypeConverter.ConvertToString(BoxedValue, SettingType); } public void SetSerializedValue(string value) { try { object boxedValue = TomlTypeConverter.ConvertToValue(value, SettingType); BoxedValue = boxedValue; } catch (Exception ex) { Logger.Log(LogLevel.Warning, $"Config value of setting \"{Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}"); } } protected T ClampValue(T 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, ICollection>, IEnumerable>, IEnumerable { private readonly BepInPlugin _ownerMetadata; private readonly object _ioLock = new object(); internal static ConfigFile CoreConfig { get; } = new ConfigFile(Paths.BepInExConfigPath, saveOnInit: true); protected Dictionary Entries { get; } = new Dictionary(); private Dictionary OrphanedEntries { get; } = new Dictionary(); [Obsolete("Use Keys instead")] public ReadOnlyCollection ConfigDefinitions { get { lock (_ioLock) { return Entries.Keys.ToList().AsReadOnly(); } } } public string ConfigFilePath { get; } public bool SaveOnConfigSet { get; set; } = true; public int Count { get { lock (_ioLock) { return Entries.Count; } } } public bool IsReadOnly => false; ConfigEntryBase IDictionary.this[ConfigDefinition key] { get { lock (_ioLock) { return Entries[key]; } } set { throw new InvalidOperationException("Directly setting a config entry is not supported"); } } public ConfigEntryBase this[ConfigDefinition key] { get { lock (_ioLock) { return Entries[key]; } } } public ConfigEntryBase this[string section, string key] => this[new ConfigDefinition(section, key)]; public ICollection Keys { get { lock (_ioLock) { return Entries.Keys.ToArray(); } } } ICollection IDictionary.Values { get { lock (_ioLock) { return Entries.Values.ToArray(); } } } public event EventHandler ConfigReloaded; public event EventHandler SettingChanged; [Obsolete("Use Values instead")] public ConfigEntryBase[] GetConfigEntries() { lock (_ioLock) { return Entries.Values.ToArray(); } } 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 void Reload() { lock (_ioLock) { OrphanedEntries.Clear(); string section = string.Empty; string[] array = File.ReadAllLines(ConfigFilePath); foreach (string text in array) { string text2 = text.Trim(); if (text2.StartsWith("#")) { continue; } if (text2.StartsWith("[") && text2.EndsWith("]")) { section = text2.Substring(1, text2.Length - 2); continue; } string[] array2 = text2.Split(new char[1] { '=' }, 2); if (array2.Length == 2) { string key = array2[0].Trim(); string text3 = array2[1].Trim(); ConfigDefinition key2 = new ConfigDefinition(section, key); Entries.TryGetValue(key2, out var value); if (value != null) { value.SetSerializedValue(text3); } else { OrphanedEntries[key2] = text3; } } } } 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(); } var source = Entries.Select((KeyValuePair x) => new { Key = x.Key, entry = x.Value, value = x.Value.GetSerializedValue() }).Concat(OrphanedEntries.Select((KeyValuePair x) => new { Key = x.Key, entry = (ConfigEntryBase)null, value = x.Value })); foreach (var item in from x in source group x by x.Key.Section into x orderby x.Key select x) { streamWriter.WriteLine("[" + item.Key + "]"); foreach (var item2 in item) { streamWriter.WriteLine(); item2.entry?.WriteDescription(streamWriter); streamWriter.WriteLine(item2.Key.Key + " = " + item2.value); } streamWriter.WriteLine(); } } } [Obsolete("Use ConfigFile[key] or TryGetEntry instead")] public ConfigEntry GetSetting(ConfigDefinition configDefinition) { ConfigEntry entry; return TryGetEntry(configDefinition, out entry) ? entry : null; } [Obsolete("Use ConfigFile[key] or TryGetEntry instead")] public ConfigEntry GetSetting(string section, string key) { ConfigEntry entry; return TryGetEntry(section, key, out entry) ? entry : null; } public bool TryGetEntry(ConfigDefinition configDefinition, out ConfigEntry entry) { lock (_ioLock) { if (Entries.TryGetValue(configDefinition, out var value)) { entry = (ConfigEntry)value; return true; } entry = null; return false; } } public bool TryGetEntry(string section, string key, out ConfigEntry entry) { return TryGetEntry(new ConfigDefinition(section, key), out entry); } public ConfigEntry Bind(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)value; } ConfigEntry configEntry = new ConfigEntry(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 Bind(string section, string key, T defaultValue, ConfigDescription configDescription = null) { return Bind(new ConfigDefinition(section, key), defaultValue, configDescription); } public ConfigEntry Bind(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 AddSetting(ConfigDefinition configDefinition, T defaultValue, ConfigDescription configDescription = null) { return Bind(configDefinition, defaultValue, configDescription); } [Obsolete("Use Bind instead")] public ConfigEntry AddSetting(string section, string key, T defaultValue, ConfigDescription configDescription = null) { return Bind(new ConfigDefinition(section, key), defaultValue, configDescription); } [Obsolete("Use Bind instead")] public ConfigEntry AddSetting(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 Wrap(string section, string key, string description = null, T defaultValue = default(T)) { lock (_ioLock) { ConfigDefinition configDefinition = new ConfigDefinition(section, key, description); ConfigEntry configEntry = Bind(configDefinition, defaultValue, string.IsNullOrEmpty(description) ? null : new ConfigDescription(description, null)); return new ConfigWrapper(configEntry); } } [Obsolete("Use Bind instead")] public ConfigWrapper Wrap(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 settingChanged = this.SettingChanged; if (settingChanged == null) { return; } SettingChangedEventArgs e = new SettingChangedEventArgs(changedEntryBase); foreach (EventHandler item in settingChanged.GetInvocationList().Cast>()) { try { item(sender, e); } catch (Exception data) { Logger.Log(LogLevel.Error, data); } } } private void OnConfigReloaded() { EventHandler configReloaded = this.ConfigReloaded; if (configReloaded == null) { return; } foreach (EventHandler item in configReloaded.GetInvocationList().Cast()) { try { item(this, EventArgs.Empty); } catch (Exception data) { Logger.Log(LogLevel.Error, data); } } } public IEnumerator> GetEnumerator() { return Entries.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } void ICollection>.Add(KeyValuePair item) { lock (_ioLock) { Entries.Add(item.Key, item.Value); } } public bool Contains(KeyValuePair item) { lock (_ioLock) { return ((ICollection>)Entries).Contains(item); } } void ICollection>.CopyTo(KeyValuePair[] array, int arrayIndex) { lock (_ioLock) { ((ICollection>)Entries).CopyTo(array, arrayIndex); } } bool ICollection>.Remove(KeyValuePair 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.TryGetValue(ConfigDefinition key, out ConfigEntryBase value) { lock (_ioLock) { return Entries.TryGetValue(key, out value); } } } [Obsolete("Use ConfigFile from new Bind overloads instead")] public sealed class ConfigWrapper { public ConfigEntry 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 configEntry) { ConfigWrapper 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 struct KeyboardShortcut { public static readonly KeyboardShortcut Empty; [Obsolete("Use UnityInput.Current.SupportedKeyCodes instead")] public static readonly IEnumerable AllKeyCodes; private static KeyCode[] _modifierBlockKeyCodes; private readonly KeyCode[] _allKeys; public KeyCode MainKey => (KeyCode)((_allKeys != null && _allKeys.Length != 0) ? ((int)_allKeys[0]) : 0); public IEnumerable Modifiers => _allKeys?.Skip(1) ?? Enumerable.Empty(); static KeyboardShortcut() { Empty = default(KeyboardShortcut); AllKeyCodes = (KeyCode[])Enum.GetValues(typeof(KeyCode)); 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)(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_001d: 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)(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 { KeyCode[] keys = ((IEnumerable)str.Split(new char[5] { ' ', '+', ',', ';', '|' }, StringSplitOptions.RemoveEmptyEntries)).Select((Func)((string x) => (KeyCode)Enum.Parse(typeof(KeyCode), x))).ToArray(); return new KeyboardShortcut(keys); } catch (SystemException ex) { Logger.Log(LogLevel.Error, "Failed to read keybind from settings: " + ex.Message); return Empty; } } public string Serialize() { if (_allKeys == null) { return string.Empty; } return string.Join(" + ", _allKeys.Select((KeyCode x) => ((object)(KeyCode)(ref x)).ToString()).ToArray()); } public bool IsDown() { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Invalid comparison between Unknown and I4 //IL_0019: Unknown result type (might be due to invalid IL or missing references) KeyCode mainKey = MainKey; if ((int)mainKey == 0) { return false; } return UnityInput.Current.GetKeyDown(mainKey) && ModifierKeyTest(); } public bool IsPressed() { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Invalid comparison between Unknown and I4 //IL_0019: Unknown result type (might be due to invalid IL or missing references) KeyCode mainKey = MainKey; if ((int)mainKey == 0) { return false; } return UnityInput.Current.GetKey(mainKey) && ModifierKeyTest(); } public bool IsUp() { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Invalid comparison between Unknown and I4 //IL_0019: Unknown result type (might be due to invalid IL or missing references) KeyCode mainKey = MainKey; if ((int)mainKey == 0) { return false; } return UnityInput.Current.GetKeyUp(mainKey) && ModifierKeyTest(); } private bool ModifierKeyTest() { //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) KeyCode[] allKeys = _allKeys; KeyCode mainKey = MainKey; if (!allKeys.All((KeyCode c) => c == mainKey || UnityInput.Current.GetKey(c))) { return false; } if (_modifierBlockKeyCodes == null) { IEnumerable supportedKeyCodes = UnityInput.Current.SupportedKeyCodes; KeyCode[] array = new KeyCode[8]; RuntimeHelpers.InitializeArray(array, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/); _modifierBlockKeyCodes = supportedKeyCodes.Except((IEnumerable)(object)array).ToArray(); } return _modifierBlockKeyCodes.All((KeyCode c) => !UnityInput.Current.GetKey(c) || allKeys.Contains(c)); } public override string ToString() { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Invalid comparison between Unknown and I4 if ((int)MainKey == 0) { return "Not set"; } return string.Join(" + ", _allKeys.Select((KeyCode c) => ((object)(KeyCode)(ref c)).ToString()).ToArray()); } public override bool Equals(object obj) { //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) return obj is KeyboardShortcut keyboardShortcut && MainKey == keyboardShortcut.MainKey && Modifiers.SequenceEqual(keyboardShortcut.Modifiers); } public override int GetHashCode() { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Invalid comparison between Unknown and I4 if ((int)MainKey == 0) { return 0; } return _allKeys.Aggregate(_allKeys.Length, (int current, KeyCode item) => current * 31 + item); } } public sealed class SettingChangedEventArgs : EventArgs { public ConfigEntryBase ChangedSetting { get; } public SettingChangedEventArgs(ConfigEntryBase changedSetting) { ChangedSetting = changedSetting; } } public static class TomlTypeConverter { private static bool _lazyLoadedConverters; private static Dictionary TypeConverters { get; } = new Dictionary { [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) { TypeConverter converter = GetConverter(valueType); if (converter == null) { throw new InvalidOperationException($"Cannot convert from type {valueType}"); } return converter.ConvertToString(value, valueType); } public static T ConvertToValue(string value) { return (T)ConvertToValue(value, typeof(T)); } public static object ConvertToValue(string value, Type valueType) { TypeConverter converter = GetConverter(valueType); if (converter == null) { throw new InvalidOperationException("Cannot convert to type " + valueType.Name); } return converter.ConvertToObject(value, valueType); } public static TypeConverter GetConverter(Type valueType) { if (valueType == null) { throw new ArgumentNullException("valueType"); } if (valueType.IsEnum) { return TypeConverters[typeof(Enum)]; } if (!TypeConverters.TryGetValue(valueType, out var value) && !_lazyLoadedConverters) { _lazyLoadedConverters = true; LazyLoadConverters(); TypeConverters.TryGetValue(valueType, out value); } return value; } public static bool AddConverter(Type type, TypeConverter converter) { if (type == null) { throw new ArgumentNullException("type"); } if (converter == null) { throw new ArgumentNullException("converter"); } if (CanConvert(type)) { Logger.LogWarning("Tried to add a TomlConverter when one already exists for type " + type.FullName); return false; } TypeConverters.Add(type, converter); return true; } public static bool CanConvert(Type type) { return GetConverter(type) != null; } public static IEnumerable GetSupportedTypes() { return TypeConverters.Keys; } private static void LazyLoadConverters() { try { LazyTomlConverterLoader.AddUnityEngineConverters(); } catch (Exception ex) { Logger.LogWarning("Failed to load UnityEngine Toml converters - " + ex.Message); } } private static string Escape(this string txt) { if (string.IsNullOrEmpty(txt)) { return string.Empty; } StringBuilder stringBuilder = new StringBuilder(txt.Length + 2); foreach (char c in txt) { switch (c) { case '\0': stringBuilder.Append("\\0"); break; case '\a': stringBuilder.Append("\\a"); break; case '\b': stringBuilder.Append("\\b"); break; case '\t': stringBuilder.Append("\\t"); break; case '\n': stringBuilder.Append("\\n"); break; case '\v': stringBuilder.Append("\\v"); break; case '\f': stringBuilder.Append("\\f"); break; case '\r': stringBuilder.Append("\\r"); break; case '\'': stringBuilder.Append("\\'"); break; case '\\': stringBuilder.Append("\\"); break; case '"': stringBuilder.Append("\\\""); break; default: stringBuilder.Append(c); break; } } return stringBuilder.ToString(); } private static string Unescape(this string txt) { if (string.IsNullOrEmpty(txt)) { return txt; } StringBuilder stringBuilder = new StringBuilder(txt.Length); int num = 0; while (num < txt.Length) { int num2 = txt.IndexOf('\\', num); if (num2 < 0 || num2 == txt.Length - 1) { num2 = txt.Length; } stringBuilder.Append(txt, num, num2 - num); if (num2 >= txt.Length) { break; } char c = txt[num2 + 1]; switch (c) { case '0': stringBuilder.Append('\0'); break; case 'a': stringBuilder.Append('\a'); break; case 'b': stringBuilder.Append('\b'); break; case 't': stringBuilder.Append('\t'); break; case 'n': stringBuilder.Append('\n'); break; case 'v': stringBuilder.Append('\v'); break; case 'f': stringBuilder.Append('\f'); break; case 'r': stringBuilder.Append('\r'); break; case '\'': stringBuilder.Append('\''); break; case '"': stringBuilder.Append('"'); break; case '\\': stringBuilder.Append('\\'); break; default: stringBuilder.Append('\\').Append(c); break; } num = num2 + 2; } return stringBuilder.ToString(); } } internal static class LazyTomlConverterLoader { [MethodImpl(MethodImplOptions.NoInlining)] public static void AddUnityEngineConverters() { TypeConverter converter = new TypeConverter { ConvertToString = (object obj, Type type) => ColorUtility.ToHtmlStringRGBA((Color)obj), ConvertToObject = delegate(string str, Type type) { //IL_003a: Unknown result type (might be due to invalid IL or missing references) Color val = default(Color); if (!ColorUtility.TryParseHtmlString("#" + str.Trim('#', ' '), ref val)) { throw new FormatException("Invalid color string, expected hex #RRGGBBAA"); } return val; } }; TomlTypeConverter.AddConverter(typeof(Color), converter); TypeConverter converter2 = new TypeConverter { ConvertToString = (object obj, Type type) => JsonUtility.ToJson(obj), ConvertToObject = (string str, Type type) => JsonUtility.FromJson(str, type) }; TomlTypeConverter.AddConverter(typeof(Vector2), converter2); TomlTypeConverter.AddConverter(typeof(Vector3), converter2); TomlTypeConverter.AddConverter(typeof(Vector4), converter2); TomlTypeConverter.AddConverter(typeof(Quaternion), converter2); TomlTypeConverter.AddConverter(typeof(Rect), new TypeConverter { ConvertToObject = StringToRect, ConvertToString = RectToString }); } private static object StringToRect(string s, Type type) { //IL_0003: 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_0145: Unknown result type (might be due to invalid IL or missing references) Rect val = default(Rect); if (s == null) { return val; } string text = s.Trim('{', '}').Replace(" ", ""); string[] array = text.Split(','); foreach (string text2 in array) { string[] array2 = text2.Split(':'); if (array2.Length != 2 || !float.TryParse(array2[1], out var result)) { continue; } string text3 = array2[0].Trim('"'); switch (text3) { case "x": ((Rect)(ref val)).x = result; break; case "y": ((Rect)(ref val)).y = result; break; default: if (!(text3 == "z")) { if (text3 == "height" || text3 == "w") { ((Rect)(ref val)).height = result; } break; } goto case "width"; case "width": ((Rect)(ref val)).width = result; break; } } return val; } private static string RectToString(object o, Type type) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) Rect val = (Rect)o; return string.Format(CultureInfo.InvariantCulture, "{{ \"x\":{0}, \"y\":{1}, \"width\":{2}, \"height\":{3} }}", ((Rect)(ref val)).x, ((Rect)(ref val)).y, ((Rect)(ref val)).width, ((Rect)(ref val)).height); } } public class TypeConverter { public Func ConvertToString { get; set; } public Func ConvertToObject { get; set; } } } namespace BepInEx.Bootstrap { public static class Chainloader { private static readonly List _plugins = new List(); private static bool? isEditor; private static bool _loaded = false; private static bool _initialized = false; private static readonly string CurrentAssemblyName = Assembly.GetExecutingAssembly().GetName().Name; private static readonly Version CurrentAssemblyVersion = Assembly.GetExecutingAssembly().GetName().Version; internal static readonly ConfigEntry ConfigHideBepInExGOs = ConfigFile.CoreConfig.Bind("Chainloader", "HideManagerGameObject", defaultValue: false, new StringBuilder().AppendLine("If enabled, hides BepInEx Manager GameObject from Unity.").AppendLine("This can fix loading issues in some games that attempt to prevent BepInEx from being loaded.").AppendLine("Use this only if you know what this option means, as it can affect functionality of some older plugins.") .ToString()); private static readonly ConfigEntry ConfigUnityLogging = ConfigFile.CoreConfig.Bind("Logging", "UnityLogListening", defaultValue: true, "Enables showing unity log messages in the BepInEx logging system."); private static readonly ConfigEntry ConfigDiskWriteUnityLog = ConfigFile.CoreConfig.Bind("Logging.Disk", "WriteUnityLog", defaultValue: false, "Include unity log messages in log file output."); private static readonly ConfigEntry ConfigDiskAppend = ConfigFile.CoreConfig.Bind("Logging.Disk", "AppendLog", defaultValue: false, "Appends to the log file instead of overwriting, on game startup."); private static readonly ConfigEntry ConfigDiskLogging = ConfigFile.CoreConfig.Bind("Logging.Disk", "Enabled", defaultValue: true, "Enables writing log messages to disk."); private static readonly ConfigEntry ConfigDiskConsoleDisplayedLevel = ConfigFile.CoreConfig.Bind("Logging.Disk", "LogLevels", LogLevel.Fatal | LogLevel.Error | LogLevel.Warning | LogLevel.Message | LogLevel.Info, "Which log leves are saved to the disk log output."); public static Dictionary PluginInfos { get; } = new Dictionary(); private static string UnityVersion { [MethodImpl(MethodImplOptions.NoInlining)] get { return Application.unityVersion; } } private static bool IsHeadless { get { MethodInfo methodInfo = AccessTools.PropertyGetter(typeof(Application), "isBatchMode"); if (methodInfo != null) { return (bool)methodInfo.Invoke(null, null); } return SystemInfo.graphicsDeviceID == 0; } } internal static bool IsEditor { [MethodImpl(MethodImplOptions.NoInlining)] get { bool? flag = isEditor; bool valueOrDefault; if (!flag.HasValue) { bool? flag2 = (isEditor = Application.isEditor); valueOrDefault = flag2.GetValueOrDefault(); } else { valueOrDefault = flag.GetValueOrDefault(); } return valueOrDefault; } } [Obsolete("Use PluginInfos instead")] public static List Plugins { get { lock (_plugins) { _plugins.RemoveAll((BaseUnityPlugin x) => (Object)(object)x == (Object)null); return _plugins.ToList(); } } } public static List DependencyErrors { get; } = new List(); public static GameObject ManagerObject { get; private set; } private static Regex allowedGuidRegex { get; } = new Regex("^[a-zA-Z0-9\\._\\-]+$"); public static void Initialize(string gameExePath, bool startConsole = true, ICollection preloaderLogEvents = null) { if (!_initialized) { ThreadingHelper.Initialize(); if (gameExePath != null) { Paths.SetExecutablePath(gameExePath); } if (ConsoleManager.ConsoleEnabled && startConsole) { ConsoleManager.CreateConsole(); Logger.Listeners.Add(new ConsoleLogListener()); } Logger.InitializeInternalLoggers(); if (ConfigDiskLogging.Value) { Logger.Listeners.Add(new DiskLogListener("LogOutput.log", ConfigDiskConsoleDisplayedLevel.Value, ConfigDiskAppend.Value, ConfigDiskWriteUnityLog.Value)); } if (!TraceLogSource.IsListening) { Logger.Sources.Add(TraceLogSource.CreateSource()); } ReplayPreloaderLogs(preloaderLogEvents); if (ConfigUnityLogging.Value) { Logger.Sources.Add(new UnityLogSource()); } if (!IsHeadless) { Logger.Listeners.Add(new UnityLogListener()); } else if (Logger.Listeners.FirstOrDefault((ILogListener l) => l is ConsoleLogListener) is ConsoleLogListener consoleLogListener) { consoleLogListener.WriteUnityLogs = false; } if (PlatformHelper.Is((Platform)8)) { Logger.LogInfo("Detected Unity version: v" + UnityVersion); } Logger.LogMessage("Chainloader ready"); _initialized = true; } } private static void ReplayPreloaderLogs(ICollection preloaderLogEvents) { if (preloaderLogEvents == null) { return; } UnityLogListener item = new UnityLogListener(); Logger.Listeners.Add(item); ILogListener logListener = Logger.Listeners.FirstOrDefault((ILogListener logger) => logger is ConsoleLogListener); if (logListener != null) { Logger.Listeners.Remove(logListener); } ManualLogSource manualLogSource = Logger.CreateLogSource("Preloader"); foreach (LogEventArgs preloaderLogEvent in preloaderLogEvents) { Logger.InternalLogEvent(manualLogSource, preloaderLogEvent); } Logger.Sources.Remove(manualLogSource); Logger.Listeners.Remove(item); if (logListener != null) { Logger.Listeners.Add(logListener); } } public static PluginInfo ToPluginInfo(TypeDefinition type) { if (type.IsInterface || type.IsAbstract) { return null; } try { if (!type.IsSubtypeOf(typeof(BaseUnityPlugin))) { return null; } } catch (AssemblyResolutionException) { return null; } BepInPlugin bepInPlugin = BepInPlugin.FromCecilType(type); if (bepInPlugin == null) { Logger.LogWarning("Skipping over type [" + ((MemberReference)type).FullName + "] as no metadata attribute is specified"); return null; } if (string.IsNullOrEmpty(bepInPlugin.GUID) || !allowedGuidRegex.IsMatch(bepInPlugin.GUID)) { Logger.LogWarning("Skipping type [" + ((MemberReference)type).FullName + "] because its GUID [" + bepInPlugin.GUID + "] is of an illegal format."); return null; } if (bepInPlugin.Version == null) { Logger.LogWarning("Skipping type [" + ((MemberReference)type).FullName + "] because its version is invalid."); return null; } if (bepInPlugin.Name == null) { Logger.LogWarning("Skipping type [" + ((MemberReference)type).FullName + "] because its name is null."); return null; } List processes = BepInProcess.FromCecilType(type); IEnumerable dependencies = BepInDependency.FromCecilType(type); IEnumerable incompatibilities = BepInIncompatibility.FromCecilType(type); AssemblyNameReference? obj = ((IEnumerable)((MemberReference)type).Module.AssemblyReferences).FirstOrDefault((Func)((AssemblyNameReference reference) => reference.Name == "BepInEx")); Version targettedBepInExVersion = ((obj != null) ? obj.Version : null) ?? new Version(); return new PluginInfo { Metadata = bepInPlugin, Processes = processes, Dependencies = dependencies, Incompatibilities = incompatibilities, TypeName = ((MemberReference)type).FullName, TargettedBepInExVersion = targettedBepInExVersion }; } private static bool HasBepinPlugins(AssemblyDefinition ass) { if (((IEnumerable)ass.MainModule.AssemblyReferences).All((AssemblyNameReference r) => r.Name != CurrentAssemblyName)) { return false; } if (ass.MainModule.GetTypeReferences().All((TypeReference r) => ((MemberReference)r).FullName != typeof(BepInPlugin).FullName)) { return false; } return true; } private static bool PluginTargetsWrongBepin(PluginInfo pluginInfo) { Version targettedBepInExVersion = pluginInfo.TargettedBepInExVersion; if (targettedBepInExVersion.Major != CurrentAssemblyVersion.Major) { return true; } if (targettedBepInExVersion.Minor > CurrentAssemblyVersion.Minor) { return true; } if (targettedBepInExVersion.Minor < CurrentAssemblyVersion.Minor) { return false; } return targettedBepInExVersion.Build > CurrentAssemblyVersion.Build; } public static void Start() { //IL_00cd: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Expected O, but got Unknown if (_loaded) { return; } if (!_initialized) { throw new InvalidOperationException("BepInEx has not been initialized. Please call Chainloader.Initialize prior to starting the chainloader instance."); } if (!Directory.Exists(Paths.PluginPath)) { Directory.CreateDirectory(Paths.PluginPath); } if (!Directory.Exists(Paths.PatcherPluginPath)) { Directory.CreateDirectory(Paths.PatcherPluginPath); } try { PropertyInfo property = typeof(Application).GetProperty("productName", BindingFlags.Static | BindingFlags.Public); if (ConsoleManager.ConsoleActive) { ConsoleManager.SetConsoleTitle($"{CurrentAssemblyName} {CurrentAssemblyVersion} - {property?.GetValue(null, null) ?? Paths.ProcessName}"); } Logger.LogMessage("Chainloader started"); ManagerObject = new GameObject("BepInEx_Manager"); if (ConfigHideBepInExGOs.Value) { ((Object)ManagerObject).hideFlags = (HideFlags)61; } Object.DontDestroyOnLoad((Object)(object)ManagerObject); Dictionary> dictionary = TypeLoader.FindPluginTypes(Paths.PluginPath, ToPluginInfo, HasBepinPlugins, "chainloader"); foreach (KeyValuePair> item in dictionary) { foreach (PluginInfo item2 in item.Value) { item2.Location = item.Key; } } List list = dictionary.SelectMany((KeyValuePair> p) => p.Value).ToList(); Dictionary dictionary2 = new Dictionary(); Logger.LogInfo(string.Format("{0} plugin{1} to load", list.Count, (list.Count == 1) ? "" : "s")); SortedDictionary> dependencyDict = new SortedDictionary>(StringComparer.InvariantCultureIgnoreCase); Dictionary pluginsByGUID = new Dictionary(); foreach (IGrouping item3 in from info in list group info by info.Metadata.GUID) { PluginInfo pluginInfo = null; foreach (PluginInfo item4 in item3.OrderByDescending((PluginInfo x) => x.Metadata.Version)) { if (pluginInfo != null) { Logger.LogWarning($"Skipping [{item4}] because a newer version exists ({pluginInfo})"); continue; } List list2 = item4.Processes.ToList(); if (list2.Count != 0 && list2.All((BepInProcess x) => !string.Equals(x.ProcessName.Replace(".exe", ""), Paths.ProcessName, StringComparison.InvariantCultureIgnoreCase))) { Logger.LogWarning(string.Format("Skipping [{0}] because of process filters ({1})", item4, string.Join(", ", item4.Processes.Select((BepInProcess p) => p.ProcessName).ToArray()))); continue; } pluginInfo = item4; dependencyDict[item4.Metadata.GUID] = item4.Dependencies.Select((BepInDependency d) => d.DependencyGUID); pluginsByGUID[item4.Metadata.GUID] = item4; } } foreach (PluginInfo item5 in pluginsByGUID.Values.ToList()) { if (item5.Incompatibilities.Any((BepInIncompatibility incompatibility) => pluginsByGUID.ContainsKey(incompatibility.IncompatibilityGUID))) { pluginsByGUID.Remove(item5.Metadata.GUID); dependencyDict.Remove(item5.Metadata.GUID); string[] value = (from x in item5.Incompatibilities select x.IncompatibilityGUID into x where pluginsByGUID.ContainsKey(x) select x).ToArray(); string text = string.Format("Could not load [{0}] because it is incompatible with: {1}", item5, string.Join(", ", value)); DependencyErrors.Add(text); Logger.LogError(text); } else if (PluginTargetsWrongBepin(item5)) { string text2 = $"Plugin [{item5}] targets a wrong version of BepInEx ({item5.TargettedBepInExVersion}) and might not work until you update"; DependencyErrors.Add(text2); Logger.LogWarning(text2); } } string[] emptyDependencies = new string[0]; List list3 = Utility.TopologicalSort(dependencyDict.Keys, delegate(string x) { IEnumerable result; if (!dependencyDict.TryGetValue(x, out var value5)) { IEnumerable enumerable = emptyDependencies; result = enumerable; } else { result = value5; } return result; }).ToList(); HashSet hashSet = new HashSet(); Dictionary dictionary3 = new Dictionary(); foreach (string item6 in list3) { if (!pluginsByGUID.TryGetValue(item6, out var value2)) { continue; } bool flag = false; List list4 = new List(); foreach (BepInDependency dependency in value2.Dependencies) { if (!dictionary3.TryGetValue(dependency.DependencyGUID, out var value3) || value3 < dependency.MinimumVersion) { if (IsHardDependency(dependency)) { list4.Add(dependency); } } else if (hashSet.Contains(dependency.DependencyGUID) && IsHardDependency(dependency)) { flag = true; break; } } dictionary3.Add(item6, value2.Metadata.Version); if (flag) { string text3 = $"Skipping [{value2}] because it has a dependency that was not loaded. See previous errors for details."; DependencyErrors.Add(text3); Logger.LogWarning(text3); continue; } if (list4.Count != 0) { string text4 = string.Format("Could not load [{0}] because it has missing dependencies: {1}", value2, string.Join(", ", list4.Select((BepInDependency s) => IsEmptyVersion(s.MinimumVersion) ? s.DependencyGUID : $"{s.DependencyGUID} (v{s.MinimumVersion} or newer)").ToArray())); DependencyErrors.Add(text4); Logger.LogError(text4); hashSet.Add(item6); continue; } try { Logger.LogInfo($"Loading [{value2}]"); if (!dictionary2.TryGetValue(value2.Location, out var value4)) { value4 = (dictionary2[value2.Location] = Assembly.LoadFile(value2.Location)); } PluginInfos[item6] = value2; value2.Instance = (BaseUnityPlugin)(object)ManagerObject.AddComponent(value4.GetType(value2.TypeName)); _plugins.Add(value2.Instance); } catch (Exception ex) { hashSet.Add(item6); PluginInfos.Remove(item6); Logger.LogError($"Error loading [{value2}] : {ex.Message}"); if (ex is ReflectionTypeLoadException ex2) { Logger.LogDebug(TypeLoader.TypeLoadExceptionToString(ex2)); } else { Logger.LogDebug(ex); } } } } catch (Exception ex3) { try { ConsoleManager.CreateConsole(); } catch { } Logger.LogFatal("Error occurred starting the game"); Logger.LogFatal(ex3.ToString()); } Logger.LogMessage("Chainloader startup complete"); _loaded = true; static bool IsEmptyVersion(Version v) { return v.Major == 0 && v.Minor == 0 && v.Build <= 0 && v.Revision <= 0; } static bool IsHardDependency(BepInDependency dep) { return (dep.Flags & BepInDependency.DependencyFlags.HardDependency) != 0; } } } public interface ICacheable { void Save(BinaryWriter bw); void Load(BinaryReader br); } public class CachedAssembly where T : ICacheable { public List CacheItems { get; set; } public long Timestamp { get; set; } } public static class TypeLoader { public static readonly DefaultAssemblyResolver Resolver; public static readonly ReaderParameters ReaderParameters; [CompilerGenerated] [DebuggerBrowsable(DebuggerBrowsableState.Never)] private static AssemblyResolveEventHandler m_AssemblyResolve; private static readonly ConfigEntry EnableAssemblyCache; public static event AssemblyResolveEventHandler AssemblyResolve { [CompilerGenerated] add { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Expected O, but got Unknown AssemblyResolveEventHandler val = TypeLoader.m_AssemblyResolve; AssemblyResolveEventHandler val2; do { val2 = val; AssemblyResolveEventHandler value2 = (AssemblyResolveEventHandler)Delegate.Combine((Delegate?)(object)val2, (Delegate?)(object)value); val = Interlocked.CompareExchange(ref TypeLoader.m_AssemblyResolve, value2, val2); } while (val != val2); } [CompilerGenerated] remove { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Expected O, but got Unknown AssemblyResolveEventHandler val = TypeLoader.m_AssemblyResolve; AssemblyResolveEventHandler val2; do { val2 = val; AssemblyResolveEventHandler value2 = (AssemblyResolveEventHandler)Delegate.Remove((Delegate?)(object)val2, (Delegate?)(object)value); val = Interlocked.CompareExchange(ref TypeLoader.m_AssemblyResolve, value2, val2); } while (val != val2); } } static TypeLoader() { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Expected O, but got Unknown //IL_002a: 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_0050: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Expected O, but got Unknown EnableAssemblyCache = ConfigFile.CoreConfig.Bind("Caching", "EnableAssemblyCache", defaultValue: true, "Enable/disable assembly metadata cache\nEnabling this will speed up discovery of plugins and patchers by caching the metadata of all types BepInEx discovers."); Resolver = new DefaultAssemblyResolver(); ReaderParameters = new ReaderParameters { AssemblyResolver = (IAssemblyResolver)(object)Resolver }; ((BaseAssemblyResolver)Resolver).ResolveFailure += (AssemblyResolveEventHandler)delegate(object sender, AssemblyNameReference reference) { if (!Utility.TryParseAssemblyName(reference.FullName, out var assemblyName)) { AssemblyResolveEventHandler assemblyResolve = TypeLoader.AssemblyResolve; return (assemblyResolve != null) ? assemblyResolve.Invoke(sender, reference) : null; } IEnumerable enumerable = new string[3] { Paths.BepInExAssemblyDirectory, Paths.PluginPath, Paths.PatcherPluginPath }.Concat(Paths.DllSearchPaths); foreach (string item in enumerable) { if (Utility.TryResolveDllAssembly(assemblyName, item, ReaderParameters, out var assembly)) { return assembly; } } AssemblyResolveEventHandler assemblyResolve2 = TypeLoader.AssemblyResolve; return (assemblyResolve2 != null) ? assemblyResolve2.Invoke(sender, reference) : null; }; } public static Dictionary> FindPluginTypes(string directory, Func typeSelector, Func assemblyFilter = null, string cacheName = null) where T : ICacheable, new() { Dictionary> dictionary = new Dictionary>(); Dictionary> dictionary2 = null; if (cacheName != null) { dictionary2 = LoadAssemblyCache(cacheName); } string[] files = Directory.GetFiles(Path.GetFullPath(directory), "*.dll", SearchOption.AllDirectories); foreach (string text in files) { try { if (dictionary2 == null || !dictionary2.TryGetValue(text, out var value)) { goto IL_008b; } long ticks = File.GetLastWriteTimeUtc(text).Ticks; if (ticks != value.Timestamp) { goto IL_008b; } dictionary[text] = value.CacheItems; goto end_IL_0039; IL_008b: AssemblyDefinition val = AssemblyDefinition.ReadAssembly(text, ReaderParameters); if (assemblyFilter != null && !assemblyFilter(val)) { dictionary[text] = new List(); val.Dispose(); continue; } List value2 = (from t in ((IEnumerable)val.MainModule.Types).Select(typeSelector) where t != null select t).ToList(); dictionary[text] = value2; val.Dispose(); end_IL_0039:; } catch (BadImageFormatException ex) { Logger.LogDebug("Skipping loading " + text + " because it's not a valid .NET assembly. Full error: " + ex.Message); } catch (Exception ex2) { Logger.LogError(ex2.ToString()); } } if (cacheName != null) { SaveAssemblyCache(cacheName, dictionary); } return dictionary; } public static Dictionary> LoadAssemblyCache(string cacheName) where T : ICacheable, new() { if (!EnableAssemblyCache.Value) { return null; } Dictionary> dictionary = new Dictionary>(); try { string path = Path.Combine(Paths.CachePath, cacheName + "_typeloader.dat"); if (!File.Exists(path)) { return null; } using BinaryReader binaryReader = new BinaryReader(File.OpenRead(path)); int num = binaryReader.ReadInt32(); for (int i = 0; i < num; i++) { string key = binaryReader.ReadString(); long timestamp = binaryReader.ReadInt64(); int num2 = binaryReader.ReadInt32(); List list = new List(); for (int j = 0; j < num2; j++) { T item = new T(); item.Load(binaryReader); list.Add(item); } dictionary[key] = new CachedAssembly { Timestamp = timestamp, CacheItems = list }; } } catch (Exception ex) { Logger.LogWarning("Failed to load cache \"" + cacheName + "\"; skipping loading cache. Reason: " + ex.Message + "."); } return dictionary; } public static void SaveAssemblyCache(string cacheName, Dictionary> entries) where T : ICacheable { if (!EnableAssemblyCache.Value) { return; } try { if (!Directory.Exists(Paths.CachePath)) { Directory.CreateDirectory(Paths.CachePath); } string path = Path.Combine(Paths.CachePath, cacheName + "_typeloader.dat"); using BinaryWriter binaryWriter = new BinaryWriter(File.OpenWrite(path)); binaryWriter.Write(entries.Count); foreach (KeyValuePair> entry in entries) { binaryWriter.Write(entry.Key); binaryWriter.Write(File.GetLastWriteTimeUtc(entry.Key).Ticks); binaryWriter.Write(entry.Value.Count); foreach (T item in entry.Value) { item.Save(binaryWriter); } } } catch (Exception ex) { Logger.LogWarning("Failed to save cache \"" + cacheName + "\"; skipping saving cache. Reason: " + ex.Message + "."); } } public static string TypeLoadExceptionToString(ReflectionTypeLoadException ex) { StringBuilder stringBuilder = new StringBuilder(); Exception[] loaderExceptions = ex.LoaderExceptions; foreach (Exception ex2 in loaderExceptions) { stringBuilder.AppendLine(ex2.Message); if (ex2 is FileNotFoundException ex3) { if (!string.IsNullOrEmpty(ex3.FusionLog)) { stringBuilder.AppendLine("Fusion Log:"); stringBuilder.AppendLine(ex3.FusionLog); } } else if (ex2 is FileLoadException ex4 && !string.IsNullOrEmpty(ex4.FusionLog)) { stringBuilder.AppendLine("Fusion Log:"); stringBuilder.AppendLine(ex4.FusionLog); } stringBuilder.AppendLine(); } return stringBuilder.ToString(); } } }