Preloader.cs 9.3 KB

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