Preloader.cs 9.5 KB

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