Preloader.cs 8.8 KB

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