Preloader.cs 13 KB

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