Preloader.cs 9.4 KB

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