Preloader.cs 9.4 KB

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