Preloader.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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.Common;
  9. using BepInEx.Logging;
  10. using Mono.Cecil;
  11. using Mono.Cecil.Cil;
  12. using UnityInjector.ConsoleUtil;
  13. using MethodAttributes = Mono.Cecil.MethodAttributes;
  14. namespace BepInEx.Bootstrap
  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 list of finalizers that were loaded from the patcher contract.
  23. /// </summary>
  24. public static List<Action> Finalizers { get; } = new List<Action>();
  25. /// <summary>
  26. /// The list of initializers that were loaded from the patcher contract.
  27. /// </summary>
  28. public static List<Action> Initializers { get; } = new List<Action>();
  29. /// <summary>
  30. /// The dictionary of currently loaded patchers. The key is the patcher delegate that will be used to patch, and the
  31. /// value is a list of filenames of assemblies that the patcher is targeting.
  32. /// </summary>
  33. public static Dictionary<AssemblyPatcherDelegate, IEnumerable<string>> PatcherDictionary { get; } =
  34. new Dictionary<AssemblyPatcherDelegate, IEnumerable<string>>();
  35. /// <summary>
  36. /// The log writer that is specific to the preloader.
  37. /// </summary>
  38. public static PreloaderLogWriter PreloaderLog { get; private set; }
  39. public static void Run()
  40. {
  41. try
  42. {
  43. AllocateConsole();
  44. PreloaderLog =
  45. new PreloaderLogWriter(Utility.SafeParseBool(Config.GetEntry("preloader-logconsole", "false", "BepInEx")));
  46. PreloaderLog.Enabled = true;
  47. string consoleTile =
  48. $"BepInEx {Assembly.GetExecutingAssembly().GetName().Version} - {Process.GetCurrentProcess().ProcessName}";
  49. ConsoleWindow.Title = consoleTile;
  50. Logger.SetLogger(PreloaderLog);
  51. PreloaderLog.WriteLine(consoleTile);
  52. #if DEBUG
  53. object[] attributes = typeof(DebugInfoAttribute).Assembly.GetCustomAttributes(typeof(DebugInfoAttribute), false);
  54. if (attributes.Length > 0)
  55. {
  56. var attribute = (DebugInfoAttribute)attributes[0];
  57. PreloaderLog.WriteLine(attribute.Info);
  58. }
  59. #endif
  60. Logger.Log(LogLevel.Message, "Preloader started");
  61. string entrypointAssembly = Config.GetEntry("entrypoint-assembly", "UnityEngine.dll", "Preloader");
  62. AddPatcher(new[] {entrypointAssembly}, PatchEntrypoint);
  63. if (Directory.Exists(Paths.PatcherPluginPath))
  64. {
  65. var sortedPatchers = new SortedDictionary<string, KeyValuePair<AssemblyPatcherDelegate, IEnumerable<string>>>();
  66. foreach (string assemblyPath in Directory.GetFiles(Paths.PatcherPluginPath, "*.dll"))
  67. try
  68. {
  69. var assembly = Assembly.LoadFrom(assemblyPath);
  70. foreach (KeyValuePair<AssemblyPatcherDelegate, IEnumerable<string>> kv in GetPatcherMethods(assembly))
  71. sortedPatchers.Add(assembly.GetName().Name, kv);
  72. }
  73. catch (BadImageFormatException)
  74. {
  75. } //unmanaged DLL
  76. catch (ReflectionTypeLoadException)
  77. {
  78. } //invalid references
  79. foreach (KeyValuePair<string, KeyValuePair<AssemblyPatcherDelegate, IEnumerable<string>>> kv in sortedPatchers)
  80. AddPatcher(kv.Value.Value, kv.Value.Key);
  81. }
  82. AssemblyPatcher.PatchAll(Paths.ManagedPath, PatcherDictionary, Initializers, Finalizers);
  83. }
  84. catch (Exception ex)
  85. {
  86. Logger.Log(LogLevel.Fatal, "Could not run preloader!");
  87. Logger.Log(LogLevel.Fatal, ex);
  88. PreloaderLog.Enabled = false;
  89. try
  90. {
  91. AllocateConsole();
  92. Console.Write(PreloaderLog);
  93. }
  94. finally
  95. {
  96. File.WriteAllText(Path.Combine(Paths.GameRootPath, $"preloader_{DateTime.Now:yyyyMMdd_HHmmss_fff}.log"),
  97. PreloaderLog.ToString());
  98. PreloaderLog.Dispose();
  99. }
  100. }
  101. }
  102. /// <summary>
  103. /// Scans the assembly for classes that use the patcher contract, and returns a dictionary of the patch methods.
  104. /// </summary>
  105. /// <param name="assembly">The assembly to scan.</param>
  106. /// <returns>A dictionary of delegates which will be used to patch the targeted assemblies.</returns>
  107. public static Dictionary<AssemblyPatcherDelegate, IEnumerable<string>> GetPatcherMethods(Assembly assembly)
  108. {
  109. var patcherMethods = new Dictionary<AssemblyPatcherDelegate, IEnumerable<string>>();
  110. foreach (var type in assembly.GetExportedTypes())
  111. try
  112. {
  113. if (type.IsInterface)
  114. continue;
  115. var targetsProperty = type.GetProperty("TargetDLLs",
  116. BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase,
  117. null,
  118. typeof(IEnumerable<string>),
  119. Type.EmptyTypes,
  120. null);
  121. //first try get the ref patcher method
  122. var patcher = type.GetMethod("Patch",
  123. BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase,
  124. null,
  125. CallingConventions.Any,
  126. new[] {typeof(AssemblyDefinition).MakeByRefType()},
  127. null);
  128. if (patcher == null) //otherwise try getting the non-ref patcher method
  129. patcher = type.GetMethod("Patch",
  130. BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase,
  131. null,
  132. CallingConventions.Any,
  133. new[] {typeof(AssemblyDefinition)},
  134. null);
  135. if (targetsProperty == null || !targetsProperty.CanRead || patcher == null)
  136. continue;
  137. AssemblyPatcherDelegate patchDelegate = (ref AssemblyDefinition ass) =>
  138. {
  139. //we do the array fuckery here to get the ref result out
  140. object[] args = {ass};
  141. patcher.Invoke(null, args);
  142. ass = (AssemblyDefinition) args[0];
  143. };
  144. var targets = (IEnumerable<string>) targetsProperty.GetValue(null, null);
  145. patcherMethods[patchDelegate] = targets;
  146. var initMethod = type.GetMethod("Initialize",
  147. BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase,
  148. null,
  149. CallingConventions.Any,
  150. Type.EmptyTypes,
  151. null);
  152. if (initMethod != null)
  153. Initializers.Add(() => initMethod.Invoke(null, null));
  154. var finalizeMethod = type.GetMethod("Finish",
  155. BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase,
  156. null,
  157. CallingConventions.Any,
  158. Type.EmptyTypes,
  159. null);
  160. if (finalizeMethod != null)
  161. Finalizers.Add(() => finalizeMethod.Invoke(null, null));
  162. }
  163. catch (Exception ex)
  164. {
  165. Logger.Log(LogLevel.Warning, $"Could not load patcher methods from {assembly.GetName().Name}");
  166. Logger.Log(LogLevel.Warning, $"{ex}");
  167. }
  168. Logger.Log(LogLevel.Info,
  169. $"Loaded {patcherMethods.Select(x => x.Key).Distinct().Count()} patcher methods from {assembly.GetName().Name}");
  170. return patcherMethods;
  171. }
  172. /// <summary>
  173. /// Inserts BepInEx's own chainloader entrypoint into UnityEngine.
  174. /// </summary>
  175. /// <param name="assembly">The assembly that will be attempted to be patched.</param>
  176. public static void PatchEntrypoint(ref AssemblyDefinition assembly)
  177. {
  178. string entrypointType = Config.GetEntry("entrypoint-type", "Application", "Preloader");
  179. string entrypointMethod = Config.HasEntry("entrypoint-method")
  180. ? Config.GetEntry("entrypoint-method", section: "Preloader")
  181. : "";
  182. bool isCctor = entrypointMethod.IsNullOrWhiteSpace() || entrypointMethod == ".cctor";
  183. using (var injected = AssemblyDefinition.ReadAssembly(Paths.BepInExAssemblyPath))
  184. {
  185. var originalInjectMethod = injected.MainModule.Types.First(x => x.Name == "Chainloader").Methods
  186. .First(x => x.Name == "Initialize");
  187. var injectMethod = assembly.MainModule.ImportReference(originalInjectMethod);
  188. var entryType = assembly.MainModule.Types.First(x => x.Name == entrypointType);
  189. if (isCctor)
  190. {
  191. MethodDefinition cctor = entryType.Methods.FirstOrDefault(m => m.IsConstructor && m.IsStatic);
  192. ILProcessor il;
  193. if (cctor == null)
  194. {
  195. cctor = new MethodDefinition(".cctor",
  196. MethodAttributes.Static | MethodAttributes.Private | MethodAttributes.HideBySig
  197. | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName,
  198. assembly.MainModule.ImportReference(typeof(void)));
  199. entryType.Methods.Add(cctor);
  200. il = cctor.Body.GetILProcessor();
  201. il.Append(il.Create(OpCodes.Ret));
  202. }
  203. Instruction ins = cctor.Body.Instructions.First();
  204. il = cctor.Body.GetILProcessor();
  205. il.InsertBefore(ins, il.Create(OpCodes.Call, injectMethod));
  206. }
  207. else
  208. {
  209. foreach (var method in entryType.Methods.Where(x => x.Name == entrypointMethod))
  210. {
  211. var il = method.Body.GetILProcessor();
  212. il.InsertBefore(method.Body.Instructions[0], il.Create(OpCodes.Call, injectMethod));
  213. }
  214. }
  215. }
  216. }
  217. /// <summary>
  218. /// Allocates a console window for use by BepInEx safely.
  219. /// </summary>
  220. public static void AllocateConsole()
  221. {
  222. bool console = Utility.SafeParseBool(Config.GetEntry("console", "false", "BepInEx"));
  223. bool shiftjis = Utility.SafeParseBool(Config.GetEntry("console-shiftjis", "false", "BepInEx"));
  224. if (console)
  225. try
  226. {
  227. ConsoleWindow.Attach();
  228. var encoding = (uint) Encoding.UTF8.CodePage;
  229. if (shiftjis)
  230. encoding = 932;
  231. ConsoleEncoding.ConsoleCodePage = encoding;
  232. Console.OutputEncoding = ConsoleEncoding.GetEncoding(encoding);
  233. }
  234. catch (Exception ex)
  235. {
  236. Logger.Log(LogLevel.Error, "Failed to allocate console!");
  237. Logger.Log(LogLevel.Error, ex);
  238. }
  239. }
  240. /// <summary>
  241. /// Adds the patcher to the patcher dictionary.
  242. /// </summary>
  243. /// <param name="dllNames">The list of DLL filenames to be patched.</param>
  244. /// <param name="patcher">The method that will perform the patching.</param>
  245. public static void AddPatcher(IEnumerable<string> dllNames, AssemblyPatcherDelegate patcher)
  246. {
  247. PatcherDictionary[patcher] = dllNames;
  248. }
  249. }
  250. }