Preloader.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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 void Run()
  28. {
  29. try
  30. {
  31. AllocateConsole();
  32. if (ConfigApplyRuntimePatches.Value)
  33. UnityPatches.Apply();
  34. Logger.Sources.Add(TraceLogSource.CreateSource());
  35. PreloaderLog = new PreloaderConsoleListener(ConfigPreloaderCOutLogging.Value);
  36. Logger.Listeners.Add(PreloaderLog);
  37. string consoleTile = $"BepInEx {typeof(Paths).Assembly.GetName().Version} RC1 - {Process.GetCurrentProcess().ProcessName}";
  38. ConsoleWindow.Title = consoleTile;
  39. Logger.LogMessage(consoleTile);
  40. //See BuildInfoAttribute for more information about this section.
  41. object[] attributes = typeof(BuildInfoAttribute).Assembly.GetCustomAttributes(typeof(BuildInfoAttribute), false);
  42. if (attributes.Length > 0)
  43. {
  44. var attribute = (BuildInfoAttribute)attributes[0];
  45. Logger.LogMessage(attribute.Info);
  46. }
  47. #if UNITY_2018
  48. Logger.LogMessage("Compiled in Unity v2018 mode");
  49. #else
  50. Logger.LogMessage("Compiled in Legacy Unity mode");
  51. #endif
  52. Logger.LogInfo($"Running under Unity v{Process.GetCurrentProcess().MainModule.FileVersionInfo.FileVersion}");
  53. Logger.LogMessage("Preloader started");
  54. AssemblyPatcher.AddPatcher(new PatcherPlugin
  55. { TargetDLLs = new[] { ConfigEntrypointAssembly.Value },
  56. Patcher = PatchEntrypoint,
  57. Name = "BepInEx.Chainloader"
  58. });
  59. AssemblyPatcher.AddPatchersFromDirectory(Paths.PatcherPluginPath, GetPatcherMethods);
  60. Logger.LogInfo($"{AssemblyPatcher.PatcherPlugins.Count} patcher plugin(s) loaded");
  61. AssemblyPatcher.PatchAndLoad(Paths.ManagedPath);
  62. AssemblyPatcher.DisposePatchers();
  63. Logger.LogMessage("Preloader finished");
  64. Logger.Listeners.Remove(PreloaderLog);
  65. Logger.Listeners.Add(new ConsoleLogListener());
  66. PreloaderLog.Dispose();
  67. }
  68. catch (Exception ex)
  69. {
  70. try
  71. {
  72. Logger.LogFatal("Could not run preloader!");
  73. Logger.LogFatal(ex);
  74. PreloaderLog?.Dispose();
  75. if (!ConsoleWindow.IsAttached)
  76. {
  77. //if we've already attached the console, then the log will already be written to the console
  78. AllocateConsole();
  79. Console.Write(PreloaderLog);
  80. }
  81. PreloaderLog = null;
  82. }
  83. finally
  84. {
  85. File.WriteAllText(
  86. Path.Combine(Paths.GameRootPath, $"preloader_{DateTime.Now:yyyyMMdd_HHmmss_fff}.log"),
  87. PreloaderLog + "\r\n" + ex);
  88. PreloaderLog?.Dispose();
  89. PreloaderLog = null;
  90. }
  91. }
  92. }
  93. /// <summary>
  94. /// Scans the assembly for classes that use the patcher contract, and returns a list of valid patchers.
  95. /// </summary>
  96. /// <param name="assembly">The assembly to scan.</param>
  97. /// <returns>A list of assembly patchers that were found in the assembly.</returns>
  98. public static List<PatcherPlugin> GetPatcherMethods(Assembly assembly)
  99. {
  100. var patcherMethods = new List<PatcherPlugin>();
  101. var flags = BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase;
  102. foreach (var type in assembly.GetExportedTypes())
  103. try
  104. {
  105. if (type.IsInterface)
  106. continue;
  107. var targetsProperty = type.GetProperty("TargetDLLs",
  108. flags,
  109. null,
  110. typeof(IEnumerable<string>),
  111. Type.EmptyTypes,
  112. null);
  113. //first try get the ref patcher method
  114. var patcher = type.GetMethod("Patch",
  115. flags,
  116. null,
  117. CallingConventions.Any,
  118. new[] { typeof(AssemblyDefinition).MakeByRefType() },
  119. null);
  120. if (patcher == null) //otherwise try getting the non-ref patcher method
  121. patcher = type.GetMethod("Patch",
  122. flags,
  123. null,
  124. CallingConventions.Any,
  125. new[] { typeof(AssemblyDefinition) },
  126. null);
  127. if (targetsProperty == null || !targetsProperty.CanRead || patcher == null)
  128. continue;
  129. var assemblyPatcher = new PatcherPlugin();
  130. assemblyPatcher.Name = $"{assembly.GetName().Name}/{type.FullName}";
  131. assemblyPatcher.Patcher = (ref AssemblyDefinition ass) =>
  132. {
  133. //we do the array fuckery here to get the ref result out
  134. object[] args = { ass };
  135. patcher.Invoke(null, args);
  136. ass = (AssemblyDefinition)args[0];
  137. };
  138. assemblyPatcher.TargetDLLs = (IEnumerable<string>)targetsProperty.GetValue(null, null);
  139. var initMethod = type.GetMethod("Initialize",
  140. flags,
  141. null,
  142. CallingConventions.Any,
  143. Type.EmptyTypes,
  144. null);
  145. if (initMethod != null)
  146. assemblyPatcher.Initializer = () => initMethod.Invoke(null, null);
  147. var finalizeMethod = type.GetMethod("Finish",
  148. flags,
  149. null,
  150. CallingConventions.Any,
  151. Type.EmptyTypes,
  152. null);
  153. if (finalizeMethod != null)
  154. assemblyPatcher.Finalizer = () => finalizeMethod.Invoke(null, null);
  155. patcherMethods.Add(assemblyPatcher);
  156. }
  157. catch (Exception ex)
  158. {
  159. Logger.LogWarning($"Could not load patcher methods from {assembly.GetName().Name}");
  160. Logger.LogWarning(ex);
  161. }
  162. Logger.Log(patcherMethods.Count > 0 ? LogLevel.Info : LogLevel.Debug,
  163. $"Loaded {patcherMethods.Count} patcher methods from {assembly.GetName().Name}");
  164. return patcherMethods;
  165. }
  166. /// <summary>
  167. /// Inserts BepInEx's own chainloader entrypoint into UnityEngine.
  168. /// </summary>
  169. /// <param name="assembly">The assembly that will be attempted to be patched.</param>
  170. public static void PatchEntrypoint(ref AssemblyDefinition assembly)
  171. {
  172. if (assembly.MainModule.AssemblyReferences.Any(x => x.Name.Contains("BepInEx")))
  173. throw new Exception("BepInEx has been detected to be patched! Please unpatch before using a patchless variant!");
  174. string entrypointType = ConfigEntrypointType.Value;
  175. string entrypointMethod = ConfigEntrypointMethod.Value;
  176. bool isCctor = entrypointMethod.IsNullOrWhiteSpace() || entrypointMethod == ".cctor";
  177. var entryType = assembly.MainModule.Types.FirstOrDefault(x => x.Name == entrypointType);
  178. if (entryType == null)
  179. throw new Exception("The entrypoint type is invalid! Please check your config.ini");
  180. using (var injected = AssemblyDefinition.ReadAssembly(Paths.BepInExAssemblyPath))
  181. {
  182. var originalInitMethod = injected.MainModule.Types.First(x => x.Name == "Chainloader").Methods
  183. .First(x => x.Name == "Initialize");
  184. var originalStartMethod = injected.MainModule.Types.First(x => x.Name == "Chainloader").Methods
  185. .First(x => x.Name == "Start");
  186. var initMethod = assembly.MainModule.ImportReference(originalInitMethod);
  187. var startMethod = assembly.MainModule.ImportReference(originalStartMethod);
  188. var methods = new List<MethodDefinition>();
  189. if (isCctor)
  190. {
  191. var cctor = entryType.Methods.FirstOrDefault(m => m.IsConstructor && m.IsStatic);
  192. if (cctor == null)
  193. {
  194. cctor = new MethodDefinition(".cctor",
  195. MethodAttributes.Static | MethodAttributes.Private | MethodAttributes.HideBySig
  196. | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName,
  197. assembly.MainModule.ImportReference(typeof(void)));
  198. entryType.Methods.Add(cctor);
  199. var il = cctor.Body.GetILProcessor();
  200. il.Append(il.Create(OpCodes.Ret));
  201. }
  202. methods.Add(cctor);
  203. }
  204. else
  205. {
  206. methods.AddRange(entryType.Methods.Where(x => x.Name == entrypointMethod));
  207. }
  208. if (!methods.Any())
  209. throw new Exception("The entrypoint method is invalid! Please check your config.ini");
  210. foreach (var method in methods)
  211. {
  212. var il = method.Body.GetILProcessor();
  213. var ins = il.Body.Instructions.First();
  214. il.InsertBefore(ins,
  215. il.Create(OpCodes.Ldstr, Paths.ExecutablePath)); //containerExePath
  216. il.InsertBefore(ins,
  217. il.Create(OpCodes.Ldc_I4_0)); //startConsole (always false, we already load the console in Preloader)
  218. il.InsertBefore(ins,
  219. il.Create(OpCodes.Call, initMethod)); //Chainloader.Initialize(string containerExePath, bool startConsole = true)
  220. il.InsertBefore(ins,
  221. il.Create(OpCodes.Call, startMethod));
  222. }
  223. }
  224. }
  225. /// <summary>
  226. /// Allocates a console window for use by BepInEx safely.
  227. /// </summary>
  228. public static void AllocateConsole()
  229. {
  230. if (!ConsoleWindow.ConfigConsoleEnabled.Value)
  231. return;
  232. try
  233. {
  234. ConsoleWindow.Attach();
  235. var encoding = (uint)Encoding.UTF8.CodePage;
  236. if (ConsoleWindow.ConfigConsoleShiftJis.Value)
  237. encoding = 932;
  238. ConsoleEncoding.ConsoleCodePage = encoding;
  239. Console.OutputEncoding = ConsoleEncoding.GetEncoding(encoding);
  240. }
  241. catch (Exception ex)
  242. {
  243. Logger.LogError("Failed to allocate console!");
  244. Logger.LogError(ex);
  245. }
  246. }
  247. #region Config
  248. private static readonly ConfigWrapper<string> ConfigEntrypointAssembly = ConfigFile.CoreConfig.Wrap(
  249. "Preloader.Entrypoint",
  250. "Assembly",
  251. "The local filename of the assembly to target.",
  252. #if UNITY_2018
  253. "UnityEngine.CoreModule.dll"
  254. #else
  255. "UnityEngine.dll"
  256. #endif
  257. );
  258. private static readonly ConfigWrapper<string> ConfigEntrypointType = ConfigFile.CoreConfig.Wrap(
  259. "Preloader.Entrypoint",
  260. "Type",
  261. "The name of the type in the entrypoint assembly to search for the entrypoint method.",
  262. "Application");
  263. private static readonly ConfigWrapper<string> ConfigEntrypointMethod = ConfigFile.CoreConfig.Wrap(
  264. "Preloader.Entrypoint",
  265. "Method",
  266. "The name of the method in the specified entrypoint assembly and type to hook and load Chainloader from.",
  267. ".cctor");
  268. private static readonly ConfigWrapper<bool> ConfigApplyRuntimePatches = ConfigFile.CoreConfig.Wrap(
  269. "Preloader",
  270. "ApplyRuntimePatches",
  271. "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.",
  272. true);
  273. private static readonly ConfigWrapper<bool> ConfigPreloaderCOutLogging = ConfigFile.CoreConfig.Wrap(
  274. "Logging",
  275. "PreloaderConsoleOutRedirection",
  276. "Redirects text from Console.Out during preloader patch loading to the BepInEx logging system.",
  277. true);
  278. #endregion
  279. }
  280. }