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