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. Logger.Listeners.Add(new ConsoleLogListener());
  41. PreloaderLog = new PreloaderConsoleListener();
  42. Logger.Listeners.Add(PreloaderLog);
  43. string consoleTile = $"BepInEx {typeof(Paths).Assembly.GetName().Version} - {Paths.ProcessName}";
  44. if (ConsoleManager.ConsoleActive)
  45. ConsoleManager.SetConsoleTitle(consoleTile);
  46. Logger.LogMessage(consoleTile);
  47. //See BuildInfoAttribute for more information about this section.
  48. object[] attributes = typeof(BuildInfoAttribute).Assembly.GetCustomAttributes(typeof(BuildInfoAttribute), false);
  49. if (attributes.Length > 0)
  50. {
  51. var attribute = (BuildInfoAttribute)attributes[0];
  52. Logger.LogMessage(attribute.Info);
  53. }
  54. Logger.LogInfo($"Running under Unity v{GetUnityVersion()}");
  55. Logger.LogInfo($"CLR runtime version: {Environment.Version}");
  56. Logger.LogInfo($"Supports SRE: {Utility.CLRSupportsDynamicAssemblies}");
  57. if (runtimePatchException != null)
  58. Logger.LogWarning($"Failed to apply runtime patches for Mono. See more info in the output log. Error message: {runtimePatchException.Message}");
  59. Logger.LogMessage("Preloader started");
  60. AssemblyPatcher.AddPatcher(new PatcherPlugin
  61. {
  62. TargetDLLs = () => new[] { ConfigEntrypointAssembly.Value },
  63. Patcher = PatchEntrypoint,
  64. TypeName = "BepInEx.Chainloader"
  65. });
  66. AssemblyPatcher.AddPatchersFromDirectory(Paths.PatcherPluginPath);
  67. Logger.LogInfo($"{AssemblyPatcher.PatcherPlugins.Count} patcher plugin(s) loaded");
  68. AssemblyPatcher.PatchAndLoad(Paths.ManagedPath);
  69. AssemblyPatcher.DisposePatchers();
  70. Logger.LogMessage("Preloader finished");
  71. Logger.Listeners.Remove(PreloaderLog);
  72. PreloaderLog.Dispose();
  73. }
  74. catch (Exception ex)
  75. {
  76. try
  77. {
  78. Logger.LogFatal("Could not run preloader!");
  79. Logger.LogFatal(ex);
  80. if (!ConsoleManager.ConsoleActive)
  81. {
  82. //if we've already attached the console, then the log will already be written to the console
  83. AllocateConsole();
  84. Console.Write(PreloaderLog);
  85. }
  86. }
  87. catch { }
  88. string log = string.Empty;
  89. try
  90. {
  91. // We could use platform-dependent newlines, however the developers use Windows so this will be easier to read :)
  92. log = string.Join("\r\n", PreloaderConsoleListener.LogEvents.Select(x => x.ToString()).ToArray());
  93. log += "\r\n";
  94. PreloaderLog?.Dispose();
  95. PreloaderLog = null;
  96. }
  97. catch { }
  98. File.WriteAllText(
  99. Path.Combine(Paths.GameRootPath, $"preloader_{DateTime.Now:yyyyMMdd_HHmmss_fff}.log"),
  100. log + ex);
  101. }
  102. }
  103. /// <summary>
  104. /// Inserts BepInEx's own chainloader entrypoint into UnityEngine.
  105. /// </summary>
  106. /// <param name="assembly">The assembly that will be attempted to be patched.</param>
  107. public static void PatchEntrypoint(ref AssemblyDefinition assembly)
  108. {
  109. if (assembly.MainModule.AssemblyReferences.Any(x => x.Name.Contains("BepInEx")))
  110. throw new Exception("BepInEx has been detected to be patched! Please unpatch before using a patchless variant!");
  111. string entrypointType = ConfigEntrypointType.Value;
  112. string entrypointMethod = ConfigEntrypointMethod.Value;
  113. bool isCctor = entrypointMethod.IsNullOrWhiteSpace() || entrypointMethod == ".cctor";
  114. var entryType = assembly.MainModule.Types.FirstOrDefault(x => x.Name == entrypointType);
  115. if (entryType == null)
  116. throw new Exception("The entrypoint type is invalid! Please check your config/BepInEx.cfg file");
  117. using (var injected = AssemblyDefinition.ReadAssembly(Paths.BepInExAssemblyPath))
  118. {
  119. var originalInitMethod = injected.MainModule.Types.First(x => x.Name == "Chainloader").Methods
  120. .First(x => x.Name == "Initialize");
  121. var originalStartMethod = injected.MainModule.Types.First(x => x.Name == "Chainloader").Methods
  122. .First(x => x.Name == "Start");
  123. var initMethod = assembly.MainModule.ImportReference(originalInitMethod);
  124. var startMethod = assembly.MainModule.ImportReference(originalStartMethod);
  125. var methods = new List<MethodDefinition>();
  126. if (isCctor)
  127. {
  128. var cctor = entryType.Methods.FirstOrDefault(m => m.IsConstructor && m.IsStatic);
  129. if (cctor == null)
  130. {
  131. cctor = new MethodDefinition(".cctor",
  132. MethodAttributes.Static | MethodAttributes.Private | MethodAttributes.HideBySig
  133. | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName,
  134. assembly.MainModule.ImportReference(typeof(void)));
  135. entryType.Methods.Add(cctor);
  136. var il = cctor.Body.GetILProcessor();
  137. il.Append(il.Create(OpCodes.Ret));
  138. }
  139. methods.Add(cctor);
  140. }
  141. else
  142. {
  143. methods.AddRange(entryType.Methods.Where(x => x.Name == entrypointMethod));
  144. }
  145. if (!methods.Any())
  146. throw new Exception("The entrypoint method is invalid! Please check your config.ini");
  147. foreach (var method in methods)
  148. {
  149. var il = method.Body.GetILProcessor();
  150. var ins = il.Body.Instructions.First();
  151. il.InsertBefore(ins,
  152. il.Create(OpCodes.Ldnull)); // gameExePath (always null, we initialize the Paths class in Entrypoint
  153. il.InsertBefore(ins,
  154. il.Create(OpCodes.Ldc_I4_0)); //startConsole (always false, we already load the console in Preloader)
  155. il.InsertBefore(ins,
  156. il.Create(OpCodes.Call, assembly.MainModule.ImportReference(
  157. AccessTools.PropertyGetter(typeof(PreloaderConsoleListener), nameof(PreloaderConsoleListener.LogEvents))))); // preloaderLogEvents (load from Preloader.PreloaderLog.LogEvents)
  158. il.InsertBefore(ins,
  159. il.Create(OpCodes.Call, initMethod)); // Chainloader.Initialize(string gamePath, string managedPath = null, bool startConsole = true)
  160. il.InsertBefore(ins,
  161. il.Create(OpCodes.Call, startMethod));
  162. }
  163. }
  164. }
  165. /// <summary>
  166. /// Allocates a console window for use by BepInEx safely.
  167. /// </summary>
  168. public static void AllocateConsole()
  169. {
  170. if (!ConsoleManager.ConfigConsoleEnabled.Value)
  171. return;
  172. try
  173. {
  174. ConsoleManager.CreateConsole();
  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. }