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