Preloader.cs 14 KB

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