Preloader.cs 9.3 KB

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