Preloader.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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. public static class Preloader
  20. {
  21. #region Path Properties
  22. private static string executablePath;
  23. /// <summary>
  24. /// The path of the currently executing program BepInEx is encapsulated in.
  25. /// </summary>
  26. public static string ExecutablePath
  27. {
  28. get => executablePath;
  29. set
  30. {
  31. executablePath = value;
  32. GameRootPath = Path.GetDirectoryName(executablePath);
  33. ManagedPath = Utility.CombinePaths(GameRootPath, $"{ProcessName}_Data", "Managed");
  34. PluginPath = Utility.CombinePaths(GameRootPath, "BepInEx");
  35. PatcherPluginPath = Utility.CombinePaths(GameRootPath, "BepInEx", "patchers");
  36. }
  37. }
  38. /// <summary>
  39. /// The path to the core BepInEx DLL.
  40. /// </summary>
  41. public static string BepInExAssemblyPath { get; } = typeof(Preloader).Assembly.CodeBase.Replace("file:///", "").Replace('/', '\\');
  42. /// <summary>
  43. /// The directory that the core BepInEx DLLs reside in.
  44. /// </summary>
  45. public static string BepInExAssemblyDirectory { get; } = Path.GetDirectoryName(BepInExAssemblyPath);
  46. /// <summary>
  47. /// The name of the currently executing process.
  48. /// </summary>
  49. public static string ProcessName { get; } = Path.GetFileNameWithoutExtension(Process.GetCurrentProcess().ProcessName);
  50. /// <summary>
  51. /// The directory that the currently executing process resides in.
  52. /// </summary>
  53. public static string GameRootPath { get; private set; }
  54. /// <summary>
  55. /// The path to the Managed folder of the currently running Unity game.
  56. /// </summary>
  57. public static string ManagedPath { get; private set; }
  58. /// <summary>
  59. /// The path to the main BepInEx folder.
  60. /// </summary>
  61. public static string PluginPath { get; private set; }
  62. /// <summary>
  63. /// The path to the patcher plugin folder which resides in the BepInEx folder.
  64. /// </summary>
  65. public static string PatcherPluginPath { get; private set; }
  66. #endregion
  67. /// <summary>
  68. /// The log writer that is specific to the preloader.
  69. /// </summary>
  70. public static PreloaderLogWriter PreloaderLog { get; private set; }
  71. /// <summary>
  72. /// The dictionary of currently loaded patchers. The key is the patcher delegate that will be used to patch, and the value is a list of filenames of assemblies that the patcher is targeting.
  73. /// </summary>
  74. public static Dictionary<AssemblyPatcherDelegate, IEnumerable<string>> PatcherDictionary { get; } = new Dictionary<AssemblyPatcherDelegate, IEnumerable<string>>();
  75. /// <summary>
  76. /// The list of initializers that were loaded from the patcher contract.
  77. /// </summary>
  78. public static List<Action> Initializers { get; } = new List<Action>();
  79. /// <summary>
  80. /// The list of finalizers that were loaded from the patcher contract.
  81. /// </summary>
  82. public static List<Action> Finalizers { get; } = new List<Action>();
  83. /// <summary>
  84. /// Adds the patcher to the patcher dictionary.
  85. /// </summary>
  86. /// <param name="dllNames">The list of DLL filenames to be patched.</param>
  87. /// <param name="patcher">The method that will perform the patching.</param>
  88. public static void AddPatcher(IEnumerable<string> dllNames, AssemblyPatcherDelegate patcher)
  89. {
  90. PatcherDictionary[patcher] = dllNames;
  91. }
  92. /// <summary>
  93. /// Safely retrieves a boolean value from the config. Returns false if not able to retrieve safely.
  94. /// </summary>
  95. /// <param name="key">The key to retrieve from the config.</param>
  96. /// <param name="defaultValue">The default value to both return and set if the key does not exist in the config.</param>
  97. /// <returns>The value of the key if found in the config, or the default value specified if not found, or false if it was unable to safely retrieve the value from the config.</returns>
  98. private static bool SafeGetConfigBool(string key, string defaultValue)
  99. {
  100. try
  101. {
  102. string result = Config.GetEntry(key, defaultValue);
  103. return bool.Parse(result);
  104. }
  105. catch
  106. {
  107. return false;
  108. }
  109. }
  110. /// <summary>
  111. /// Allocates a console window for use by BepInEx safely.
  112. /// </summary>
  113. internal static void AllocateConsole()
  114. {
  115. bool console = SafeGetConfigBool("console", "false");
  116. bool shiftjis = SafeGetConfigBool("console-shiftjis", "false");
  117. if (console)
  118. {
  119. try
  120. {
  121. ConsoleWindow.Attach();
  122. uint encoding = (uint) Encoding.UTF8.CodePage;
  123. if (shiftjis)
  124. encoding = 932;
  125. ConsoleEncoding.ConsoleCodePage = encoding;
  126. Console.OutputEncoding = ConsoleEncoding.GetEncoding(encoding);
  127. }
  128. catch (Exception ex)
  129. {
  130. Logger.Log(LogLevel.Error, "Failed to allocate console!");
  131. Logger.Log(LogLevel.Error, ex);
  132. }
  133. }
  134. }
  135. /// <summary>
  136. /// The main entrypoint of BepInEx, called from Doorstop.
  137. /// </summary>
  138. /// <param name="args">The arguments passed in from Doorstop. First argument is the path of the currently executing process.</param>
  139. public static void Main(string[] args)
  140. {
  141. try
  142. {
  143. AppDomain.CurrentDomain.AssemblyResolve += LocalResolve;
  144. ExecutablePath = args[0];
  145. AllocateConsole();
  146. PreloaderLog = new PreloaderLogWriter(SafeGetConfigBool("preloader-logconsole", "false"));
  147. PreloaderLog.Enabled = true;
  148. string consoleTile = $"BepInEx {Assembly.GetExecutingAssembly().GetName().Version} - {Process.GetCurrentProcess().ProcessName}";
  149. ConsoleWindow.Title = consoleTile;
  150. Logger.SetLogger(PreloaderLog);
  151. PreloaderLog.WriteLine(consoleTile);
  152. Logger.Log(LogLevel.Message, "Preloader started");
  153. AddPatcher(new [] { "UnityEngine.dll" }, PatchEntrypoint);
  154. if (Directory.Exists(PatcherPluginPath))
  155. {
  156. SortedDictionary<string, KeyValuePair<AssemblyPatcherDelegate, IEnumerable<string>>> sortedPatchers = new SortedDictionary<string, KeyValuePair<AssemblyPatcherDelegate, IEnumerable<string>>>();
  157. foreach (string assemblyPath in Directory.GetFiles(PatcherPluginPath, "*.dll"))
  158. {
  159. try
  160. {
  161. var assembly = Assembly.LoadFrom(assemblyPath);
  162. foreach (var kv in GetPatcherMethods(assembly))
  163. sortedPatchers.Add(assembly.GetName().Name, kv);
  164. }
  165. catch (BadImageFormatException) { } //unmanaged DLL
  166. catch (ReflectionTypeLoadException) { } //invalid references
  167. }
  168. foreach (var kv in sortedPatchers)
  169. AddPatcher(kv.Value.Value, kv.Value.Key);
  170. }
  171. AssemblyPatcher.PatchAll(ManagedPath, PatcherDictionary, Initializers, Finalizers);
  172. }
  173. catch (Exception ex)
  174. {
  175. Logger.Log(LogLevel.Fatal, "Could not run preloader!");
  176. Logger.Log(LogLevel.Fatal, ex);
  177. PreloaderLog.Enabled = false;
  178. try
  179. {
  180. UnityInjector.ConsoleUtil.ConsoleWindow.Attach();
  181. Console.Write(PreloaderLog);
  182. }
  183. finally
  184. {
  185. File.WriteAllText(Path.Combine(GameRootPath, $"preloader_{DateTime.Now:yyyyMMdd_HHmmss_fff}.log"),
  186. PreloaderLog.ToString());
  187. PreloaderLog.Dispose();
  188. }
  189. }
  190. }
  191. /// <summary>
  192. /// Scans the assembly for classes that use the patcher contract, and returns a dictionary of the patch methods.
  193. /// </summary>
  194. /// <param name="assembly">The assembly to scan.</param>
  195. /// <returns>A dictionary of delegates which will be used to patch the targeted assemblies.</returns>
  196. internal static Dictionary<AssemblyPatcherDelegate, IEnumerable<string>> GetPatcherMethods(Assembly assembly)
  197. {
  198. var patcherMethods = new Dictionary<AssemblyPatcherDelegate, IEnumerable<string>>();
  199. foreach (var type in assembly.GetExportedTypes())
  200. {
  201. try
  202. {
  203. if (type.IsInterface)
  204. continue;
  205. PropertyInfo targetsProperty = type.GetProperty(
  206. "TargetDLLs",
  207. BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase,
  208. null,
  209. typeof(IEnumerable<string>),
  210. Type.EmptyTypes,
  211. null);
  212. //first try get the ref patcher method
  213. MethodInfo patcher = type.GetMethod(
  214. "Patch",
  215. BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase,
  216. null,
  217. CallingConventions.Any,
  218. new[] {typeof(AssemblyDefinition).MakeByRefType()},
  219. null);
  220. if (patcher == null) //otherwise try getting the non-ref patcher method
  221. {
  222. patcher = type.GetMethod(
  223. "Patch",
  224. BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase,
  225. null,
  226. CallingConventions.Any,
  227. new[] {typeof(AssemblyDefinition)},
  228. null);
  229. }
  230. if (targetsProperty == null || !targetsProperty.CanRead || patcher == null)
  231. continue;
  232. AssemblyPatcherDelegate patchDelegate = (ref AssemblyDefinition ass) =>
  233. {
  234. //we do the array fuckery here to get the ref result out
  235. object[] args = { ass };
  236. patcher.Invoke(null, args);
  237. ass = (AssemblyDefinition)args[0];
  238. };
  239. IEnumerable<string> targets = (IEnumerable<string>)targetsProperty.GetValue(null, null);
  240. patcherMethods[patchDelegate] = targets;
  241. MethodInfo initMethod = type.GetMethod(
  242. "Initialize",
  243. BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase,
  244. null,
  245. CallingConventions.Any,
  246. Type.EmptyTypes,
  247. null);
  248. if (initMethod != null)
  249. {
  250. Initializers.Add(() => initMethod.Invoke(null, null));
  251. }
  252. MethodInfo finalizeMethod = type.GetMethod(
  253. "Finish",
  254. BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase,
  255. null,
  256. CallingConventions.Any,
  257. Type.EmptyTypes,
  258. null);
  259. if (finalizeMethod != null)
  260. {
  261. Finalizers.Add(() => finalizeMethod.Invoke(null, null));
  262. }
  263. }
  264. catch (Exception ex)
  265. {
  266. Logger.Log(LogLevel.Warning, $"Could not load patcher methods from {assembly.GetName().Name}");
  267. Logger.Log(LogLevel.Warning, $"{ex}");
  268. }
  269. }
  270. Logger.Log(LogLevel.Info, $"Loaded {patcherMethods.Select(x => x.Key).Distinct().Count()} patcher methods from {assembly.GetName().Name}");
  271. return patcherMethods;
  272. }
  273. /// <summary>
  274. /// Inserts BepInEx's own chainloader entrypoint into UnityEngine.
  275. /// </summary>
  276. /// <param name="assembly">The assembly that will be attempted to be patched.</param>
  277. internal static void PatchEntrypoint(ref AssemblyDefinition assembly)
  278. {
  279. if (assembly.Name.Name == "UnityEngine")
  280. {
  281. #if CECIL_10
  282. using (AssemblyDefinition injected = AssemblyDefinition.ReadAssembly(BepInExAssemblyPath))
  283. #elif CECIL_9
  284. AssemblyDefinition injected = AssemblyDefinition.ReadAssembly(BepInExAssemblyPath);
  285. #endif
  286. {
  287. var originalInjectMethod = injected.MainModule.Types.First(x => x.Name == "Chainloader")
  288. .Methods.First(x => x.Name == "Initialize");
  289. var injectMethod = assembly.MainModule.ImportReference(originalInjectMethod);
  290. var sceneManager = assembly.MainModule.Types.First(x => x.Name == "Application");
  291. var voidType = assembly.MainModule.ImportReference(typeof(void));
  292. var cctor = new MethodDefinition(".cctor",
  293. MethodAttributes.Static
  294. | MethodAttributes.Private
  295. | MethodAttributes.HideBySig
  296. | MethodAttributes.SpecialName
  297. | MethodAttributes.RTSpecialName,
  298. voidType);
  299. var ilp = cctor.Body.GetILProcessor();
  300. ilp.Append(ilp.Create(OpCodes.Call, injectMethod));
  301. ilp.Append(ilp.Create(OpCodes.Ret));
  302. sceneManager.Methods.Add(cctor);
  303. }
  304. }
  305. }
  306. /// <summary>
  307. /// A handler for <see cref="AppDomain"/>.AssemblyResolve to perform some special handling.
  308. /// <para>
  309. /// It attempts to check currently loaded assemblies (ignoring the version), and then checks the BepInEx/core path, BepInEx/patchers path and the BepInEx folder, all in that order.
  310. /// </para>
  311. /// </summary>
  312. /// <param name="sender"></param>
  313. /// <param name="args"></param>
  314. /// <returns></returns>
  315. internal static Assembly LocalResolve(object sender, ResolveEventArgs args)
  316. {
  317. AssemblyName assemblyName = new AssemblyName(args.Name);
  318. var foundAssembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(x => x.GetName().Name == assemblyName.Name);
  319. if (foundAssembly != null)
  320. return foundAssembly;
  321. if (Utility.TryResolveDllAssembly(assemblyName, BepInExAssemblyDirectory, out foundAssembly) ||
  322. Utility.TryResolveDllAssembly(assemblyName, PatcherPluginPath, out foundAssembly) ||
  323. Utility.TryResolveDllAssembly(assemblyName, PluginPath, out foundAssembly))
  324. return foundAssembly;
  325. return null;
  326. }
  327. }
  328. }