Preloader.cs 9.4 KB

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