Preloader.cs 9.1 KB

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