Preloader.cs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Linq;
  6. using BepInEx.Configuration;
  7. using BepInEx.Logging;
  8. using BepInEx.Preloader.Patching;
  9. using BepInEx.Preloader.RuntimeFixes;
  10. using HarmonyLib;
  11. using Mono.Cecil;
  12. using Mono.Cecil.Cil;
  13. using MonoMod.RuntimeDetour;
  14. using MonoMod.Utils;
  15. using MethodAttributes = Mono.Cecil.MethodAttributes;
  16. namespace BepInEx.Preloader
  17. {
  18. /// <summary>
  19. /// The main entrypoint of BepInEx, and initializes all patchers and the chainloader.
  20. /// </summary>
  21. internal static class Preloader
  22. {
  23. /// <summary>
  24. /// The log writer that is specific to the preloader.
  25. /// </summary>
  26. private static PreloaderConsoleListener PreloaderLog { get; set; }
  27. public static bool IsPostUnity2017 { get; } = File.Exists(Path.Combine(Paths.ManagedPath, "UnityEngine.CoreModule.dll"));
  28. public static void Run()
  29. {
  30. try
  31. {
  32. ConsoleManager.Initialize(false);
  33. AllocateConsole();
  34. bool bridgeInitialized = Utility.TryDo(() =>
  35. {
  36. if (ConfigShimHarmony.Value)
  37. HarmonyDetourBridge.Init();
  38. }, out var harmonyBridgeException);
  39. Exception runtimePatchException = null;
  40. if (bridgeInitialized)
  41. Utility.TryDo(() =>
  42. {
  43. if (ConfigApplyRuntimePatches.Value)
  44. UnityPatches.Apply();
  45. }, out runtimePatchException);
  46. Logger.Sources.Add(TraceLogSource.CreateSource());
  47. HarmonyFixes.Apply();
  48. PreloaderLog = new PreloaderConsoleListener(ConfigPreloaderCOutLogging.Value);
  49. Logger.Listeners.Add(PreloaderLog);
  50. string consoleTile = $"BepInEx {typeof(Paths).Assembly.GetName().Version} - {Path.GetFileNameWithoutExtension(Process.GetCurrentProcess().ProcessName)}";
  51. if (ConsoleManager.ConsoleActive)
  52. ConsoleManager.SetConsoleTitle(consoleTile);
  53. Logger.LogMessage(consoleTile);
  54. //See BuildInfoAttribute for more information about this section.
  55. object[] attributes = typeof(BuildInfoAttribute).Assembly.GetCustomAttributes(typeof(BuildInfoAttribute), false);
  56. if (attributes.Length > 0)
  57. {
  58. var attribute = (BuildInfoAttribute)attributes[0];
  59. Logger.LogMessage(attribute.Info);
  60. }
  61. Logger.LogInfo($"Running under Unity v{GetUnityVersion()}");
  62. Logger.LogInfo($"CLR runtime version: {Environment.Version}");
  63. Logger.LogInfo($"Supports SRE: {Utility.CLRSupportsDynamicAssemblies}");
  64. if (harmonyBridgeException != null)
  65. Logger.LogWarning($"Failed to enable fix for Harmony for .NET Standard API. Error message: {harmonyBridgeException.Message}");
  66. if (runtimePatchException != null)
  67. Logger.LogWarning($"Failed to apply runtime patches for Mono. See more info in the output log. Error message: {runtimePatchException.Message}");
  68. Logger.LogMessage("Preloader started");
  69. AssemblyPatcher.AddPatcher(new PatcherPlugin
  70. {
  71. TargetDLLs = () => new[] { ConfigEntrypointAssembly.Value },
  72. Patcher = PatchEntrypoint,
  73. TypeName = "BepInEx.Chainloader"
  74. });
  75. AssemblyPatcher.AddPatchersFromDirectory(Paths.PatcherPluginPath);
  76. Logger.LogInfo($"{AssemblyPatcher.PatcherPlugins.Count} patcher plugin(s) loaded");
  77. AssemblyPatcher.PatchAndLoad(Paths.ManagedPath);
  78. AssemblyPatcher.DisposePatchers();
  79. Logger.LogMessage("Preloader finished");
  80. Logger.Listeners.Remove(PreloaderLog);
  81. Logger.Listeners.Add(new ConsoleLogListener());
  82. PreloaderLog.Dispose();
  83. }
  84. catch (Exception ex)
  85. {
  86. try
  87. {
  88. Logger.LogFatal("Could not run preloader!");
  89. Logger.LogFatal(ex);
  90. if (!ConsoleManager.ConsoleActive)
  91. {
  92. //if we've already attached the console, then the log will already be written to the console
  93. AllocateConsole();
  94. Console.Write(PreloaderLog);
  95. }
  96. }
  97. catch { }
  98. string log = string.Empty;
  99. try
  100. {
  101. // We could use platform-dependent newlines, however the developers use Windows so this will be easier to read :)
  102. log = string.Join("\r\n", PreloaderConsoleListener.LogEvents.Select(x => x.ToString()).ToArray());
  103. log += "\r\n";
  104. PreloaderLog?.Dispose();
  105. PreloaderLog = null;
  106. }
  107. catch { }
  108. File.WriteAllText(
  109. Path.Combine(Paths.GameRootPath, $"preloader_{DateTime.Now:yyyyMMdd_HHmmss_fff}.log"),
  110. log + ex);
  111. }
  112. }
  113. /// <summary>
  114. /// Inserts BepInEx's own chainloader entrypoint into UnityEngine.
  115. /// </summary>
  116. /// <param name="assembly">The assembly that will be attempted to be patched.</param>
  117. public static void PatchEntrypoint(ref AssemblyDefinition assembly)
  118. {
  119. if (assembly.MainModule.AssemblyReferences.Any(x => x.Name.Contains("BepInEx")))
  120. throw new Exception("BepInEx has been detected to be patched! Please unpatch before using a patchless variant!");
  121. string entrypointType = ConfigEntrypointType.Value;
  122. string entrypointMethod = ConfigEntrypointMethod.Value;
  123. bool isCctor = entrypointMethod.IsNullOrWhiteSpace() || entrypointMethod == ".cctor";
  124. var entryType = assembly.MainModule.Types.FirstOrDefault(x => x.Name == entrypointType);
  125. if (entryType == null)
  126. throw new Exception("The entrypoint type is invalid! Please check your config/BepInEx.cfg file");
  127. using (var injected = AssemblyDefinition.ReadAssembly(Paths.BepInExAssemblyPath))
  128. {
  129. var originalInitMethod = injected.MainModule.Types.First(x => x.Name == "Chainloader").Methods
  130. .First(x => x.Name == "Initialize");
  131. var originalStartMethod = injected.MainModule.Types.First(x => x.Name == "Chainloader").Methods
  132. .First(x => x.Name == "Start");
  133. var initMethod = assembly.MainModule.ImportReference(originalInitMethod);
  134. var startMethod = assembly.MainModule.ImportReference(originalStartMethod);
  135. var methods = new List<MethodDefinition>();
  136. if (isCctor)
  137. {
  138. var cctor = entryType.Methods.FirstOrDefault(m => m.IsConstructor && m.IsStatic);
  139. if (cctor == null)
  140. {
  141. cctor = new MethodDefinition(".cctor",
  142. MethodAttributes.Static | MethodAttributes.Private | MethodAttributes.HideBySig
  143. | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName,
  144. assembly.MainModule.ImportReference(typeof(void)));
  145. entryType.Methods.Add(cctor);
  146. var il = cctor.Body.GetILProcessor();
  147. il.Append(il.Create(OpCodes.Ret));
  148. }
  149. methods.Add(cctor);
  150. }
  151. else
  152. {
  153. methods.AddRange(entryType.Methods.Where(x => x.Name == entrypointMethod));
  154. }
  155. if (!methods.Any())
  156. throw new Exception("The entrypoint method is invalid! Please check your config.ini");
  157. foreach (var method in methods)
  158. {
  159. var il = method.Body.GetILProcessor();
  160. var ins = il.Body.Instructions.First();
  161. il.InsertBefore(ins,
  162. il.Create(OpCodes.Ldnull)); // gameExePath (always null, we initialize the Paths class in Entrypoint
  163. il.InsertBefore(ins,
  164. il.Create(OpCodes.Ldc_I4_0)); //startConsole (always false, we already load the console in Preloader)
  165. il.InsertBefore(ins,
  166. il.Create(OpCodes.Call, assembly.MainModule.ImportReference(
  167. AccessTools.PropertyGetter(typeof(PreloaderConsoleListener), nameof(PreloaderConsoleListener.LogEvents))))); // preloaderLogEvents (load from Preloader.PreloaderLog.LogEvents)
  168. il.InsertBefore(ins,
  169. il.Create(OpCodes.Call, initMethod)); // Chainloader.Initialize(string gamePath, string managedPath = null, bool startConsole = true)
  170. il.InsertBefore(ins,
  171. il.Create(OpCodes.Call, startMethod));
  172. }
  173. }
  174. }
  175. /// <summary>
  176. /// Allocates a console window for use by BepInEx safely.
  177. /// </summary>
  178. public static void AllocateConsole()
  179. {
  180. if (!ConsoleManager.ConfigConsoleEnabled.Value)
  181. return;
  182. try
  183. {
  184. ConsoleManager.CreateConsole();
  185. ConsoleManager.SetConsoleEncoding();
  186. }
  187. catch (Exception ex)
  188. {
  189. Logger.LogError("Failed to allocate console!");
  190. Logger.LogError(ex);
  191. }
  192. }
  193. public static string GetUnityVersion()
  194. {
  195. if (Utility.CurrentOs == Platform.Windows)
  196. return FileVersionInfo.GetVersionInfo(Paths.ExecutablePath).FileVersion;
  197. return $"Unknown ({(IsPostUnity2017 ? "post" : "pre")}-2017)";
  198. }
  199. #region Config
  200. private static readonly ConfigEntry<string> ConfigEntrypointAssembly = ConfigFile.CoreConfig.Bind(
  201. "Preloader.Entrypoint", "Assembly",
  202. IsPostUnity2017 ? "UnityEngine.CoreModule.dll" : "UnityEngine.dll",
  203. "The local filename of the assembly to target.");
  204. private static readonly ConfigEntry<string> ConfigEntrypointType = ConfigFile.CoreConfig.Bind(
  205. "Preloader.Entrypoint", "Type",
  206. "Application",
  207. "The name of the type in the entrypoint assembly to search for the entrypoint method.");
  208. private static readonly ConfigEntry<string> ConfigEntrypointMethod = ConfigFile.CoreConfig.Bind(
  209. "Preloader.Entrypoint", "Method",
  210. ".cctor",
  211. "The name of the method in the specified entrypoint assembly and type to hook and load Chainloader from.");
  212. internal static readonly ConfigEntry<bool> ConfigApplyRuntimePatches = ConfigFile.CoreConfig.Bind(
  213. "Preloader", "ApplyRuntimePatches",
  214. true,
  215. "Enables or disables runtime patches.\nThis should always be true, unless you cannot start the game due to a Harmony related issue (such as running .NET Standard runtime) or you know what you're doing.");
  216. private static readonly ConfigEntry<bool> ConfigShimHarmony = ConfigFile.CoreConfig.Bind(
  217. "Preloader", "ShimHarmonySupport",
  218. !Utility.CLRSupportsDynamicAssemblies,
  219. "If enabled, basic Harmony functionality is patched to use MonoMod's RuntimeDetour instead.\nTry using this if Harmony does not work in a game.");
  220. private static readonly ConfigEntry<bool> ConfigPreloaderCOutLogging = ConfigFile.CoreConfig.Bind(
  221. "Logging", "PreloaderConsoleOutRedirection",
  222. true,
  223. "Redirects text from Console.Out during preloader patch loading to the BepInEx logging system.");
  224. #endregion
  225. }
  226. }