Preloader.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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 CurrentExecutingAssemblyPath { get; } = Assembly.GetExecutingAssembly().CodeBase.Replace("file:///", "").Replace('/', '\\');
  42. /// <summary>
  43. /// The directory that the core BepInEx DLLs reside in.
  44. /// </summary>
  45. public static string CurrentExecutingAssemblyDirectoryPath { get; } = Path.GetDirectoryName(CurrentExecutingAssemblyPath);
  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. foreach (string assemblyPath in Directory.GetFiles(PatcherPluginPath, "*.dll"))
  156. {
  157. try
  158. {
  159. var assembly = Assembly.LoadFrom(assemblyPath);
  160. foreach (var kv in GetPatcherMethods(assembly))
  161. AddPatcher(kv.Value, kv.Key);
  162. }
  163. catch (BadImageFormatException) { } //unmanaged DLL
  164. catch (ReflectionTypeLoadException) { } //invalid references
  165. }
  166. AssemblyPatcher.PatchAll(ManagedPath, PatcherDictionary);
  167. }
  168. catch (Exception ex)
  169. {
  170. Logger.Log(LogLevel.Fatal, "Could not run preloader!");
  171. Logger.Log(LogLevel.Fatal, ex);
  172. PreloaderLog.Enabled = false;
  173. try
  174. {
  175. UnityInjector.ConsoleUtil.ConsoleWindow.Attach();
  176. Console.Write(PreloaderLog);
  177. }
  178. finally
  179. {
  180. File.WriteAllText(Path.Combine(GameRootPath, $"preloader_{DateTime.Now:yyyyMMdd_HHmmss_fff}.log"),
  181. PreloaderLog.ToString());
  182. PreloaderLog.Dispose();
  183. }
  184. }
  185. }
  186. /// <summary>
  187. /// Scans the assembly for classes that use the patcher contract, and returns a dictionary of the patch methods.
  188. /// </summary>
  189. /// <param name="assembly">The assembly to scan.</param>
  190. /// <returns>A dictionary of delegates which will be used to patch the targeted assemblies.</returns>
  191. internal static Dictionary<AssemblyPatcherDelegate, IEnumerable<string>> GetPatcherMethods(Assembly assembly)
  192. {
  193. var patcherMethods = new Dictionary<AssemblyPatcherDelegate, IEnumerable<string>>();
  194. foreach (var type in assembly.GetExportedTypes())
  195. {
  196. try
  197. {
  198. if (type.IsInterface)
  199. continue;
  200. PropertyInfo targetsProperty = type.GetProperty(
  201. "TargetDLLs",
  202. BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase,
  203. null,
  204. typeof(IEnumerable<string>),
  205. Type.EmptyTypes,
  206. null);
  207. //first try get the ref patcher method
  208. MethodInfo patcher = type.GetMethod(
  209. "Patch",
  210. BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase,
  211. null,
  212. CallingConventions.Any,
  213. new[] {typeof(AssemblyDefinition).MakeByRefType()},
  214. null);
  215. if (patcher == null) //otherwise try getting the non-ref patcher method
  216. {
  217. patcher = type.GetMethod(
  218. "Patch",
  219. BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase,
  220. null,
  221. CallingConventions.Any,
  222. new[] {typeof(AssemblyDefinition)},
  223. null);
  224. }
  225. if (targetsProperty == null || !targetsProperty.CanRead || patcher == null)
  226. continue;
  227. AssemblyPatcherDelegate patchDelegate = (ref AssemblyDefinition ass) =>
  228. {
  229. //we do the array fuckery here to get the ref result out
  230. object[] args = { ass };
  231. patcher.Invoke(null, args);
  232. ass = (AssemblyDefinition)args[0];
  233. };
  234. IEnumerable<string> targets = (IEnumerable<string>)targetsProperty.GetValue(null, null);
  235. patcherMethods[patchDelegate] = targets;
  236. MethodInfo initMethod = type.GetMethod(
  237. "Initialize",
  238. BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase,
  239. null,
  240. CallingConventions.Any,
  241. Type.EmptyTypes,
  242. null);
  243. if (initMethod != null)
  244. {
  245. Initializers.Add(() => initMethod.Invoke(null, null));
  246. }
  247. MethodInfo finalizeMethod = type.GetMethod(
  248. "Finish",
  249. BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase,
  250. null,
  251. CallingConventions.Any,
  252. Type.EmptyTypes,
  253. null);
  254. if (finalizeMethod != null)
  255. {
  256. Finalizers.Add(() => finalizeMethod.Invoke(null, null));
  257. }
  258. }
  259. catch (Exception ex)
  260. {
  261. Logger.Log(LogLevel.Warning, $"Could not load patcher methods from {assembly.GetName().Name}");
  262. Logger.Log(LogLevel.Warning, $"{ex}");
  263. }
  264. }
  265. Logger.Log(LogLevel.Info, $"Loaded {patcherMethods.Select(x => x.Key).Distinct().Count()} patcher methods from {assembly.GetName().Name}");
  266. return patcherMethods;
  267. }
  268. /// <summary>
  269. /// Inserts BepInEx's own chainloader entrypoint into UnityEngine.
  270. /// </summary>
  271. /// <param name="assembly">The assembly that will be attempted to be patched.</param>
  272. internal static void PatchEntrypoint(ref AssemblyDefinition assembly)
  273. {
  274. if (assembly.Name.Name == "UnityEngine")
  275. {
  276. #if CECIL_10
  277. using (AssemblyDefinition injected = AssemblyDefinition.ReadAssembly(CurrentExecutingAssemblyPath))
  278. #elif CECIL_9
  279. AssemblyDefinition injected = AssemblyDefinition.ReadAssembly(CurrentExecutingAssemblyPath);
  280. #endif
  281. {
  282. var originalInjectMethod = injected.MainModule.Types.First(x => x.Name == "Chainloader")
  283. .Methods.First(x => x.Name == "Initialize");
  284. var injectMethod = assembly.MainModule.ImportReference(originalInjectMethod);
  285. var sceneManager = assembly.MainModule.Types.First(x => x.Name == "Application");
  286. var voidType = assembly.MainModule.ImportReference(typeof(void));
  287. var cctor = new MethodDefinition(".cctor",
  288. MethodAttributes.Static
  289. | MethodAttributes.Private
  290. | MethodAttributes.HideBySig
  291. | MethodAttributes.SpecialName
  292. | MethodAttributes.RTSpecialName,
  293. voidType);
  294. var ilp = cctor.Body.GetILProcessor();
  295. ilp.Append(ilp.Create(OpCodes.Call, injectMethod));
  296. ilp.Append(ilp.Create(OpCodes.Ret));
  297. sceneManager.Methods.Add(cctor);
  298. }
  299. }
  300. }
  301. /// <summary>
  302. /// A handler for <see cref="AppDomain"/>.AssemblyResolve to perform some special handling.
  303. /// <para>
  304. /// 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.
  305. /// </para>
  306. /// </summary>
  307. /// <param name="sender"></param>
  308. /// <param name="args"></param>
  309. /// <returns></returns>
  310. internal static Assembly LocalResolve(object sender, ResolveEventArgs args)
  311. {
  312. AssemblyName assemblyName = new AssemblyName(args.Name);
  313. var foundAssembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(x => x.GetName().Name == assemblyName.Name);
  314. if (foundAssembly != null)
  315. return foundAssembly;
  316. if (Utility.TryResolveDllAssembly(assemblyName, CurrentExecutingAssemblyDirectoryPath, out foundAssembly) ||
  317. Utility.TryResolveDllAssembly(assemblyName, PatcherPluginPath, out foundAssembly) ||
  318. Utility.TryResolveDllAssembly(assemblyName, PluginPath, out foundAssembly))
  319. return foundAssembly;
  320. return null;
  321. }
  322. }
  323. }