Preloader.cs 9.4 KB

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