From 4bb48c502ead1b50a1cfdae8e00d610360ca1049 Mon Sep 17 00:00:00 2001 From: ghorsington Date: Tue, 21 Dec 2021 18:55:05 +0200 Subject: [PATCH] Reformat project; apply code style --- BepInEx.Core/Bootstrap/BaseChainloader.cs | 15 ++++--- BepInEx.Core/Bootstrap/TypeLoader.cs | 9 ++-- BepInEx.Core/Configuration/ConfigFile.cs | 1 - .../Configuration/TomlTypeConverter.cs | 3 +- BepInEx.Core/Console/Windows/Kon.cs | 2 +- .../BepInExLogInterpolatedStringHandler.cs | 44 +++++++++++++------ BepInEx.Core/Logging/DiskLogListener.cs | 2 - .../InterpolatedStringHandlerAttribute.cs | 1 + BepInEx.Core/Logging/Logger.cs | 34 +++++++------- BepInEx.Core/Logging/ManualLogSource.cs | 5 ++- BepInEx.Core/Paths.cs | 2 +- BepInEx.Core/Utility.cs | 10 ++--- BepInEx.IL2CPP/BasePlugin.cs | 5 +-- BepInEx.IL2CPP/Hook/FastNativeDetour.cs | 3 +- BepInEx.IL2CPP/IL2CPPChainloader.cs | 13 +++--- .../Logging/IL2CPPUnityLogSource.cs | 4 +- BepInEx.IL2CPP/Preloader.cs | 12 ++--- BepInEx.IL2CPP/ProxyAssemblyGenerator.cs | 8 ++-- .../Collections/ManagedIl2CppEnumerable.cs | 2 +- BepInEx.NetLauncher/NetPreloader.cs | 24 +++++----- BepInEx.Preloader.Core/EnvVars.cs | 2 +- .../Logging/PreloaderConsoleListener.cs | 5 +-- .../Patching/AssemblyPatcher.cs | 36 ++++++++------- BepInEx.Preloader.Core/Patching/Attributes.cs | 19 ++++---- .../Patching/BasePatcher.cs | 41 ++++++++--------- .../Patching/PatcherContext.cs | 15 ++++--- BepInEx.Preloader.Unity/EntrypointPatcher.cs | 39 ++++++++-------- BepInEx.Preloader.Unity/UnityPreloader.cs | 17 ++++--- .../Configuration/KeyboardShortcut.cs | 2 +- BepInEx.Unity/Logging/UnityLogListener.cs | 10 ++--- 30 files changed, 213 insertions(+), 172 deletions(-) diff --git a/BepInEx.Core/Bootstrap/BaseChainloader.cs b/BepInEx.Core/Bootstrap/BaseChainloader.cs index bc661ca..7cffe4f 100644 --- a/BepInEx.Core/Bootstrap/BaseChainloader.cs +++ b/BepInEx.Core/Bootstrap/BaseChainloader.cs @@ -52,7 +52,8 @@ public abstract class BaseChainloader if (string.IsNullOrEmpty(metadata.GUID) || !allowedGuidRegex.IsMatch(metadata.GUID)) { - Logger.Log(LogLevel.Warning, $"Skipping type [{type.FullName}] because its GUID [{metadata.GUID}] is of an illegal format."); + Logger.Log(LogLevel.Warning, + $"Skipping type [{type.FullName}] because its GUID [{metadata.GUID}] is of an illegal format."); return null; } @@ -196,7 +197,8 @@ public abstract class BaseChainloader { if (loadedVersion != null) { - Logger.Log(LogLevel.Warning, $"Skipping [{pluginInfo}] because a newer version exists ({loadedVersion})"); + Logger.Log(LogLevel.Warning, + $"Skipping [{pluginInfo}] because a newer version exists ({loadedVersion})"); continue; } @@ -210,7 +212,8 @@ public abstract class BaseChainloader if (invalidProcessName) { - Logger.Log(LogLevel.Warning, $"Skipping [{pluginInfo}] because of process filters ({string.Join(", ", pluginInfo.Processes.Select(p => p.ProcessName).ToArray())})"); + Logger.Log(LogLevel.Warning, + $"Skipping [{pluginInfo}] because of process filters ({string.Join(", ", pluginInfo.Processes.Select(p => p.ProcessName).ToArray())})"); continue; } @@ -340,7 +343,8 @@ public abstract class BaseChainloader invalidPlugins.Add(plugin.Metadata.GUID); Plugins.Remove(plugin.Metadata.GUID); - Logger.Log(LogLevel.Error, $"Error loading [{plugin}]: {(ex is ReflectionTypeLoadException re ? TypeLoader.TypeLoadExceptionToString(re) : ex.ToString())}"); + Logger.Log(LogLevel.Error, + $"Error loading [{plugin}]: {(ex is ReflectionTypeLoadException re ? TypeLoader.TypeLoadExceptionToString(re) : ex.ToString())}"); } } } @@ -366,7 +370,8 @@ public abstract class BaseChainloader } catch (Exception e) { - Logger.Log(LogLevel.Warning, $"Couldn't run Module constructor for {assembly.FullName}::{plugin.TypeName}: {e}"); + Logger.Log(LogLevel.Warning, + $"Couldn't run Module constructor for {assembly.FullName}::{plugin.TypeName}: {e}"); } } diff --git a/BepInEx.Core/Bootstrap/TypeLoader.cs b/BepInEx.Core/Bootstrap/TypeLoader.cs index 1b274aa..69a7775 100644 --- a/BepInEx.Core/Bootstrap/TypeLoader.cs +++ b/BepInEx.Core/Bootstrap/TypeLoader.cs @@ -169,7 +169,8 @@ public static class TypeLoader } catch (BadImageFormatException e) { - Logger.Log(LogLevel.Debug, $"Skipping loading {dll} because it's not a valid .NET assembly. Full error: {e.Message}"); + Logger.Log(LogLevel.Debug, + $"Skipping loading {dll} because it's not a valid .NET assembly. Full error: {e.Message}"); } catch (Exception e) { @@ -228,7 +229,8 @@ public static class TypeLoader } catch (Exception e) { - Logger.Log(LogLevel.Warning, $"Failed to load cache \"{cacheName}\"; skipping loading cache. Reason: {e.Message}."); + Logger.Log(LogLevel.Warning, + $"Failed to load cache \"{cacheName}\"; skipping loading cache. Reason: {e.Message}."); } return result; @@ -271,7 +273,8 @@ public static class TypeLoader } catch (Exception e) { - Logger.Log(LogLevel.Warning, $"Failed to save cache \"{cacheName}\"; skipping saving cache. Reason: {e.Message}."); + Logger.Log(LogLevel.Warning, + $"Failed to save cache \"{cacheName}\"; skipping saving cache. Reason: {e.Message}."); } } diff --git a/BepInEx.Core/Configuration/ConfigFile.cs b/BepInEx.Core/Configuration/ConfigFile.cs index 714fdbf..5e52e1f 100644 --- a/BepInEx.Core/Configuration/ConfigFile.cs +++ b/BepInEx.Core/Configuration/ConfigFile.cs @@ -4,7 +4,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; -using System.Text; using BepInEx.Logging; namespace BepInEx.Configuration; diff --git a/BepInEx.Core/Configuration/TomlTypeConverter.cs b/BepInEx.Core/Configuration/TomlTypeConverter.cs index 655b5d1..41595af 100644 --- a/BepInEx.Core/Configuration/TomlTypeConverter.cs +++ b/BepInEx.Core/Configuration/TomlTypeConverter.cs @@ -162,7 +162,8 @@ public static class TomlTypeConverter if (converter == null) throw new ArgumentNullException(nameof(converter)); if (CanConvert(type)) { - Logger.Log(LogLevel.Warning, "Tried to add a TomlConverter when one already exists for type " + type.FullName); + Logger.Log(LogLevel.Warning, + "Tried to add a TomlConverter when one already exists for type " + type.FullName); return false; } diff --git a/BepInEx.Core/Console/Windows/Kon.cs b/BepInEx.Core/Console/Windows/Kon.cs index f2ea9a1..d6784f8 100644 --- a/BepInEx.Core/Console/Windows/Kon.cs +++ b/BepInEx.Core/Console/Windows/Kon.cs @@ -102,7 +102,7 @@ namespace BepInEx.ConsoleUtil if (!flag) return; var num = bufferInfo.wAttributes; - num &= isBackground ? (short) -241 : (short) -16; + num &= (short) (isBackground ? -241 : -16); num = (short) ((ushort) num | (ushort) color); SetConsoleTextAttribute(conOut, num); } diff --git a/BepInEx.Core/Logging/BepInExLogInterpolatedStringHandler.cs b/BepInEx.Core/Logging/BepInExLogInterpolatedStringHandler.cs index 7f37c3d..16460b6 100644 --- a/BepInEx.Core/Logging/BepInExLogInterpolatedStringHandler.cs +++ b/BepInEx.Core/Logging/BepInExLogInterpolatedStringHandler.cs @@ -6,42 +6,47 @@ using BepInEx.Logging; namespace BepInEx.Core.Logging; /// -/// Interpolated string handler for BepInEx . This allows to conditionally skip logging certain messages and speed up logging in certain places. +/// Interpolated string handler for BepInEx . This allows to conditionally skip logging certain +/// messages and speed up logging in certain places. /// /// -/// The class isn't meant to be constructed manually. -/// Instead, use with string interpolation. +/// The class isn't meant to be constructed manually. +/// Instead, use with +/// string interpolation. /// [InterpolatedStringHandler] public class BepInExLogInterpolatedStringHandler { - // We can't use an array pool to support net35 builds, so default to StringBuilder - private readonly StringBuilder sb; - // See https://source.dot.net/#System.Private.CoreLib/DefaultInterpolatedStringHandler.cs,29 private const int GUESSED_LENGTH_PER_HOLE = 11; + // We can't use an array pool to support net35 builds, so default to StringBuilder + private readonly StringBuilder sb; + /// - /// Constructs a log handler. + /// Constructs a log handler. /// /// Length of the literal string. /// Number for formatted items. /// Log level the message belongs to. /// Whether this string should be logged. - public BepInExLogInterpolatedStringHandler(int literalLength, int formattedCount, LogLevel logLevel, out bool isEnabled) + public BepInExLogInterpolatedStringHandler(int literalLength, + int formattedCount, + LogLevel logLevel, + out bool isEnabled) { Enabled = (logLevel & Logger.ListenedLogLevels) == LogLevel.None; isEnabled = Enabled; - sb = Enabled ? new StringBuilder(literalLength + (formattedCount * GUESSED_LENGTH_PER_HOLE)) : null; + sb = Enabled ? new StringBuilder(literalLength + formattedCount * GUESSED_LENGTH_PER_HOLE) : null; } /// - /// Whether the interpolation is enabled and string will be logged. + /// Whether the interpolation is enabled and string will be logged. /// public bool Enabled { get; } /// - /// Appends a literal string to the interpolation. + /// Appends a literal string to the interpolation. /// /// String to append. public void AppendLiteral(string s) @@ -52,7 +57,7 @@ public class BepInExLogInterpolatedStringHandler } /// - /// Appends a value to the interpolation. + /// Appends a value to the interpolation. /// /// Value to append. /// Type of the value to append. @@ -65,7 +70,7 @@ public class BepInExLogInterpolatedStringHandler } /// - /// Append a formattable item. + /// Append a formattable item. /// /// Item to append. /// Format to append with. @@ -78,6 +83,19 @@ public class BepInExLogInterpolatedStringHandler sb.Append(t?.ToString(format, null)); } + /// + /// Append an IntPtr. + /// + /// Item to append. + /// Format to append with. + public void AppendFormatted(IntPtr t, string format) + { + if (!Enabled) + return; + + sb.Append(t.ToString(format)); + } + /// public override string ToString() => sb?.ToString() ?? string.Empty; } diff --git a/BepInEx.Core/Logging/DiskLogListener.cs b/BepInEx.Core/Logging/DiskLogListener.cs index fd7bced..5e2bb46 100644 --- a/BepInEx.Core/Logging/DiskLogListener.cs +++ b/BepInEx.Core/Logging/DiskLogListener.cs @@ -1,9 +1,7 @@ using System; using System.Collections.Generic; using System.IO; -using System.Text; using System.Threading; -using Mono.Cecil; namespace BepInEx.Logging; diff --git a/BepInEx.Core/Logging/InterpolatedStringHandlerAttribute.cs b/BepInEx.Core/Logging/InterpolatedStringHandlerAttribute.cs index 05d9bfe..9def31e 100644 --- a/BepInEx.Core/Logging/InterpolatedStringHandlerAttribute.cs +++ b/BepInEx.Core/Logging/InterpolatedStringHandlerAttribute.cs @@ -1,4 +1,5 @@ // ReSharper disable once CheckNamespace + namespace System.Runtime.CompilerServices; [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false)] diff --git a/BepInEx.Core/Logging/Logger.cs b/BepInEx.Core/Logging/Logger.cs index d51e341..3fb0ff8 100644 --- a/BepInEx.Core/Logging/Logger.cs +++ b/BepInEx.Core/Logging/Logger.cs @@ -14,11 +14,19 @@ public static class Logger private static readonly LogListenerCollection listeners; + static Logger() + { + Sources = new LogSourceCollection(); + listeners = new LogListenerCollection(); + + InternalLogSource = CreateLogSource("BepInEx"); + } + /// - /// Log levels that are currently listened to by at least one listener. + /// Log levels that are currently listened to by at least one listener. /// public static LogLevel ListenedLogLevels => listeners.activeLogLevels; - + /// /// Collection of all log listeners that receive log events. /// @@ -29,14 +37,6 @@ public static class Logger /// public static ICollection Sources { get; } - static Logger() - { - Sources = new LogSourceCollection(); - listeners = new LogListenerCollection(); - - InternalLogSource = CreateLogSource("BepInEx"); - } - internal static void InternalLogEvent(object sender, LogEventArgs eventArgs) { // ReSharper disable once ForeachCanBePartlyConvertedToQueryUsingAnotherGetEnumerator Prevent extra allocations @@ -53,14 +53,14 @@ public static class Logger internal static void Log(LogLevel level, object data) => InternalLogSource.Log(level, data); /// - /// Logs an entry to the internal logger instance if any log listener wants the message. + /// Logs an entry to the internal logger instance if any log listener wants the message. /// /// The level of the entry. /// Log handler to resolve log from. - internal static void Log(LogLevel level, [InterpolatedStringHandlerArgument("level")] BepInExLogInterpolatedStringHandler logHandler) - { + internal static void Log(LogLevel level, + [InterpolatedStringHandlerArgument("level")] + BepInExLogInterpolatedStringHandler logHandler) => InternalLogSource.Log(level, logHandler); - } /// /// Creates a new log source with a name and attaches it to . @@ -77,14 +77,14 @@ public static class Logger private class LogListenerCollection : List, ICollection { public LogLevel activeLogLevels = LogLevel.None; - + void ICollection.Add(ILogListener item) { if (item == null) throw new ArgumentNullException(nameof(item)); activeLogLevels |= item.LogLevelFilter; - + base.Add(item); } @@ -103,7 +103,7 @@ public static class Logger foreach (var i in this) activeLogLevels |= i.LogLevelFilter; - + return true; } } diff --git a/BepInEx.Core/Logging/ManualLogSource.cs b/BepInEx.Core/Logging/ManualLogSource.cs index 7f0ef7c..880204c 100644 --- a/BepInEx.Core/Logging/ManualLogSource.cs +++ b/BepInEx.Core/Logging/ManualLogSource.cs @@ -34,12 +34,13 @@ public class ManualLogSource : ILogSource /// Data to log. public void Log(LogLevel level, object data) => LogEvent?.Invoke(this, new LogEventArgs(data, level, this)); - public void Log(LogLevel level, [InterpolatedStringHandlerArgument("level")] BepInExLogInterpolatedStringHandler logHandler) + public void Log(LogLevel level, + [InterpolatedStringHandlerArgument("level")] BepInExLogInterpolatedStringHandler logHandler) { if (logHandler.Enabled) LogEvent?.Invoke(this, new LogEventArgs(logHandler.ToString(), level, this)); } - + /// /// Logs a message with level. /// diff --git a/BepInEx.Core/Paths.cs b/BepInEx.Core/Paths.cs index 2634448..4e8d186 100644 --- a/BepInEx.Core/Paths.cs +++ b/BepInEx.Core/Paths.cs @@ -80,7 +80,7 @@ public static class Paths public static string ProcessName { get; private set; } /// - /// List of directories from where Mono will search assemblies before assembly resolving is invoked. + /// List of directories from where Mono will search assemblies before assembly resolving is invoked. /// public static string[] DllSearchPaths { get; private set; } diff --git a/BepInEx.Core/Utility.cs b/BepInEx.Core/Utility.cs index be4eb21..24569b4 100644 --- a/BepInEx.Core/Utility.cs +++ b/BepInEx.Core/Utility.cs @@ -25,7 +25,7 @@ public static class Utility public static bool CLRSupportsDynamicAssemblies => CheckSRE(); /// - /// An encoding for UTF-8 which does not emit a byte order mark (BOM). + /// An encoding for UTF-8 which does not emit a byte order mark (BOM). /// public static Encoding UTF8NoBom { get; } = new UTF8Encoding(false); @@ -302,7 +302,7 @@ public static class Utility } /// - /// Compute a MD5 hash of the given stream. + /// Compute a MD5 hash of the given stream. /// /// Stream to hash /// MD5 hash as a hex string @@ -321,7 +321,7 @@ public static class Utility } /// - /// Convert the given array to a hex string. + /// Convert the given array to a hex string. /// /// Bytes to convert. /// Bytes reinterpreted as a hex number. @@ -374,8 +374,8 @@ public static class Utility } /// - /// Gets unique files in all given directories. If the file with the same name exists in multiple directories, - /// only the first occurrence is returned. + /// Gets unique files in all given directories. If the file with the same name exists in multiple directories, + /// only the first occurrence is returned. /// /// Directories to search from. /// File pattern to search. diff --git a/BepInEx.IL2CPP/BasePlugin.cs b/BepInEx.IL2CPP/BasePlugin.cs index d3cde6a..b9de98f 100644 --- a/BepInEx.IL2CPP/BasePlugin.cs +++ b/BepInEx.IL2CPP/BasePlugin.cs @@ -24,9 +24,8 @@ public abstract class BasePlugin public virtual bool Unload() => false; /// - /// Add a Component (e.g. MonoBehaviour) into Unity scene. - /// - /// Automatically registers the type with Il2Cpp Type system if it isn't already. + /// Add a Component (e.g. MonoBehaviour) into Unity scene. + /// Automatically registers the type with Il2Cpp Type system if it isn't already. /// /// Type of the component to add. public T AddComponent() where T : Il2CppObjectBase => IL2CPPChainloader.AddUnityComponent(); diff --git a/BepInEx.IL2CPP/Hook/FastNativeDetour.cs b/BepInEx.IL2CPP/Hook/FastNativeDetour.cs index a6cc954..d06c8be 100644 --- a/BepInEx.IL2CPP/Hook/FastNativeDetour.cs +++ b/BepInEx.IL2CPP/Hook/FastNativeDetour.cs @@ -143,7 +143,8 @@ public class FastNativeDetour : IDetour var trampolineAlloc = PageAllocator.Instance.Allocate(OriginalFunctionPtr); - logger.Log(LogLevel.Debug, $"Original: {OriginalFunctionPtr.ToInt64():X}, Trampoline: {(long) trampolineAlloc:X}, diff: {Math.Abs(OriginalFunctionPtr.ToInt64() - trampolineAlloc):X}; is within +-1GB range: {PageAllocator.IsInRelJmpRange(OriginalFunctionPtr, trampolineAlloc)}"); + logger.Log(LogLevel.Debug, + $"Original: {OriginalFunctionPtr.ToInt64():X}, Trampoline: {trampolineAlloc:X}, diff: {Math.Abs(OriginalFunctionPtr.ToInt64() - trampolineAlloc):X}; is within +-1GB range: {PageAllocator.IsInRelJmpRange(OriginalFunctionPtr, trampolineAlloc)}"); DetourHelper.Native.MakeWritable(trampolineAlloc, PageAllocator.PAGE_SIZE); diff --git a/BepInEx.IL2CPP/IL2CPPChainloader.cs b/BepInEx.IL2CPP/IL2CPPChainloader.cs index 68cadf5..a4ea66b 100644 --- a/BepInEx.IL2CPP/IL2CPPChainloader.cs +++ b/BepInEx.IL2CPP/IL2CPPChainloader.cs @@ -42,17 +42,15 @@ public class IL2CPPChainloader : BaseChainloader public static IL2CPPChainloader Instance { get; set; } /// - /// Register and add a Unity Component (for example MonoBehaviour) into BepInEx global manager. - /// - /// Automatically registers the type with Il2Cpp type system if it isn't initialised already. + /// Register and add a Unity Component (for example MonoBehaviour) into BepInEx global manager. + /// Automatically registers the type with Il2Cpp type system if it isn't initialised already. /// /// Type of the component to add. public static T AddUnityComponent() where T : Il2CppObjectBase => AddUnityComponent(typeof(T)).Cast(); /// - /// Register and add a Unity Component (for example MonoBehaviour) into BepInEx global manager. - /// - /// Automatically registers the type with Il2Cpp type system if it isn't initialised already. + /// Register and add a Unity Component (for example MonoBehaviour) into BepInEx global manager. + /// Automatically registers the type with Il2Cpp type system if it isn't initialised already. /// /// Type of the component to add public static Il2CppObjectBase AddUnityComponent(Type t) => Il2CppUtils.AddComponent(t); @@ -73,7 +71,8 @@ public class IL2CPPChainloader : BaseChainloader if (gameAssemblyModule == null) { - Logger.Log(LogLevel.Fatal, "Could not locate Il2Cpp game assembly (GameAssembly.dll) or (UserAssembly.dll). The game might be obfuscated or use a yet unsupported build of Unity."); + Logger.Log(LogLevel.Fatal, + "Could not locate Il2Cpp game assembly (GameAssembly.dll) or (UserAssembly.dll). The game might be obfuscated or use a yet unsupported build of Unity."); return; } diff --git a/BepInEx.IL2CPP/Logging/IL2CPPUnityLogSource.cs b/BepInEx.IL2CPP/Logging/IL2CPPUnityLogSource.cs index 7e4b512..b46f6df 100644 --- a/BepInEx.IL2CPP/Logging/IL2CPPUnityLogSource.cs +++ b/BepInEx.IL2CPP/Logging/IL2CPPUnityLogSource.cs @@ -6,8 +6,6 @@ namespace BepInEx.IL2CPP.Logging; public class IL2CPPUnityLogSource : ILogSource { - private delegate IntPtr SetLogCallbackDefinedDelegate(bool defined); - public IL2CPPUnityLogSource() { Application.s_LogCallbackHandler = new Action(UnityLogCallback); @@ -36,4 +34,6 @@ public class IL2CPPUnityLogSource : ILogSource }; LogEvent?.Invoke(this, new LogEventArgs(logLine, level, this)); } + + private delegate IntPtr SetLogCallbackDefinedDelegate(bool defined); } diff --git a/BepInEx.IL2CPP/Preloader.cs b/BepInEx.IL2CPP/Preloader.cs index d7c1aa7..f705896 100644 --- a/BepInEx.IL2CPP/Preloader.cs +++ b/BepInEx.IL2CPP/Preloader.cs @@ -51,9 +51,9 @@ public static class Preloader ChainloaderLogHelper.PrintLogInfo(Log); - Log.Log(LogLevel.Debug,$"Game executable path: {Paths.ExecutablePath}"); - Log.Log(LogLevel.Debug,$"Unhollowed assembly directory: {IL2CPPUnhollowedPath}"); - Log.Log(LogLevel.Debug,$"BepInEx root path: {Paths.BepInExRootPath}"); + Log.Log(LogLevel.Debug, $"Game executable path: {Paths.ExecutablePath}"); + Log.Log(LogLevel.Debug, $"Unhollowed assembly directory: {IL2CPPUnhollowedPath}"); + Log.Log(LogLevel.Debug, $"BepInEx root path: {Paths.BepInExRootPath}"); UnhollowerLog = Logger.CreateLogSource("Unhollower"); LogSupport.InfoHandler += UnhollowerLog.LogInfo; @@ -100,11 +100,11 @@ public static class Preloader private static void InitializeUnityVersion() { if (TryInitializeUnityVersion(ConfigUnityVersion.Value)) - Log.LogWarning($"Unity version obtained from the config."); + Log.LogWarning("Unity version obtained from the config."); else if (TryInitializeUnityVersion(Process.GetCurrentProcess().MainModule.FileVersionInfo.FileVersion)) - Log.LogDebug($"Unity version obtained from main application module."); + Log.LogDebug("Unity version obtained from main application module."); else - Log.LogError($"Running under default Unity version. UnityVersionHandler is not initialized."); + Log.LogError("Running under default Unity version. UnityVersionHandler is not initialized."); } private static bool TryInitializeUnityVersion(string version) diff --git a/BepInEx.IL2CPP/ProxyAssemblyGenerator.cs b/BepInEx.IL2CPP/ProxyAssemblyGenerator.cs index c869145..4f498fb 100644 --- a/BepInEx.IL2CPP/ProxyAssemblyGenerator.cs +++ b/BepInEx.IL2CPP/ProxyAssemblyGenerator.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.IO; using System.IO.Compression; using System.Net.Http; @@ -53,7 +54,7 @@ internal static class ProxyAssemblyGenerator false, "If enabled, BepInEx will save dummy assemblies generated by an il2cpp dumper into BepInEx/dummy."); - private static ManualLogSource Il2cppDumperLogger = null; + private static ManualLogSource Il2cppDumperLogger; public static string GameAssemblyPath => Path.Combine(Paths.GameRootPath, "GameAssembly.dll"); @@ -109,7 +110,8 @@ internal static class ProxyAssemblyGenerator { var hash = ComputeHash(); Preloader.Log - .Log(LogLevel.Warning, $"Unhollowed assemblies are possibly out of date. To disable this message, create file {HashPath} with the following contents: {hash}"); + .Log(LogLevel.Warning, + $"Unhollowed assemblies are possibly out of date. To disable this message, create file {HashPath} with the following contents: {hash}"); return false; } @@ -254,7 +256,7 @@ internal static class ProxyAssemblyGenerator List sourceAssemblies; - var stopwatch = new System.Diagnostics.Stopwatch(); + var stopwatch = new Stopwatch(); stopwatch.Start(); if (dumperType == IL2CPPDumperType.Il2CppDumper) diff --git a/BepInEx.IL2CPP/Utils/Collections/ManagedIl2CppEnumerable.cs b/BepInEx.IL2CPP/Utils/Collections/ManagedIl2CppEnumerable.cs index aa8377e..86ad853 100644 --- a/BepInEx.IL2CPP/Utils/Collections/ManagedIl2CppEnumerable.cs +++ b/BepInEx.IL2CPP/Utils/Collections/ManagedIl2CppEnumerable.cs @@ -5,7 +5,7 @@ namespace BepInEx.IL2CPP.Utils.Collections; public class ManagedIl2CppEnumerable : IEnumerable { - private Il2CppSystem.Collections.IEnumerable enumerable; + private readonly Il2CppSystem.Collections.IEnumerable enumerable; public ManagedIl2CppEnumerable(Il2CppSystem.Collections.IEnumerable enumerable) { diff --git a/BepInEx.NetLauncher/NetPreloader.cs b/BepInEx.NetLauncher/NetPreloader.cs index 7654531..609c492 100644 --- a/BepInEx.NetLauncher/NetPreloader.cs +++ b/BepInEx.NetLauncher/NetPreloader.cs @@ -20,6 +20,15 @@ public static class NetPreloader { private static readonly ManualLogSource Log = PreloaderLogger.Log; + #region Config + + private static readonly ConfigEntry ConfigEntrypointExecutable = ConfigFile.CoreConfig.Bind( + "Preloader.Entrypoint", "Assembly", + null, + "The local filename of the .NET executable to target."); + + #endregion + [DllImport("Kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] private static extern bool SetDllDirectory(string lpPathName); @@ -34,7 +43,8 @@ public static class NetPreloader if (string.IsNullOrEmpty(ConfigEntrypointExecutable.Value)) { - Log.Log(LogLevel.Fatal, $"Entry executable was not set. Please set this in your config before launching the application"); + Log.Log(LogLevel.Fatal, + $"Entry executable was not set. Please set this in your config before launching the application"); Program.ReadExit(); return; } @@ -76,7 +86,8 @@ public static class NetPreloader { assemblyPatcher.AddPatchersFromDirectory(Paths.PatcherPluginPath); - Log.Log(LogLevel.Info, $"{assemblyPatcher.PatcherContext.PatchDefinitions.Count} patcher definition(s) loaded"); + Log.Log(LogLevel.Info, + $"{assemblyPatcher.PatcherContext.PatchDefinitions.Count} patcher definition(s) loaded"); assemblyPatcher.LoadAssemblyDirectories(new[] { Paths.GameRootPath }, new[] { "dll", "exe" }); @@ -152,13 +163,4 @@ public static class NetPreloader Log.LogFatal($"Unhandled exception: {ex}"); } } - - #region Config - - private static readonly ConfigEntry ConfigEntrypointExecutable = ConfigFile.CoreConfig.Bind( - "Preloader.Entrypoint", "Assembly", - null, - "The local filename of the .NET executable to target."); - - #endregion } diff --git a/BepInEx.Preloader.Core/EnvVars.cs b/BepInEx.Preloader.Core/EnvVars.cs index 180b687..65a6c32 100644 --- a/BepInEx.Preloader.Core/EnvVars.cs +++ b/BepInEx.Preloader.Core/EnvVars.cs @@ -26,7 +26,7 @@ public static class EnvVars public static string DOORSTOP_PROCESS_PATH { get; private set; } /// - /// Array of paths where Mono searches DLLs from before assembly resolvers are invoked. + /// Array of paths where Mono searches DLLs from before assembly resolvers are invoked. /// public static string[] DOORSTOP_DLL_SEARCH_DIRS { get; private set; } diff --git a/BepInEx.Preloader.Core/Logging/PreloaderConsoleListener.cs b/BepInEx.Preloader.Core/Logging/PreloaderConsoleListener.cs index 5df6f2f..f94fbd0 100644 --- a/BepInEx.Preloader.Core/Logging/PreloaderConsoleListener.cs +++ b/BepInEx.Preloader.Core/Logging/PreloaderConsoleListener.cs @@ -23,10 +23,7 @@ public class PreloaderConsoleListener : ILogListener public LogLevel LogLevelFilter => ConfigConsoleDisplayedLevel.Value; /// - public void LogEvent(object sender, LogEventArgs eventArgs) - { - LogEvents.Add(eventArgs); - } + public void LogEvent(object sender, LogEventArgs eventArgs) => LogEvents.Add(eventArgs); /// public void Dispose() { } diff --git a/BepInEx.Preloader.Core/Patching/AssemblyPatcher.cs b/BepInEx.Preloader.Core/Patching/AssemblyPatcher.cs index d710b37..c800d22 100644 --- a/BepInEx.Preloader.Core/Patching/AssemblyPatcher.cs +++ b/BepInEx.Preloader.Core/Patching/AssemblyPatcher.cs @@ -23,7 +23,7 @@ public class AssemblyPatcher : IDisposable private static readonly string CurrentAssemblyName = Assembly.GetExecutingAssembly().GetName().Name; /// - /// The context of this assembly patcher instance that is passed to all patcher plugins. + /// The context of this assembly patcher instance that is passed to all patcher plugins. /// public PatcherContext PatcherContext { get; } = new() { @@ -81,7 +81,8 @@ public class AssemblyPatcher : IDisposable if (string.IsNullOrEmpty(metadata.GUID) || !allowedGuidRegex.IsMatch(metadata.GUID)) { - Logger.Log(LogLevel.Warning, $"Skipping type [{type.FullName}] because its GUID [{metadata.GUID}] is of an illegal format"); + Logger.Log(LogLevel.Warning, + $"Skipping type [{type.FullName}] because its GUID [{metadata.GUID}] is of an illegal format"); return null; } @@ -180,7 +181,8 @@ public class AssemblyPatcher : IDisposable ) { Logger - .Log(LogLevel.Warning, $"Skipping method [{method.FullDescription()}] as it is not a valid patcher method"); + .Log(LogLevel.Warning, + $"Skipping method [{method.FullDescription()}] as it is not a valid patcher method"); continue; } @@ -211,7 +213,8 @@ public class AssemblyPatcher : IDisposable /// - /// Adds all .dll assemblies in given directories to be patched and loaded by this patcher instance. Non-managed assemblies + /// Adds all .dll assemblies in given directories to be patched and loaded by this patcher instance. Non-managed + /// assemblies /// are skipped. /// /// The directories to search. @@ -219,7 +222,8 @@ public class AssemblyPatcher : IDisposable LoadAssemblyDirectories(directories, new[] { "dll" }); /// - /// Adds all assemblies in given directories to be patched and loaded by this patcher instance. Non-managed assemblies are + /// Adds all assemblies in given directories to be patched and loaded by this patcher instance. Non-managed assemblies + /// are /// skipped. /// /// The directory to search. @@ -386,7 +390,8 @@ public class AssemblyPatcher : IDisposable } catch (Exception e) { - Logger.Log(LogLevel.Error, $"Failed to run [{patchDefinition.FullName}] when patching [{assembly.Name.Name}]. This assembly will not be patched. Error: {e}"); + Logger.Log(LogLevel.Error, + $"Failed to run [{patchDefinition.FullName}] when patching [{assembly.Name.Name}]. This assembly will not be patched. Error: {e}"); patchedAssemblies.Remove(targetDll); invalidAssemblies.Add(targetDll); return false; @@ -416,14 +421,14 @@ public class AssemblyPatcher : IDisposable if (earlyLoadAssemblies.Count != 0) Logger.Log(LogLevel.Warning, new StringBuilder() - .AppendLine("The following assemblies have been loaded too early and will not be patched by preloader:") - .AppendLine(string.Join(Environment.NewLine, - earlyLoadAssemblies - .Select(kv => - $"* [{kv.Key}] (first loaded by [{kv.Value}])") - .ToArray())) - .AppendLine("Expect unexpected behavior and issues with plugins and patchers not being loaded.") - .ToString()); + .AppendLine("The following assemblies have been loaded too early and will not be patched by preloader:") + .AppendLine(string.Join(Environment.NewLine, + earlyLoadAssemblies + .Select(kv => + $"* [{kv.Key}] (first loaded by [{kv.Value}])") + .ToArray())) + .AppendLine("Expect unexpected behavior and issues with plugins and patchers not being loaded.") + .ToString()); var dumpedAssemblyPaths = new Dictionary(); // Finally, load patched assemblies into memory @@ -457,7 +462,8 @@ public class AssemblyPatcher : IDisposable if (ConfigBreakBeforeLoadAssemblies.Value) { - Logger.Log(LogLevel.Info, $"BepInEx is about load the following assemblies:\n{string.Join("\n", patchedAssemblies.ToArray())}"); + Logger.Log(LogLevel.Info, + $"BepInEx is about load the following assemblies:\n{string.Join("\n", patchedAssemblies.ToArray())}"); Logger.Log(LogLevel.Info, $"The assemblies were dumped into {PatcherContext.DumpedAssembliesPath}"); Logger.Log(LogLevel.Info, "Load any assemblies into the debugger, set breakpoints and continue execution."); Debugger.Break(); diff --git a/BepInEx.Preloader.Core/Patching/Attributes.cs b/BepInEx.Preloader.Core/Patching/Attributes.cs index b9a5c4c..95b21c4 100644 --- a/BepInEx.Preloader.Core/Patching/Attributes.cs +++ b/BepInEx.Preloader.Core/Patching/Attributes.cs @@ -80,35 +80,38 @@ public class PatcherPluginInfoAttribute : Attribute } /// -/// Defines an assembly that a patch method will target. +/// Defines an assembly that a patch method will target. /// [AttributeUsage(AttributeTargets.Method)] public class TargetAssemblyAttribute : Attribute { /// - /// Marker used to indicate all possible assemblies to be targeted by a patch method. + /// Marker used to indicate all possible assemblies to be targeted by a patch method. /// public const string AllAssemblies = "_all"; - /// The short filename of the assembly. Use to mark all possible assemblies as targets. + /// + /// The short filename of the assembly. Use to mark all possible + /// assemblies as targets. + /// public TargetAssemblyAttribute(string targetAssembly) { TargetAssembly = targetAssembly; } /// - /// The short filename of the assembly to target. + /// The short filename of the assembly to target. /// public string TargetAssembly { get; } } /// -/// Defines a type that a patch method will target. +/// Defines a type that a patch method will target. /// [AttributeUsage(AttributeTargets.Method)] public class TargetTypeAttribute : Attribute { - /// The short filename of the assembly of which belongs to. + /// The short filename of the assembly of which belongs to. /// The full name of the type to target for patching. public TargetTypeAttribute(string targetAssembly, string targetType) { @@ -117,12 +120,12 @@ public class TargetTypeAttribute : Attribute } /// - /// The short filename of the assembly to target. + /// The short filename of the assembly to target. /// public string TargetAssembly { get; } /// - /// The full name of the type to target for patching. + /// The full name of the type to target for patching. /// public string TargetType { get; } } diff --git a/BepInEx.Preloader.Core/Patching/BasePatcher.cs b/BepInEx.Preloader.Core/Patching/BasePatcher.cs index bc16cd0..1543731 100644 --- a/BepInEx.Preloader.Core/Patching/BasePatcher.cs +++ b/BepInEx.Preloader.Core/Patching/BasePatcher.cs @@ -8,26 +8,6 @@ namespace BepInEx.Preloader.Core.Patching; /// public abstract class BasePatcher { - /// - /// A instance created for use by this patcher plugin. - /// - public ManualLogSource Log { get; } - - /// - /// A configuration file binding created with the of this plugin as the filename. - /// - public ConfigFile Config { get; } - - /// - /// Metadata associated with this patcher plugin. - /// - public PatcherPluginInfoAttribute Info { get; } - - /// - /// The context of the this BasePatcher is associated with. - /// - public PatcherContext Context { get; set; } - protected BasePatcher() { Info = PatcherPluginInfoAttribute.FromType(GetType()); @@ -38,6 +18,27 @@ public abstract class BasePatcher new BepInPlugin(Info.GUID, Info.Name, Info.Version.ToString())); } + /// + /// A instance created for use by this patcher plugin. + /// + public ManualLogSource Log { get; } + + /// + /// A configuration file binding created with the of this plugin as the + /// filename. + /// + public ConfigFile Config { get; } + + /// + /// Metadata associated with this patcher plugin. + /// + public PatcherPluginInfoAttribute Info { get; } + + /// + /// The context of the this BasePatcher is associated with. + /// + public PatcherContext Context { get; set; } + /// /// Executed before any patches from any plugin are applied. /// diff --git a/BepInEx.Preloader.Core/Patching/PatcherContext.cs b/BepInEx.Preloader.Core/Patching/PatcherContext.cs index 1331bea..d918061 100644 --- a/BepInEx.Preloader.Core/Patching/PatcherContext.cs +++ b/BepInEx.Preloader.Core/Patching/PatcherContext.cs @@ -5,7 +5,7 @@ using Mono.Cecil; namespace BepInEx.Preloader.Core.Patching; /// -/// A definition of an individual patch for use by . +/// A definition of an individual patch for use by . /// public class PatchDefinition { @@ -31,20 +31,20 @@ public class PatchDefinition /// /// The assembly / assemblies this patch will target, if there any. /// - public TargetAssemblyAttribute TargetAssembly { get; } = null; + public TargetAssemblyAttribute TargetAssembly { get; } /// /// The type / types this patch will target, if there are any. /// - public TargetTypeAttribute TargetType { get; } = null; + public TargetTypeAttribute TargetType { get; } /// - /// The instance of the this originates from. + /// The instance of the this originates from. /// public BasePatcher Instance { get; } /// - /// The method that will perform the patching logic defined by this instance. + /// The method that will perform the patching logic defined by this instance. /// public MethodInfo MethodInfo { get; } @@ -55,7 +55,7 @@ public class PatchDefinition } /// -/// Context provided to patcher plugins from the associated patcher engine. +/// Context provided to patcher plugins from the associated patcher engine. /// public class PatcherContext { @@ -85,7 +85,8 @@ public class PatcherContext public List PatcherPlugins { get; } = new(); /// - /// A list of individual patches that will execute, generated by parsing . + /// A list of individual patches that will execute, generated by parsing + /// . /// public List PatchDefinitions { get; } = new(); diff --git a/BepInEx.Preloader.Unity/EntrypointPatcher.cs b/BepInEx.Preloader.Unity/EntrypointPatcher.cs index f942d5a..c6a707f 100644 --- a/BepInEx.Preloader.Unity/EntrypointPatcher.cs +++ b/BepInEx.Preloader.Unity/EntrypointPatcher.cs @@ -14,7 +14,24 @@ namespace BepInEx.Preloader.Unity; [PatcherPluginInfo("io.bepinex.entrypointpatcher", "BepInEx Entrypoint", "1.0")] internal class EntrypointPatcher : BasePatcher { - private bool HasLoaded { get; set; } = false; + private static readonly ConfigEntry ConfigEntrypointAssembly = ConfigFile.CoreConfig.Bind( + "Preloader.Entrypoint", "Assembly", + UnityPreloader.IsPostUnity2017 + ? "UnityEngine.CoreModule.dll" + : "UnityEngine.dll", + "The local filename of the assembly to target."); + + private static readonly ConfigEntry ConfigEntrypointType = ConfigFile.CoreConfig.Bind( + "Preloader.Entrypoint", "Type", + "Application", + "The name of the type in the entrypoint assembly to search for the entrypoint method."); + + private static readonly ConfigEntry ConfigEntrypointMethod = ConfigFile.CoreConfig.Bind( + "Preloader.Entrypoint", "Method", + ".cctor", + "The name of the method in the specified entrypoint assembly and type to hook and load Chainloader from."); + + private bool HasLoaded { get; set; } [TargetAssembly(TargetAssemblyAttribute.AllAssemblies)] public bool PatchEntrypoint(ref AssemblyDefinition assembly, string filename) @@ -110,23 +127,7 @@ internal class EntrypointPatcher : BasePatcher public override void Finalizer() { if (!HasLoaded) - Log.Log(LogLevel.Fatal, $"Failed to patch BepInEx chainloader into assembly '{ConfigEntrypointAssembly.Value}', either due to error or not being able to find it. Is it spelled correctly?"); + Log.Log(LogLevel.Fatal, + $"Failed to patch BepInEx chainloader into assembly '{ConfigEntrypointAssembly.Value}', either due to error or not being able to find it. Is it spelled correctly?"); } - - private static readonly ConfigEntry ConfigEntrypointAssembly = ConfigFile.CoreConfig.Bind( - "Preloader.Entrypoint", "Assembly", - UnityPreloader.IsPostUnity2017 - ? "UnityEngine.CoreModule.dll" - : "UnityEngine.dll", - "The local filename of the assembly to target."); - - private static readonly ConfigEntry ConfigEntrypointType = ConfigFile.CoreConfig.Bind( - "Preloader.Entrypoint", "Type", - "Application", - "The name of the type in the entrypoint assembly to search for the entrypoint method."); - - private static readonly ConfigEntry ConfigEntrypointMethod = ConfigFile.CoreConfig.Bind( - "Preloader.Entrypoint", "Method", - ".cctor", - "The name of the method in the specified entrypoint assembly and type to hook and load Chainloader from."); } diff --git a/BepInEx.Preloader.Unity/UnityPreloader.cs b/BepInEx.Preloader.Unity/UnityPreloader.cs index 873b31b..99d0f4a 100644 --- a/BepInEx.Preloader.Unity/UnityPreloader.cs +++ b/BepInEx.Preloader.Unity/UnityPreloader.cs @@ -53,15 +53,16 @@ internal static class UnityPreloader ChainloaderLogHelper.PrintLogInfo(Log); Log.Log(LogLevel.Info, $"Running under Unity v{GetUnityVersion()}"); - Log.Log(LogLevel.Info,$"CLR runtime version: {Environment.Version}"); - Log.Log(LogLevel.Info,$"Supports SRE: {Utility.CLRSupportsDynamicAssemblies}"); + Log.Log(LogLevel.Info, $"CLR runtime version: {Environment.Version}"); + Log.Log(LogLevel.Info, $"Supports SRE: {Utility.CLRSupportsDynamicAssemblies}"); Log.Log(LogLevel.Debug, $"Game executable path: {Paths.ExecutablePath}"); - Log.Log(LogLevel.Debug,$"Unity Managed directory: {Paths.ManagedPath}"); - Log.Log(LogLevel.Debug,$"BepInEx root path: {Paths.BepInExRootPath}"); + Log.Log(LogLevel.Debug, $"Unity Managed directory: {Paths.ManagedPath}"); + Log.Log(LogLevel.Debug, $"BepInEx root path: {Paths.BepInExRootPath}"); if (runtimePatchException != null) - Log.Log(LogLevel.Warning, $"Failed to apply runtime patches for Mono. See more info in the output log. Error message: {runtimePatchException.Message}"); + Log.Log(LogLevel.Warning, + $"Failed to apply runtime patches for Mono. See more info in the output log. Error message: {runtimePatchException.Message}"); Log.Log(LogLevel.Message, "Preloader started"); @@ -72,11 +73,13 @@ internal static class UnityPreloader assemblyPatcher.AddPatchersFromDirectory(Paths.BepInExAssemblyDirectory); assemblyPatcher.AddPatchersFromDirectory(Paths.PatcherPluginPath); - Log.Log(LogLevel.Info, $"{assemblyPatcher.PatcherContext.PatcherPlugins.Count} patcher plugin{(assemblyPatcher.PatcherContext.PatcherPlugins.Count == 1 ? "" : "s")} loaded"); + Log.Log(LogLevel.Info, + $"{assemblyPatcher.PatcherContext.PatcherPlugins.Count} patcher plugin{(assemblyPatcher.PatcherContext.PatcherPlugins.Count == 1 ? "" : "s")} loaded"); assemblyPatcher.LoadAssemblyDirectories(Paths.DllSearchPaths); - Log.Log(LogLevel.Info, $"{assemblyPatcher.PatcherContext.AvailableAssemblies.Count} assemblies discovered"); + Log.Log(LogLevel.Info, + $"{assemblyPatcher.PatcherContext.AvailableAssemblies.Count} assemblies discovered"); assemblyPatcher.PatchAndLoad(); } diff --git a/BepInEx.Unity/Configuration/KeyboardShortcut.cs b/BepInEx.Unity/Configuration/KeyboardShortcut.cs index 7410a73..a8ffd88 100644 --- a/BepInEx.Unity/Configuration/KeyboardShortcut.cs +++ b/BepInEx.Unity/Configuration/KeyboardShortcut.cs @@ -54,7 +54,7 @@ public struct KeyboardShortcut /// 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) - .ToArray()) + .ToArray()) { if (mainKey == KeyCode.None && modifiers.Any()) throw new diff --git a/BepInEx.Unity/Logging/UnityLogListener.cs b/BepInEx.Unity/Logging/UnityLogListener.cs index 9a058dc..bd3f56a 100644 --- a/BepInEx.Unity/Logging/UnityLogListener.cs +++ b/BepInEx.Unity/Logging/UnityLogListener.cs @@ -16,17 +16,17 @@ namespace BepInEx.Unity.Logging { internal static readonly Action WriteStringToUnityLog; + protected static readonly ConfigEntry ConfigUnityLogLevel = ConfigFile.CoreConfig.Bind( + "Logging.Unity", "LogLevels", + LogLevel.Fatal | LogLevel.Error | LogLevel.Warning | LogLevel.Message | LogLevel.Info, + "What log levels to log to Unity's output log."); + private readonly ConfigEntry LogConsoleToUnity = ConfigFile.CoreConfig.Bind("Logging", "LogConsoleToUnityLog", false, new StringBuilder() .AppendLine("If enabled, writes Standard Output messages to Unity log") .AppendLine("NOTE: By default, Unity does so automatically. Only use this option if no console messages are visible in Unity log") .ToString()); - - protected static readonly ConfigEntry ConfigUnityLogLevel = ConfigFile.CoreConfig.Bind( - "Logging.Unity", "LogLevels", - LogLevel.Fatal | LogLevel.Error | LogLevel.Warning | LogLevel.Message | LogLevel.Info, - "What log levels to log to Unity's output log."); static UnityLogListener() {