diff --git a/BepInEx.Core/Bootstrap/TypeLoader.cs b/BepInEx.Core/Bootstrap/TypeLoader.cs index 3bc5a3b..69695b0 100644 --- a/BepInEx.Core/Bootstrap/TypeLoader.cs +++ b/BepInEx.Core/Bootstrap/TypeLoader.cs @@ -75,7 +75,7 @@ namespace BepInEx.Bootstrap static TypeLoader() { CecilResolver = new DefaultAssemblyResolver(); - ReaderParameters = new ReaderParameters {AssemblyResolver = CecilResolver}; + ReaderParameters = new ReaderParameters { AssemblyResolver = CecilResolver }; CecilResolver.ResolveFailure += CecilResolveOnFailure; } @@ -126,7 +126,8 @@ namespace BepInEx.Bootstrap public static Dictionary> FindPluginTypes(string directory, Func typeSelector, Func assemblyFilter = - null, string cacheName = null) + null, + string cacheName = null) where T : ICacheable, new() { var result = new Dictionary>(); @@ -220,7 +221,7 @@ namespace BepInEx.Bootstrap items.Add(entry); } - result[entryIdentifier] = new CachedAssembly {Timestamp = entryDate, CacheItems = items}; + result[entryIdentifier] = new CachedAssembly { Timestamp = entryDate, CacheItems = items }; } } } diff --git a/BepInEx.Core/Configuration/AcceptableValueList.cs b/BepInEx.Core/Configuration/AcceptableValueList.cs index 78eca37..488a2b9 100644 --- a/BepInEx.Core/Configuration/AcceptableValueList.cs +++ b/BepInEx.Core/Configuration/AcceptableValueList.cs @@ -36,15 +36,10 @@ namespace BepInEx.Configuration } /// - public override bool IsValid(object value) - { - return value is T v && AcceptableValues.Any(x => x.Equals(v)); - } + public override bool IsValid(object value) => value is T v && AcceptableValues.Any(x => x.Equals(v)); /// - public override string ToDescriptionString() - { - return "# Acceptable values: " + string.Join(", ", AcceptableValues.Select(x => x.ToString()).ToArray()); - } + public override string ToDescriptionString() => + "# Acceptable values: " + string.Join(", ", AcceptableValues.Select(x => x.ToString()).ToArray()); } } diff --git a/BepInEx.Core/Configuration/ConfigDefinition.cs b/BepInEx.Core/Configuration/ConfigDefinition.cs index b232030..1168c1e 100644 --- a/BepInEx.Core/Configuration/ConfigDefinition.cs +++ b/BepInEx.Core/Configuration/ConfigDefinition.cs @@ -11,7 +11,7 @@ namespace BepInEx.Configuration /// public class ConfigDefinition : IEquatable { - private static readonly char[] _invalidConfigChars = {'=', '\n', '\t', '\\', '"', '\'', '[', ']'}; + private static readonly char[] _invalidConfigChars = { '=', '\n', '\t', '\\', '"', '\'', '[', ']' }; /// /// Create a new definition. Definitions with same section and key are equal. @@ -52,7 +52,7 @@ namespace BepInEx.Configuration { if (other == null) return false; return string.Equals(Key, other.Key) - && string.Equals(Section, other.Section); + && string.Equals(Section, other.Section); } private static void CheckInvalidConfigChars(string val, string name) diff --git a/BepInEx.Core/Configuration/ConfigEntryBase.cs b/BepInEx.Core/Configuration/ConfigEntryBase.cs index bb03909..74fa1a4 100644 --- a/BepInEx.Core/Configuration/ConfigEntryBase.cs +++ b/BepInEx.Core/Configuration/ConfigEntryBase.cs @@ -13,15 +13,15 @@ namespace BepInEx.Configuration { private T _typedValue; - internal ConfigEntry(ConfigFile configFile, ConfigDefinition definition, T defaultValue, + internal ConfigEntry(ConfigFile configFile, + ConfigDefinition definition, + T defaultValue, ConfigDescription configDescription) : base(configFile, definition, typeof(T), - defaultValue, configDescription) - { + defaultValue, configDescription) => configFile.SettingChanged += (sender, args) => { if (args.ChangedSetting == this) SettingChanged?.Invoke(sender, args); }; - } /// /// Value of this setting. @@ -62,8 +62,11 @@ namespace BepInEx.Configuration /// /// Types of defaultValue and definition.AcceptableValues have to be the same as settingType. /// - internal ConfigEntryBase(ConfigFile configFile, ConfigDefinition definition, Type settingType, - object defaultValue, ConfigDescription configDescription) + internal ConfigEntryBase(ConfigFile configFile, + ConfigDefinition definition, + Type settingType, + object defaultValue, + ConfigDescription configDescription) { ConfigFile = configFile ?? throw new ArgumentNullException(nameof(configFile)); Definition = definition ?? throw new ArgumentNullException(nameof(definition)); @@ -147,10 +150,7 @@ namespace BepInEx.Configuration /// /// Trigger setting changed event. /// - protected void OnSettingChanged(object sender) - { - ConfigFile.OnSettingChanged(sender, this); - } + protected void OnSettingChanged(object sender) => ConfigFile.OnSettingChanged(sender, this); /// /// Write a description of this setting using all available metadata. diff --git a/BepInEx.Core/Configuration/ConfigFile.cs b/BepInEx.Core/Configuration/ConfigFile.cs index e89f643..882d731 100644 --- a/BepInEx.Core/Configuration/ConfigFile.cs +++ b/BepInEx.Core/Configuration/ConfigFile.cs @@ -109,7 +109,8 @@ namespace BepInEx.Configuration } void ICollection>.CopyTo( - KeyValuePair[] array, int arrayIndex) + KeyValuePair[] array, + int arrayIndex) { lock (_ioLock) ((ICollection>) Entries).CopyTo(array, arrayIndex); @@ -143,10 +144,8 @@ namespace BepInEx.Configuration } /// - public void Add(ConfigDefinition key, ConfigEntryBase value) - { + public void Add(ConfigDefinition key, ConfigEntryBase value) => throw new InvalidOperationException("Directly adding a config entry is not supported"); - } /// public bool Remove(ConfigDefinition key) @@ -251,7 +250,7 @@ namespace BepInEx.Configuration continue; } - var split = line.Split(new[] {'='}, 2); //actual config line + var split = line.Split(new[] { '=' }, 2); //actual config line if (split.Length != 2) continue; //empty/invalid line @@ -399,7 +398,8 @@ namespace BepInEx.Configuration /// Section and Key of the setting. /// Value of the setting if the setting was not created yet. /// Description of the setting shown to the user and other metadata. - public ConfigEntry Bind(ConfigDefinition configDefinition, T defaultValue, + public ConfigEntry Bind(ConfigDefinition configDefinition, + T defaultValue, ConfigDescription configDescription = null) { if (!TomlTypeConverter.CanConvert(typeof(T))) @@ -438,7 +438,9 @@ namespace BepInEx.Configuration /// Name of the setting. /// Value of the setting if the setting was not created yet. /// Description of the setting shown to the user and other metadata. - public ConfigEntry Bind(string section, string key, T defaultValue, + public ConfigEntry Bind(string section, + string key, + T defaultValue, ConfigDescription configDescription = null) => Bind(new ConfigDefinition(section, key), defaultValue, configDescription); @@ -464,7 +466,8 @@ namespace BepInEx.Configuration /// Value of the setting if the setting was not created yet. /// Description of the setting shown to the user and other metadata. [Obsolete("Use Bind instead")] - public ConfigEntry AddSetting(ConfigDefinition configDefinition, T defaultValue, + public ConfigEntry AddSetting(ConfigDefinition configDefinition, + T defaultValue, ConfigDescription configDescription = null) => Bind(configDefinition, defaultValue, configDescription); @@ -479,7 +482,9 @@ namespace BepInEx.Configuration /// Value of the setting if the setting was not created yet. /// Description of the setting shown to the user and other metadata. [Obsolete("Use Bind instead")] - public ConfigEntry AddSetting(string section, string key, T defaultValue, + public ConfigEntry AddSetting(string section, + string key, + T defaultValue, ConfigDescription configDescription = null) => Bind(new ConfigDefinition(section, key), defaultValue, configDescription); diff --git a/BepInEx.Core/Console/Unix/ConsoleWriter.cs b/BepInEx.Core/Console/Unix/ConsoleWriter.cs index 4c6764a..4e03679 100644 --- a/BepInEx.Core/Console/Unix/ConsoleWriter.cs +++ b/BepInEx.Core/Console/Unix/ConsoleWriter.cs @@ -22,12 +22,12 @@ namespace BepInEx.Unix Func GetCtor(int[] perm) { - var parameters = new[] {typeof(Stream), typeof(Encoding), typeof(bool)}; + var parameters = new[] { typeof(Stream), typeof(Encoding), typeof(bool) }; var ctor = AccessTools.Constructor(cStreamWriter, perm.Select(i => parameters[i]).ToArray()); if (ctor != null) return (stream, encoding, l) => { - var vals = new object[] {stream, encoding, l}; + var vals = new object[] { stream, encoding, l }; return (StreamWriter) ctor.Invoke(perm.Select(i => vals[i]).ToArray()); }; return null; @@ -35,8 +35,8 @@ namespace BepInEx.Unix var ctorParams = new[] { - new[] {0, 1, 2}, // Unity 5.x and up - new[] {0, 1} // Unity 4.7 and older + new[] { 0, 1, 2 }, // Unity 5.x and up + new[] { 0, 1 } // Unity 4.7 and older }; cStreamWriterConstructor = ctorParams.Select(GetCtor).FirstOrDefault(f => f != null); diff --git a/BepInEx.Core/Console/Unix/LinuxConsoleDriver.cs b/BepInEx.Core/Console/Unix/LinuxConsoleDriver.cs index 2ce1046..f7d93b0 100644 --- a/BepInEx.Core/Console/Unix/LinuxConsoleDriver.cs +++ b/BepInEx.Core/Console/Unix/LinuxConsoleDriver.cs @@ -66,15 +66,11 @@ namespace BepInEx.Unix ConsoleOut = StandardOut; } - public void CreateConsole(uint codepage) - { + public void CreateConsole(uint codepage) => Logger.LogWarning("An external console currently cannot be spawned on a Unix platform."); - } - public void DetachConsole() - { + public void DetachConsole() => throw new PlatformNotSupportedException("Cannot detach console on a Unix platform"); - } public void SetConsoleColor(ConsoleColor color) { diff --git a/BepInEx.Core/Console/Unix/TtyHandler.cs b/BepInEx.Core/Console/Unix/TtyHandler.cs index b874919..db57b34 100644 --- a/BepInEx.Core/Console/Unix/TtyHandler.cs +++ b/BepInEx.Core/Console/Unix/TtyHandler.cs @@ -141,7 +141,7 @@ namespace BepInEx.Unix var colorOffset = baseOffset - + intSize * (int) TermInfoNumbers.MaxColors; // Finally the offset for the max color integer + + intSize * (int) TermInfoNumbers.MaxColors; // Finally the offset for the max color integer //int stringOffset = baseOffset + (intSize * intFieldLength); @@ -168,13 +168,13 @@ namespace BepInEx.Unix private static int GetInt32(byte[] buffer, int offset) => buffer[offset] - | (buffer[offset + 1] << 8) - | (buffer[offset + 2] << 16) - | (buffer[offset + 3] << 24); + | (buffer[offset + 1] << 8) + | (buffer[offset + 2] << 16) + | (buffer[offset + 3] << 24); private static short GetInt16(byte[] buffer, int offset) => (short) (buffer[offset] - | (buffer[offset + 1] << 8)); + | (buffer[offset + 1] << 8)); private static int GetInteger(int intSize, byte[] buffer, int offset) => intSize == 2 diff --git a/BepInEx.Core/Console/Unix/UnixStream.cs b/BepInEx.Core/Console/Unix/UnixStream.cs index a3b2105..9db012d 100644 --- a/BepInEx.Core/Console/Unix/UnixStream.cs +++ b/BepInEx.Core/Console/Unix/UnixStream.cs @@ -31,17 +31,11 @@ namespace BepInEx.Unix public IntPtr FileHandle { get; } - public override void Flush() - { - UnixStreamHelper.fflush(FileHandle); - } + 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 void SetLength(long value) => throw new InvalidOperationException(); public override int Read(byte[] buffer, int offset, int count) { @@ -65,10 +59,7 @@ namespace BepInEx.Unix gcHandle.Free(); } - private void ReleaseUnmanagedResources() - { - UnixStreamHelper.fclose(FileHandle); - } + private void ReleaseUnmanagedResources() => UnixStreamHelper.fclose(FileHandle); protected override void Dispose(bool disposing) { @@ -76,9 +67,6 @@ namespace BepInEx.Unix base.Dispose(disposing); } - ~UnixStream() - { - Dispose(false); - } + ~UnixStream() => Dispose(false); } } diff --git a/BepInEx.Core/Console/Windows/ConsoleEncoding/ConsoleEncoding.PInvoke.cs b/BepInEx.Core/Console/Windows/ConsoleEncoding/ConsoleEncoding.PInvoke.cs index 994b6e8..1e4f0d3 100644 --- a/BepInEx.Core/Console/Windows/ConsoleEncoding/ConsoleEncoding.PInvoke.cs +++ b/BepInEx.Core/Console/Windows/ConsoleEncoding/ConsoleEncoding.PInvoke.cs @@ -24,26 +24,24 @@ namespace UnityInjector.ConsoleUtil 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); + 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); + 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); } } diff --git a/BepInEx.Core/Console/Windows/ConsoleWindow.cs b/BepInEx.Core/Console/Windows/ConsoleWindow.cs index 01ba1c3..0c8b2ec 100644 --- a/BepInEx.Core/Console/Windows/ConsoleWindow.cs +++ b/BepInEx.Core/Console/Windows/ConsoleWindow.cs @@ -99,14 +99,13 @@ namespace UnityInjector.ConsoleUtil 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); + private static extern IntPtr CreateFile(string fileName, + uint desiredAccess, + int shareMode, + IntPtr securityAttributes, + int creationDisposition, + int flagsAndAttributes, + IntPtr templateFile); [DllImport("kernel32.dll", SetLastError = false)] private static extern bool FreeConsole(); diff --git a/BepInEx.Core/Console/Windows/Kon.cs b/BepInEx.Core/Console/Windows/Kon.cs index e218d91..52fcb0e 100644 --- a/BepInEx.Core/Console/Windows/Kon.cs +++ b/BepInEx.Core/Console/Windows/Kon.cs @@ -103,7 +103,7 @@ namespace BepInEx.ConsoleUtil if (!flag) return; var num = bufferInfo.wAttributes; - num &= isBackground ? (short)-241 : (short)-16; + num &= isBackground ? (short) -241 : (short) -16; num = (short) ((ushort) num | (ushort) color); SetConsoleTextAttribute(conOut, num); } diff --git a/BepInEx.Core/Console/Windows/WindowsConsoleDriver.cs b/BepInEx.Core/Console/Windows/WindowsConsoleDriver.cs index 04ea189..d91d11e 100644 --- a/BepInEx.Core/Console/Windows/WindowsConsoleDriver.cs +++ b/BepInEx.Core/Console/Windows/WindowsConsoleDriver.cs @@ -18,8 +18,8 @@ namespace BepInEx // As such, we're trying to use SafeFileHandle when it's available and go back to IntPtr overload if not available private static readonly ConstructorInfo FileStreamCtor = new[] { - AccessTools.Constructor(typeof(FileStream), new[] {typeof(SafeFileHandle), typeof(FileAccess)}), - AccessTools.Constructor(typeof(FileStream), new[] {typeof(IntPtr), typeof(FileAccess)}) + AccessTools.Constructor(typeof(FileStream), new[] { typeof(SafeFileHandle), typeof(FileAccess) }), + AccessTools.Constructor(typeof(FileStream), new[] { typeof(IntPtr), typeof(FileAccess) }) }.FirstOrDefault(m => m != null); public TextWriter StandardOut { get; private set; } @@ -85,10 +85,7 @@ namespace BepInEx Kon.ForegroundColor = color; } - public void SetConsoleTitle(string title) - { - ConsoleWindow.Title = title; - } + public void SetConsoleTitle(string title) => ConsoleWindow.Title = title; private static FileStream OpenFileStream(IntPtr handle) { diff --git a/BepInEx.Core/Contract/Attributes.cs b/BepInEx.Core/Contract/Attributes.cs index 6afa32b..cd6438c 100644 --- a/BepInEx.Core/Contract/Attributes.cs +++ b/BepInEx.Core/Contract/Attributes.cs @@ -186,15 +186,9 @@ namespace BepInEx /// public string IncompatibilityGUID { get; protected set; } - void ICacheable.Save(BinaryWriter bw) - { - bw.Write(IncompatibilityGUID); - } + void ICacheable.Save(BinaryWriter bw) => bw.Write(IncompatibilityGUID); - void ICacheable.Load(BinaryReader br) - { - IncompatibilityGUID = br.ReadString(); - } + void ICacheable.Load(BinaryReader br) => IncompatibilityGUID = br.ReadString(); internal static IEnumerable FromCecilType(TypeDefinition td) { diff --git a/BepInEx.Core/Logging/DiskLogListener.cs b/BepInEx.Core/Logging/DiskLogListener.cs index 6aa2259..2faf1b4 100644 --- a/BepInEx.Core/Logging/DiskLogListener.cs +++ b/BepInEx.Core/Logging/DiskLogListener.cs @@ -25,8 +25,11 @@ namespace BepInEx.Logging /// when debugging crashes. /// /// Maximum amount of concurrently opened log files. Can help with infinite game boot loops. - public DiskLogListener(string localPath, LogLevel displayedLogLevel = LogLevel.Info, bool appendLog = false, - bool delayedFlushing = true, int fileLimit = 5) + public DiskLogListener(string localPath, + LogLevel displayedLogLevel = LogLevel.Info, + bool appendLog = false, + bool delayedFlushing = true, + int fileLimit = 5) { DisplayedLogLevel = displayedLogLevel; @@ -97,17 +100,14 @@ namespace BepInEx.Logging { FlushTimer?.Dispose(); - try - { - LogWriter?.Flush(); - LogWriter?.Dispose(); + try + { + LogWriter?.Flush(); + LogWriter?.Dispose(); + } + catch (ObjectDisposedException) { } } - catch (ObjectDisposedException) {} - } - ~DiskLogListener() - { - Dispose(); - } + ~DiskLogListener() => Dispose(); } } diff --git a/BepInEx.Core/Logging/HarmonyLogSource.cs b/BepInEx.Core/Logging/HarmonyLogSource.cs index 852cc76..e12fd34 100644 --- a/BepInEx.Core/Logging/HarmonyLogSource.cs +++ b/BepInEx.Core/Logging/HarmonyLogSource.cs @@ -27,10 +27,7 @@ namespace BepInEx.Logging HarmonyLogger.MessageReceived += HandleHarmonyMessage; } - public void Dispose() - { - HarmonyLogger.MessageReceived -= HandleHarmonyMessage; - } + public void Dispose() => HarmonyLogger.MessageReceived -= HandleHarmonyMessage; public string SourceName { get; } = "HarmonyX"; public event EventHandler LogEvent; diff --git a/BepInEx.Core/Logging/LogLevel.cs b/BepInEx.Core/Logging/LogLevel.cs index 7626656..c24d213 100644 --- a/BepInEx.Core/Logging/LogLevel.cs +++ b/BepInEx.Core/Logging/LogLevel.cs @@ -81,13 +81,13 @@ namespace BepInEx.Logging level = GetHighestLevel(level); return level switch { - LogLevel.Fatal => ConsoleColor.Red, - LogLevel.Error => ConsoleColor.DarkRed, + LogLevel.Fatal => ConsoleColor.Red, + LogLevel.Error => ConsoleColor.DarkRed, LogLevel.Warning => ConsoleColor.Yellow, LogLevel.Message => ConsoleColor.White, - LogLevel.Info => ConsoleColor.DarkGray, - LogLevel.Debug => ConsoleColor.DarkGray, - _ => ConsoleColor.Gray + LogLevel.Info => ConsoleColor.DarkGray, + LogLevel.Debug => ConsoleColor.DarkGray, + _ => ConsoleColor.Gray }; } } diff --git a/BepInEx.Core/Logging/Logger.cs b/BepInEx.Core/Logging/Logger.cs index 48ad1ec..48914ff 100644 --- a/BepInEx.Core/Logging/Logger.cs +++ b/BepInEx.Core/Logging/Logger.cs @@ -38,10 +38,7 @@ namespace BepInEx.Logging /// /// The level of the entry. /// The data of the entry. - internal static void Log(LogLevel level, object data) - { - InternalLogSource.Log(level, data); - } + 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); diff --git a/BepInEx.Core/Logging/ManualLogSource.cs b/BepInEx.Core/Logging/ManualLogSource.cs index 123f640..4e45a11 100644 --- a/BepInEx.Core/Logging/ManualLogSource.cs +++ b/BepInEx.Core/Logging/ManualLogSource.cs @@ -27,10 +27,7 @@ namespace BepInEx.Logging /// /// Log levels to attach to the message. Multiple can be used with bitwise ORing. /// Data to log. - public void Log(LogLevel level, object data) - { - LogEvent?.Invoke(this, new LogEventArgs(data, level, this)); - } + public void Log(LogLevel level, object data) => LogEvent?.Invoke(this, new LogEventArgs(data, level, this)); /// /// Logs a message with level. diff --git a/BepInEx.Core/Logging/TraceLogSource.cs b/BepInEx.Core/Logging/TraceLogSource.cs index 14d9496..8c60a78 100644 --- a/BepInEx.Core/Logging/TraceLogSource.cs +++ b/BepInEx.Core/Logging/TraceLogSource.cs @@ -45,36 +45,37 @@ namespace BepInEx.Logging /// Writes a message to the underlying instance. /// /// The message to write. - public override void Write(string message) - { - LogSource.LogInfo(message); - } + public override void Write(string message) => LogSource.LogInfo(message); /// /// Writes a message and a newline to the underlying instance. /// /// The message to write. - public override void WriteLine(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) => + 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, + public override void TraceEvent(TraceEventCache eventCache, + string source, + TraceEventType eventType, + int id, string message) { var level = eventType switch { - TraceEventType.Critical => LogLevel.Fatal, - TraceEventType.Error => LogLevel.Error, - TraceEventType.Warning => LogLevel.Warning, + TraceEventType.Critical => LogLevel.Fatal, + TraceEventType.Error => LogLevel.Error, + TraceEventType.Warning => LogLevel.Warning, TraceEventType.Information => LogLevel.Info, - _ => LogLevel.Debug + _ => LogLevel.Debug }; LogSource.Log(level, $"{message}".Trim()); } diff --git a/BepInEx.Core/Paths.cs b/BepInEx.Core/Paths.cs index e3e10e2..6b73b20 100644 --- a/BepInEx.Core/Paths.cs +++ b/BepInEx.Core/Paths.cs @@ -78,7 +78,8 @@ namespace BepInEx /// public static string ProcessName { get; private set; } - public static void SetExecutablePath(string executablePath, string bepinRootPath = null, + public static void SetExecutablePath(string executablePath, + string bepinRootPath = null, string managedPath = null) { ExecutablePath = executablePath; @@ -100,9 +101,7 @@ namespace BepInEx CachePath = Path.Combine(BepInExRootPath, "cache"); } - internal static void SetPluginPath(string pluginPath) - { + internal static void SetPluginPath(string pluginPath) => PluginPath = Utility.CombinePaths(BepInExRootPath, pluginPath); - } } } diff --git a/BepInEx.Core/Utility.cs b/BepInEx.Core/Utility.cs index 9ec52f0..f17dd16 100644 --- a/BepInEx.Core/Utility.cs +++ b/BepInEx.Core/Utility.cs @@ -169,15 +169,17 @@ namespace BepInEx /// Directory to search the assembly from. /// The loaded assembly. /// True, if the assembly was found and loaded. Otherwise, false. - private static bool TryResolveDllAssembly(AssemblyName assemblyName, string directory, - Func loader, out T assembly) where T : class + private static bool TryResolveDllAssembly(AssemblyName assemblyName, + string directory, + Func loader, + out T assembly) where T : class { assembly = null; - var potentialDirectories = new List {directory}; + var potentialDirectories = new List { directory }; - if (!Directory.Exists(directory)) - return false; + if (!Directory.Exists(directory)) + return false; potentialDirectories.AddRange(Directory.GetDirectories(directory, "*", SearchOption.AllDirectories)); @@ -243,12 +245,12 @@ namespace BepInEx /// Reader parameters that contain possible custom assembly resolver. /// The loaded assembly. /// True, if the assembly was found and loaded. Otherwise, false. - public static bool TryResolveDllAssembly(AssemblyName assemblyName, string directory, - ReaderParameters readerParameters, out AssemblyDefinition assembly) - { - return TryResolveDllAssembly(assemblyName, directory, - s => AssemblyDefinition.ReadAssembly(s, readerParameters), out assembly); - } + public static bool TryResolveDllAssembly(AssemblyName assemblyName, + string directory, + ReaderParameters readerParameters, + out AssemblyDefinition assembly) => + TryResolveDllAssembly(assemblyName, directory, + s => AssemblyDefinition.ReadAssembly(s, readerParameters), out assembly); /// /// Tries to create a file with the given name @@ -259,8 +261,11 @@ namespace BepInEx /// File access options /// File share options /// - public static bool TryOpenFileStream(string path, FileMode mode, out FileStream fileStream, - FileAccess access = FileAccess.ReadWrite, FileShare share = FileShare.Read) + public static bool TryOpenFileStream(string path, + FileMode mode, + out FileStream fileStream, + FileAccess access = FileAccess.ReadWrite, + FileShare share = FileShare.Read) { try { diff --git a/BepInEx.IL2CPP/DoorstopEntrypoint.cs b/BepInEx.IL2CPP/DoorstopEntrypoint.cs index 2687ebf..30399f9 100644 --- a/BepInEx.IL2CPP/DoorstopEntrypoint.cs +++ b/BepInEx.IL2CPP/DoorstopEntrypoint.cs @@ -45,9 +45,9 @@ namespace BepInEx.IL2CPP return foundAssembly; if (Utility.TryResolveDllAssembly(assemblyName, Paths.BepInExAssemblyDirectory, out foundAssembly) - || Utility.TryResolveDllAssembly(assemblyName, Paths.PatcherPluginPath, out foundAssembly) - || Utility.TryResolveDllAssembly(assemblyName, Paths.PluginPath, out foundAssembly) - || Utility.TryResolveDllAssembly(assemblyName, Preloader.IL2CPPUnhollowedPath, out foundAssembly)) + || Utility.TryResolveDllAssembly(assemblyName, Paths.PatcherPluginPath, out foundAssembly) + || Utility.TryResolveDllAssembly(assemblyName, Paths.PluginPath, out foundAssembly) + || Utility.TryResolveDllAssembly(assemblyName, Preloader.IL2CPPUnhollowedPath, out foundAssembly)) return foundAssembly; return null; diff --git a/BepInEx.IL2CPP/Hook/Allocator/MacOsPageAllocator.cs b/BepInEx.IL2CPP/Hook/Allocator/MacOsPageAllocator.cs index 33e8db6..fc4aa17 100644 --- a/BepInEx.IL2CPP/Hook/Allocator/MacOsPageAllocator.cs +++ b/BepInEx.IL2CPP/Hook/Allocator/MacOsPageAllocator.cs @@ -71,8 +71,12 @@ namespace BepInEx.IL2CPP.Hook.Allocator public static vm_region_64Delegate vm_region_64; #pragma warning restore 649 - public delegate int vm_region_64Delegate(nint target_task, ref nint address, ref nint size, int flavor, - ref vm_region_basic_info_64 info, ref uint infoCnt, + public delegate int vm_region_64Delegate(nint target_task, + ref nint address, + ref nint size, + int flavor, + ref vm_region_basic_info_64 info, + ref uint infoCnt, ref uint object_name); // ReSharper restore InconsistentNaming } diff --git a/BepInEx.IL2CPP/Hook/Allocator/PageAllocator.cs b/BepInEx.IL2CPP/Hook/Allocator/PageAllocator.cs index 43ce9b3..e30d13a 100644 --- a/BepInEx.IL2CPP/Hook/Allocator/PageAllocator.cs +++ b/BepInEx.IL2CPP/Hook/Allocator/PageAllocator.cs @@ -111,16 +111,14 @@ namespace BepInEx.IL2CPP.Hook.Allocator [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsInRelJmpRange(nint src, nint dst) => dst - src is <= int.MaxValue and >= int.MinValue; - private static PageAllocator Init() - { - return PlatformHelper.Current switch + private static PageAllocator Init() => + PlatformHelper.Current switch { var v when v.Is(Platform.Windows) => new WindowsPageAllocator(), - var v when v.Is(Platform.Linux) => new LinuxPageAllocator(), - var v when v.Is(Platform.MacOS) => new MacOsPageAllocator(), - _ => throw new NotSupportedException() + var v when v.Is(Platform.Linux) => new LinuxPageAllocator(), + var v when v.Is(Platform.MacOS) => new MacOsPageAllocator(), + _ => throw new NotSupportedException() }; - } private class PageChunk { diff --git a/BepInEx.IL2CPP/Hook/Allocator/UnixPageAllocator.cs b/BepInEx.IL2CPP/Hook/Allocator/UnixPageAllocator.cs index 5037322..c4f73bd 100644 --- a/BepInEx.IL2CPP/Hook/Allocator/UnixPageAllocator.cs +++ b/BepInEx.IL2CPP/Hook/Allocator/UnixPageAllocator.cs @@ -72,7 +72,7 @@ namespace BepInEx.IL2CPP.Hook.Allocator { var (start, end) = GetFreeArea(hint); // Try to allocate to end (after original method) first, then try before - var addrs = new[] {end, start}; + var addrs = new[] { end, start }; foreach (var addr in addrs) { if (addr == 0) @@ -92,7 +92,11 @@ namespace BepInEx.IL2CPP.Hook.Allocator private static class Unix { - public delegate nint mmapDelegate(nint addr, nuint length, Protection prot, MapFlags flags, int fd, + public delegate nint mmapDelegate(nint addr, + nuint length, + Protection prot, + MapFlags flags, + int fd, int offset); public delegate int munmapDelegate(nint addr, nuint length); @@ -113,8 +117,7 @@ namespace BepInEx.IL2CPP.Hook.Allocator public static readonly nint MAP_FAILED = -1; - static Unix() - { + static Unix() => typeof(Unix).ResolveDynDllImports(new Dictionary> { ["libc"] = new() @@ -124,7 +127,6 @@ namespace BepInEx.IL2CPP.Hook.Allocator "/usr/lib/libSystem.dylib" // OSX POSIX } }); - } #pragma warning disable 649 // Set by MonoMod [DynDllImport("mmap")] diff --git a/BepInEx.IL2CPP/Hook/Allocator/WindowsPageAllocator.cs b/BepInEx.IL2CPP/Hook/Allocator/WindowsPageAllocator.cs index c2def50..48f0618 100644 --- a/BepInEx.IL2CPP/Hook/Allocator/WindowsPageAllocator.cs +++ b/BepInEx.IL2CPP/Hook/Allocator/WindowsPageAllocator.cs @@ -111,7 +111,9 @@ namespace BepInEx.IL2CPP.Hook.Allocator public static extern int VirtualQuery(nint lpAddress, ref MEMORY_BASIC_INFORMATION lpBuffer, int dwLength); [DllImport("kernel32", SetLastError = true)] - public static extern nint VirtualAlloc(nint lpAddress, nuint dwSize, AllocationType flAllocationType, + public static extern nint VirtualAlloc(nint lpAddress, + nuint dwSize, + AllocationType flAllocationType, ProtectConstant flProtect); [DllImport("kernel32", SetLastError = true)] diff --git a/BepInEx.IL2CPP/Hook/DetourGenerator.cs b/BepInEx.IL2CPP/Hook/DetourGenerator.cs index d37d765..4b0d3e1 100644 --- a/BepInEx.IL2CPP/Hook/DetourGenerator.cs +++ b/BepInEx.IL2CPP/Hook/DetourGenerator.cs @@ -54,7 +54,9 @@ namespace BepInEx.IL2CPP /// The minimum amount of length that the detour should consume. If the generated redirect is /// smaller than this, the remaining space is padded with NOPs. /// - public static void ApplyDetour(IntPtr functionPtr, IntPtr detourPtr, Architecture architecture, + public static void ApplyDetour(IntPtr functionPtr, + IntPtr detourPtr, + Architecture architecture, int minimumLength = 0) { var jmp = GenerateAbsoluteJump(detourPtr, functionPtr, architecture); @@ -66,7 +68,8 @@ namespace BepInEx.IL2CPP Marshal.WriteByte(functionPtr + i, 0x90); } - public static IntPtr CreateTrampolineFromFunction(IntPtr originalFuncPointer, out int trampolineLength, + public static IntPtr CreateTrampolineFromFunction(IntPtr originalFuncPointer, + out int trampolineLength, out int jmpLength) { var instructionBuffer = new byte[32]; @@ -100,9 +103,13 @@ namespace BepInEx.IL2CPP /// Copies at least this many bytes of assembly from . /// Returns the total length of the trampoline, in bytes. /// Returns the length of the jmp at the end of the trampoline, in bytes. - public static void CreateTrampolineFromFunction(byte[] instructionBuffer, IntPtr functionPtr, - IntPtr trampolinePtr, int minimumTrampolineLength, - Architecture arch, out int trampolineLength, out int jmpLength) + public static void CreateTrampolineFromFunction(byte[] instructionBuffer, + IntPtr functionPtr, + IntPtr trampolinePtr, + int minimumTrampolineLength, + Architecture arch, + out int trampolineLength, + out int jmpLength) { // Decode original function up until we go past the needed bytes to write the jump to patchedFunctionPtr diff --git a/BepInEx.IL2CPP/Hook/FastNativeDetour.cs b/BepInEx.IL2CPP/Hook/FastNativeDetour.cs index e7d81fd..d705407 100644 --- a/BepInEx.IL2CPP/Hook/FastNativeDetour.cs +++ b/BepInEx.IL2CPP/Hook/FastNativeDetour.cs @@ -39,10 +39,7 @@ namespace BepInEx.IL2CPP.Hook public bool IsValid { get; protected set; } = true; public bool IsApplied { get; protected set; } - public void Apply() - { - Apply(null); - } + public void Apply() => Apply(null); public void Undo() @@ -60,10 +57,7 @@ namespace BepInEx.IL2CPP.Hook IsApplied = false; } - public void Free() - { - IsValid = false; - } + public void Free() => IsValid = false; public MethodBase GenerateTrampoline(MethodBase signature = null) { @@ -166,7 +160,9 @@ namespace BepInEx.IL2CPP.Hook TrampolineJmpSize = jmpLength; } - public static FastNativeDetour CreateAndApply(IntPtr from, T to, out T original, + public static FastNativeDetour CreateAndApply(IntPtr from, + T to, + out T original, CallingConvention? callingConvention = null) where T : Delegate { var toPtr = callingConvention != null diff --git a/BepInEx.IL2CPP/Hook/IL2CPPDetourMethodPatcher.cs b/BepInEx.IL2CPP/Hook/IL2CPPDetourMethodPatcher.cs index 62af0b1..dd8b889 100644 --- a/BepInEx.IL2CPP/Hook/IL2CPPDetourMethodPatcher.cs +++ b/BepInEx.IL2CPP/Hook/IL2CPPDetourMethodPatcher.cs @@ -69,10 +69,7 @@ namespace BepInEx.IL2CPP.Hook /// Constructs a new instance of method patcher. /// /// - public IL2CPPDetourMethodPatcher(MethodBase original) : base(original) - { - Init(); - } + public IL2CPPDetourMethodPatcher(MethodBase original) : base(original) => Init(); private void Init() { @@ -272,10 +269,7 @@ namespace BepInEx.IL2CPP.Hook return dmd; } - private static void ReportException(Exception ex) - { - DetourLogger.LogError(ex.ToString()); - } + private static void ReportException(Exception ex) => DetourLogger.LogError(ex.ToString()); private static Type ConvertManagedTypeToIL2CPPType(Type managedType) { @@ -322,7 +316,9 @@ namespace BepInEx.IL2CPP.Hook .GetValue(null); } - private static void EmitConvertArgumentToManaged(ILGenerator il, int argIndex, Type managedParamType, + private static void EmitConvertArgumentToManaged(ILGenerator il, + int argIndex, + Type managedParamType, out LocalBuilder variable) { variable = null; @@ -359,7 +355,7 @@ namespace BepInEx.IL2CPP.Hook il.Emit(OpCodes.Br_S, endLabel); il.MarkLabel(notNullLabel); - il.Emit(OpCodes.Newobj, AccessTools.DeclaredConstructor(originalType, new[] {typeof(IntPtr)})); + il.Emit(OpCodes.Newobj, AccessTools.DeclaredConstructor(originalType, new[] { typeof(IntPtr) })); il.MarkLabel(endLabel); } @@ -406,15 +402,15 @@ namespace BepInEx.IL2CPP.Hook TypeAttributes.SequentialLayout, typeof(System.ValueType)); var fb = tb.DefineField("buffer", typeof(IntPtr), FieldAttributes.Public); fb.SetCustomAttribute(new - CustomAttributeBuilder(AccessTools.Constructor(typeof(MarshalAsAttribute), new[] {typeof(UnmanagedType)}), - new object[] {UnmanagedType.ByValArray}, + CustomAttributeBuilder(AccessTools.Constructor(typeof(MarshalAsAttribute), new[] { typeof(UnmanagedType) }), + new object[] { UnmanagedType.ByValArray }, new[] { AccessTools.Field(typeof(MarshalAsAttribute), nameof(MarshalAsAttribute.SizeConst)), AccessTools.Field(typeof(MarshalAsAttribute), nameof(MarshalAsAttribute.ArraySubType)) - }, new object[] {size, UnmanagedType.U1})); + }, new object[] { size, UnmanagedType.U1 })); var type = tb.CreateType(); return FixedStructCache[size] = type; diff --git a/BepInEx.IL2CPP/Logging/IL2CPPLogSource.cs b/BepInEx.IL2CPP/Logging/IL2CPPLogSource.cs index 66e4b02..9983d26 100644 --- a/BepInEx.IL2CPP/Logging/IL2CPPLogSource.cs +++ b/BepInEx.IL2CPP/Logging/IL2CPPLogSource.cs @@ -17,10 +17,8 @@ namespace BepInEx.IL2CPP.Logging public void Dispose() { } - private void IL2CPPLogCallback(string message) - { + private void IL2CPPLogCallback(string message) => LogEvent?.Invoke(this, new LogEventArgs(message.Trim(), LogLevel.Message, this)); - } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void IL2CPPLogCallbackDelegate([In] [MarshalAs(UnmanagedType.LPStr)] string message); diff --git a/BepInEx.IL2CPP/Logging/IL2CPPUnityLogSource.cs b/BepInEx.IL2CPP/Logging/IL2CPPUnityLogSource.cs index 34d051f..9e67ee7 100644 --- a/BepInEx.IL2CPP/Logging/IL2CPPUnityLogSource.cs +++ b/BepInEx.IL2CPP/Logging/IL2CPPUnityLogSource.cs @@ -19,12 +19,12 @@ namespace BepInEx.IL2CPP.Logging { var level = type switch { - LogType.Error => LogLevel.Error, - LogType.Assert => LogLevel.Debug, - LogType.Warning => LogLevel.Warning, - LogType.Log => LogLevel.Message, + LogType.Error => LogLevel.Error, + LogType.Assert => LogLevel.Debug, + LogType.Warning => LogLevel.Warning, + LogType.Log => LogLevel.Message, LogType.Exception => LogLevel.Error, - _ => LogLevel.Message + _ => LogLevel.Message }; LogEvent?.Invoke(this, new LogEventArgs(logLine, level, this)); } diff --git a/BepInEx.IL2CPP/ProxyAssemblyGenerator.cs b/BepInEx.IL2CPP/ProxyAssemblyGenerator.cs index e7bd654..c825d8b 100644 --- a/BepInEx.IL2CPP/ProxyAssemblyGenerator.cs +++ b/BepInEx.IL2CPP/ProxyAssemblyGenerator.cs @@ -99,7 +99,7 @@ namespace BepInEx.IL2CPP })); CreateInstanceAndUnwrap = AccessTools.MethodDelegate>(AccessTools.Method(appDomain, - nameof(CreateInstanceAndUnwrap), new[] {typeof(string), typeof(string)})); + nameof(CreateInstanceAndUnwrap), new[] { typeof(string), typeof(string) })); } public static Func CreateInstanceAndUnwrap { get; } @@ -122,20 +122,11 @@ namespace BepInEx.IL2CPP [Serializable] private class AppDomainListener : MarshalByRefObject { - public void DoPreloaderLog(object data, LogLevel level) - { - Preloader.Log.Log(level, data); - } + public void DoPreloaderLog(object data, LogLevel level) => Preloader.Log.Log(level, data); - public void DoDumperLog(object data, LogLevel level) - { - Il2cppDumperLogger.Log(level, data); - } + public void DoDumperLog(object data, LogLevel level) => Il2cppDumperLogger.Log(level, data); - public void DoUnhollowerLog(object data, LogLevel level) - { - Preloader.UnhollowerLog.Log(level, data); - } + public void DoUnhollowerLog(object data, LogLevel level) => Preloader.UnhollowerLog.Log(level, data); } [Serializable] diff --git a/BepInEx.NetLauncher/NetPreloader.cs b/BepInEx.NetLauncher/NetPreloader.cs index bd54e94..7414703 100644 --- a/BepInEx.NetLauncher/NetPreloader.cs +++ b/BepInEx.NetLauncher/NetPreloader.cs @@ -90,7 +90,7 @@ namespace BepInEx.NetLauncher } else { - Log.LogDebug("Using entrypoint assembly from disk"); + Log.LogDebug("Using entrypoint assembly from disk"); entrypointAssembly = Assembly.LoadFrom(executablePath); } } @@ -104,15 +104,15 @@ namespace BepInEx.NetLauncher AssemblyFix.Execute(entrypointAssembly); - entrypointAssembly.EntryPoint.Invoke(null, new [] { args }); + entrypointAssembly.EntryPoint.Invoke(null, new[] { args }); } #region Config private static readonly ConfigEntry ConfigEntrypointExecutable = ConfigFile.CoreConfig.Bind( - "Preloader.Entrypoint", "Assembly", - null, - "The local filename of the .NET executable to target."); + "Preloader.Entrypoint", "Assembly", + null, + "The local filename of the .NET executable to target."); #endregion } diff --git a/BepInEx.NetLauncher/Program.cs b/BepInEx.NetLauncher/Program.cs index 6449004..85a350a 100644 --- a/BepInEx.NetLauncher/Program.cs +++ b/BepInEx.NetLauncher/Program.cs @@ -49,8 +49,8 @@ namespace BepInEx.NetLauncher return foundAssembly; if (LocalUtility.TryResolveDllAssembly(assemblyName, Paths.BepInExAssemblyDirectory, out foundAssembly) - || LocalUtility.TryResolveDllAssembly(assemblyName, Paths.PatcherPluginPath, out foundAssembly) - || LocalUtility.TryResolveDllAssembly(assemblyName, Paths.PluginPath, out foundAssembly)) + || LocalUtility.TryResolveDllAssembly(assemblyName, Paths.PatcherPluginPath, out foundAssembly) + || LocalUtility.TryResolveDllAssembly(assemblyName, Paths.PluginPath, out foundAssembly)) return foundAssembly; return null; @@ -78,7 +78,8 @@ namespace BepInEx.NetLauncher string filename; #if DEBUG - filename = Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName)); + filename = + Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName)); ResolveDirectories.Add(Path.GetDirectoryName(filename)); // for debugging within VS diff --git a/BepInEx.NetLauncher/Utility.cs b/BepInEx.NetLauncher/Utility.cs index 38059f0..2fd9098 100644 --- a/BepInEx.NetLauncher/Utility.cs +++ b/BepInEx.NetLauncher/Utility.cs @@ -17,8 +17,10 @@ namespace BepInEx.NetLauncher /// Directory to search the assembly from. /// The loaded assembly. /// True, if the assembly was found and loaded. Otherwise, false. - private static bool TryResolveDllAssembly(AssemblyName assemblyName, string directory, - Func loader, out T assembly) where T : class + private static bool TryResolveDllAssembly(AssemblyName assemblyName, + string directory, + Func loader, + out T assembly) where T : class { assembly = null; diff --git a/BepInEx.Patcher/Program.cs b/BepInEx.Patcher/Program.cs index ab685c7..e21bbfc 100644 --- a/BepInEx.Patcher/Program.cs +++ b/BepInEx.Patcher/Program.cs @@ -175,10 +175,10 @@ namespace BepInEx.Patcher var voidType = unity.MainModule.ImportReference(typeof(void)); var cctor = new MethodDefinition(".cctor", MethodAttributes.Static - | MethodAttributes.Private - | MethodAttributes.HideBySig - | MethodAttributes.SpecialName - | MethodAttributes.RTSpecialName, + | MethodAttributes.Private + | MethodAttributes.HideBySig + | MethodAttributes.SpecialName + | MethodAttributes.RTSpecialName, voidType); var ilp = cctor.Body.GetILProcessor(); diff --git a/BepInEx.Preloader.Core/Patching/AssemblyPatcher.cs b/BepInEx.Preloader.Core/Patching/AssemblyPatcher.cs index 4759cc8..92a19a5 100644 --- a/BepInEx.Preloader.Core/Patching/AssemblyPatcher.cs +++ b/BepInEx.Preloader.Core/Patching/AssemblyPatcher.cs @@ -181,7 +181,7 @@ namespace BepInEx.Preloader.Core patcherPlugin.Patcher = (ref AssemblyDefinition pAss) => { //we do the array fuckery here to get the ref result out - object[] args = {pAss}; + object[] args = { pAss }; patcher.Invoke(null, args); @@ -214,10 +214,7 @@ namespace BepInEx.Preloader.Core /// are skipped. /// /// The directory to search. - public void LoadAssemblyDirectory(string directory) - { - LoadAssemblyDirectory(directory, "dll"); - } + public void LoadAssemblyDirectory(string directory) => LoadAssemblyDirectory(directory, "dll"); /// /// Adds all assemblies in a directory to be patched and loaded by this patcher instance. Non-managed assemblies are @@ -401,17 +398,13 @@ namespace BepInEx.Preloader.Core Assembly loadedAssembly; if (ConfigLoadDumpedAssemblies.Value) - { loadedAssembly = Assembly.LoadFrom(Path.Combine(DumpedAssembliesPath, filename)); - } else - { using (var assemblyStream = new MemoryStream()) { assembly.Write(assemblyStream); loadedAssembly = Assembly.Load(assemblyStream.ToArray()); } - } LoadedAssemblies.Add(filename, loadedAssembly); diff --git a/BepInEx.Preloader.Core/Patching/PatcherPlugin.cs b/BepInEx.Preloader.Core/Patching/PatcherPlugin.cs index 49fe57b..15aae06 100644 --- a/BepInEx.Preloader.Core/Patching/PatcherPlugin.cs +++ b/BepInEx.Preloader.Core/Patching/PatcherPlugin.cs @@ -36,15 +36,9 @@ namespace BepInEx.Preloader.Core public string TypeName { get; set; } = string.Empty; /// - public void Save(BinaryWriter bw) - { - bw.Write(TypeName); - } + public void Save(BinaryWriter bw) => bw.Write(TypeName); /// - public void Load(BinaryReader br) - { - TypeName = br.ReadString(); - } + public void Load(BinaryReader br) => TypeName = br.ReadString(); } } diff --git a/BepInEx.Preloader.Core/RuntimeFixes/ConsoleSetOutFix.cs b/BepInEx.Preloader.Core/RuntimeFixes/ConsoleSetOutFix.cs index d9aabb2..f5ae728 100644 --- a/BepInEx.Preloader.Core/RuntimeFixes/ConsoleSetOutFix.cs +++ b/BepInEx.Preloader.Core/RuntimeFixes/ConsoleSetOutFix.cs @@ -13,7 +13,7 @@ namespace BepInEx.Preloader.RuntimeFixes public static void Apply() { - loggedTextWriter = new LoggedTextWriter {Parent = Console.Out}; + loggedTextWriter = new LoggedTextWriter { Parent = Console.Out }; Console.SetOut(loggedTextWriter); Harmony.CreateAndPatchAll(typeof(ConsoleSetOutFix)); } diff --git a/BepInEx.Preloader.Unity/DoorstopEntrypoint.cs b/BepInEx.Preloader.Unity/DoorstopEntrypoint.cs index ea6be0f..255e0ae 100644 --- a/BepInEx.Preloader.Unity/DoorstopEntrypoint.cs +++ b/BepInEx.Preloader.Unity/DoorstopEntrypoint.cs @@ -95,8 +95,8 @@ namespace BepInEx.Preloader.Unity return foundAssembly; if (Utility.TryResolveDllAssembly(assemblyName, Paths.BepInExAssemblyDirectory, out foundAssembly) - || Utility.TryResolveDllAssembly(assemblyName, Paths.PatcherPluginPath, out foundAssembly) - || Utility.TryResolveDllAssembly(assemblyName, Paths.PluginPath, out foundAssembly)) + || Utility.TryResolveDllAssembly(assemblyName, Paths.PatcherPluginPath, out foundAssembly) + || Utility.TryResolveDllAssembly(assemblyName, Paths.PluginPath, out foundAssembly)) return foundAssembly; return null; diff --git a/BepInEx.Preloader.Unity/RuntimeFixes/XTermFix.cs b/BepInEx.Preloader.Unity/RuntimeFixes/XTermFix.cs index c8f68b9..93ad069 100644 --- a/BepInEx.Preloader.Unity/RuntimeFixes/XTermFix.cs +++ b/BepInEx.Preloader.Unity/RuntimeFixes/XTermFix.cs @@ -38,13 +38,13 @@ namespace BepInEx.Preloader.RuntimeFixes harmony.Patch(AccessTools.Method("System.TermInfoReader:ReadHeader"), new HarmonyMethod(typeof(XTermFix), nameof(ReadHeaderPrefix))); - harmony.Patch(AccessTools.Method("System.TermInfoReader:Get", new[] {AccessTools.TypeByName("System.TermInfoNumbers")}), + harmony.Patch(AccessTools.Method("System.TermInfoReader:Get", new[] { AccessTools.TypeByName("System.TermInfoNumbers") }), transpiler: new HarmonyMethod(typeof(XTermFix), nameof(GetTermInfoNumbersTranspiler))); - harmony.Patch(AccessTools.Method("System.TermInfoReader:Get", new[] {AccessTools.TypeByName("System.TermInfoStrings")}), + harmony.Patch(AccessTools.Method("System.TermInfoReader:Get", new[] { AccessTools.TypeByName("System.TermInfoStrings") }), transpiler: new HarmonyMethod(typeof(XTermFix), nameof(GetTermInfoStringsTranspiler))); - harmony.Patch(AccessTools.Method("System.TermInfoReader:GetStringBytes", new[] {AccessTools.TypeByName("System.TermInfoStrings")}), + harmony.Patch(AccessTools.Method("System.TermInfoReader:GetStringBytes", new[] { AccessTools.TypeByName("System.TermInfoStrings") }), transpiler: new HarmonyMethod(typeof(XTermFix), nameof(GetTermInfoStringsTranspiler))); DetourHelper.Native = null; @@ -83,8 +83,11 @@ namespace BepInEx.Preloader.RuntimeFixes throw new Exception($"Unknown xterm header format: {magic}"); } - public static bool ReadHeaderPrefix(byte[] buffer, ref int position, ref short ___boolSize, - ref short ___numSize, ref short ___strOffsets) + public static bool ReadHeaderPrefix(byte[] buffer, + ref int position, + ref short ___boolSize, + ref short ___numSize, + ref short ___strOffsets) { var magic = GetInt16(buffer, position); position += 2; diff --git a/BepInEx.Preloader.Unity/UnityPreloader.cs b/BepInEx.Preloader.Unity/UnityPreloader.cs index cf64f4c..4a0e9a7 100644 --- a/BepInEx.Preloader.Unity/UnityPreloader.cs +++ b/BepInEx.Preloader.Unity/UnityPreloader.cs @@ -82,7 +82,7 @@ namespace BepInEx.Preloader.Unity { assemblyPatcher.PatcherPlugins.Add(new PatcherPlugin { - TargetDLLs = () => new[] {ConfigEntrypointAssembly.Value}, + TargetDLLs = () => new[] { ConfigEntrypointAssembly.Value }, Patcher = PatchEntrypoint, TypeName = "BepInEx.Chainloader" }); @@ -192,7 +192,7 @@ namespace BepInEx.Preloader.Unity cctor = new MethodDefinition(".cctor", MethodAttributes.Static | MethodAttributes.Private | MethodAttributes.HideBySig - | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, + | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, assembly.MainModule.ImportReference(typeof(void))); entryType.Methods.Add(cctor); diff --git a/BepInEx.Unity/Configuration/KeyboardShortcut.cs b/BepInEx.Unity/Configuration/KeyboardShortcut.cs index d1b721a..c3e368b 100644 --- a/BepInEx.Unity/Configuration/KeyboardShortcut.cs +++ b/BepInEx.Unity/Configuration/KeyboardShortcut.cs @@ -18,8 +18,7 @@ namespace BepInEx.Configuration /// public struct KeyboardShortcut { - static KeyboardShortcut() - { + static KeyboardShortcut() => TomlTypeConverter.AddConverter( typeof(KeyboardShortcut), new TypeConverter @@ -27,7 +26,6 @@ namespace BepInEx.Configuration ConvertToString = (o, type) => ((KeyboardShortcut) o).Serialize(), ConvertToObject = (s, type) => Deserialize(s) }); - } /// /// Shortcut that never triggers. @@ -53,7 +51,7 @@ namespace BepInEx.Configuration /// /// Main key to press /// Keys that should be held down before main key is registered - public KeyboardShortcut(KeyCode mainKey, params KeyCode[] modifiers) : this(new[] {mainKey}.Concat(modifiers) + public KeyboardShortcut(KeyCode mainKey, params KeyCode[] modifiers) : this(new[] { mainKey }.Concat(modifiers) .ToArray()) { if (mainKey == KeyCode.None && modifiers.Any()) @@ -66,10 +64,10 @@ namespace BepInEx.Configuration private static KeyCode[] SanitizeKeys(params KeyCode[] keys) { if (keys.Length == 0 || keys[0] == KeyCode.None) - return new[] {KeyCode.None}; + return new[] { KeyCode.None }; - return new[] {keys[0]}.Concat(keys.Skip(1).Distinct().Where(x => x != keys[0]).OrderBy(x => (int) x)) - .ToArray(); + return new[] { keys[0] }.Concat(keys.Skip(1).Distinct().Where(x => x != keys[0]).OrderBy(x => (int) x)) + .ToArray(); } /// @@ -90,7 +88,7 @@ namespace BepInEx.Configuration { try { - var parts = str.Split(new[] {' ', '+', ',', ';', '|'}, StringSplitOptions.RemoveEmptyEntries) + var parts = str.Split(new[] { ' ', '+', ',', ';', '|' }, StringSplitOptions.RemoveEmptyEntries) .Select(x => (KeyCode) Enum.Parse(typeof(KeyCode), x)).ToArray(); return new KeyboardShortcut(parts); } diff --git a/BepInEx.Unity/Logging/UnityLogListener.cs b/BepInEx.Unity/Logging/UnityLogListener.cs index c01c760..cf801eb 100644 --- a/BepInEx.Unity/Logging/UnityLogListener.cs +++ b/BepInEx.Unity/Logging/UnityLogListener.cs @@ -29,7 +29,7 @@ namespace BepInEx.Unity.Logging { try { - methodInfo.Invoke(null, new object[] {""}); + methodInfo.Invoke(null, new object[] { "" }); } catch { diff --git a/BepInEx.Unity/Logging/UnityLogSource.cs b/BepInEx.Unity/Logging/UnityLogSource.cs index 568b7d7..c571dce 100644 --- a/BepInEx.Unity/Logging/UnityLogSource.cs +++ b/BepInEx.Unity/Logging/UnityLogSource.cs @@ -58,7 +58,7 @@ namespace BepInEx.Unity.Logging { var registerLogCallback = typeof(Application).GetMethod("RegisterLogCallback", BindingFlags.Public | BindingFlags.Static); - registerLogCallback.Invoke(null, new object[] {callback}); + registerLogCallback.Invoke(null, new object[] { callback }); //UnsubscribeAction = () => registerLogCallback.Invoke(null, new object[] { null }); } } diff --git a/BepInEx.Unity/ThreadingHelper.cs b/BepInEx.Unity/ThreadingHelper.cs index b6f7ffd..08fe7e5 100644 --- a/BepInEx.Unity/ThreadingHelper.cs +++ b/BepInEx.Unity/ThreadingHelper.cs @@ -192,7 +192,8 @@ namespace BepInEx public static class ThreadingExtensions { /// - public static IEnumerable RunParallel(this IEnumerable data, Func work, + public static IEnumerable RunParallel(this IEnumerable data, + Func work, int workerCount = -1) { foreach (var result in RunParallel(data.ToList(), work)) @@ -213,7 +214,8 @@ namespace BepInEx /// aborted. /// /// Need at least 1 workerCount. - public static IEnumerable RunParallel(this IList data, Func work, + public static IEnumerable RunParallel(this IList data, + Func work, int workerCount = -1) { if (workerCount < 0) diff --git a/BepInExTests/AssemblyInit.cs b/BepInExTests/AssemblyInit.cs index 365864f..74c9220 100644 --- a/BepInExTests/AssemblyInit.cs +++ b/BepInExTests/AssemblyInit.cs @@ -21,9 +21,6 @@ namespace BepInEx.Tests } [AssemblyCleanup] - public static void CleanupAss() - { - Directory.Delete(_testPath, true); - } + public static void CleanupAss() => Directory.Delete(_testPath, true); } } diff --git a/BepInExTests/Configuration/ConfigFileTests.cs b/BepInExTests/Configuration/ConfigFileTests.cs index 5de5d38..e448c4a 100644 --- a/BepInExTests/Configuration/ConfigFileTests.cs +++ b/BepInExTests/Configuration/ConfigFileTests.cs @@ -14,10 +14,7 @@ namespace BepInEx.Configuration.Tests private static ConcurrentBag _toRemove; [ClassInitialize] - public static void Init(TestContext context) - { - _toRemove = new ConcurrentBag(); - } + public static void Init(TestContext context) => _toRemove = new ConcurrentBag(); [ClassCleanup] public static void Cleanup() @@ -36,10 +33,7 @@ namespace BepInEx.Configuration.Tests } [TestMethod] - public void SaveTest() - { - MakeConfig().Save(); - } + public void SaveTest() => MakeConfig().Save(); [TestMethod] public void SaveTestValueChange() @@ -303,7 +297,7 @@ namespace BepInEx.Configuration.Tests var w = c.Bind("Cat", "Key", "", new ConfigDescription("Test")); var unescaped = @"D:\test\p ath"; - foreach (var testVal in new[] {unescaped, @"D:\\test\\p ath"}) + foreach (var testVal in new[] { unescaped, @"D:\\test\\p ath" }) { File.WriteAllText(c.ConfigFilePath, $"[Cat]\n# Test\nKey={testVal}\n"); c.Reload();