Preloader.cs 9.1 KB

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