Preloader.cs 9.6 KB

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