Preloader.cs 8.7 KB

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