Preloader.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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. UnityPatches.Apply();
  44. PreloaderLog =
  45. new PreloaderLogWriter(Utility.SafeParseBool(Config.GetEntry("preloader-logconsole", "false", "BepInEx")));
  46. PreloaderLog.Enabled = true;
  47. string consoleTile =
  48. $"BepInEx {Assembly.GetExecutingAssembly().GetName().Version} - {Process.GetCurrentProcess().ProcessName}";
  49. ConsoleWindow.Title = consoleTile;
  50. Logger.SetLogger(PreloaderLog);
  51. PreloaderLog.WriteLine(consoleTile);
  52. #if DEBUG
  53. object[] attributes = typeof(DebugInfoAttribute).Assembly.GetCustomAttributes(typeof(DebugInfoAttribute), false);
  54. if (attributes.Length > 0)
  55. {
  56. var attribute = (DebugInfoAttribute)attributes[0];
  57. PreloaderLog.WriteLine(attribute.Info);
  58. }
  59. #endif
  60. Logger.Log(LogLevel.Message, "Preloader started");
  61. string entrypointAssembly = Config.GetEntry("entrypoint-assembly", "UnityEngine.dll", "Preloader");
  62. AddPatcher(new[] {entrypointAssembly}, PatchEntrypoint);
  63. if (Directory.Exists(Paths.PatcherPluginPath))
  64. {
  65. var sortedPatchers = new SortedDictionary<string, KeyValuePair<AssemblyPatcherDelegate, IEnumerable<string>>>();
  66. foreach (string assemblyPath in Directory.GetFiles(Paths.PatcherPluginPath, "*.dll"))
  67. try
  68. {
  69. var assembly = Assembly.LoadFrom(assemblyPath);
  70. foreach (KeyValuePair<string, KeyValuePair<AssemblyPatcherDelegate, IEnumerable<string>>> kv in GetPatcherMethods(assembly))
  71. try
  72. {
  73. sortedPatchers.Add(kv.Key, kv.Value);
  74. }
  75. catch (ArgumentException)
  76. {
  77. Logger.Log(LogLevel.Warning, $"Found duplicate of patcher {kv.Key}!");
  78. }
  79. }
  80. catch (BadImageFormatException) { } //unmanaged DLL
  81. catch (ReflectionTypeLoadException) { } //invalid references
  82. foreach (KeyValuePair<string, KeyValuePair<AssemblyPatcherDelegate, IEnumerable<string>>> kv in sortedPatchers)
  83. AddPatcher(kv.Value.Value, kv.Value.Key);
  84. }
  85. AssemblyPatcherLoader.PatchAll(Paths.ManagedPath, PatcherDictionary, Initializers, Finalizers);
  86. }
  87. catch (Exception ex)
  88. {
  89. Logger.Log(LogLevel.Fatal, "Could not run preloader!");
  90. Logger.Log(LogLevel.Fatal, ex);
  91. PreloaderLog.Enabled = false;
  92. try
  93. {
  94. if (!ConsoleWindow.IsAttatched)
  95. {
  96. //if we've already attached the console, then the log will already be written to the console
  97. AllocateConsole();
  98. Console.Write(PreloaderLog);
  99. }
  100. }
  101. finally
  102. {
  103. File.WriteAllText(Path.Combine(Paths.GameRootPath, $"preloader_{DateTime.Now:yyyyMMdd_HHmmss_fff}.log"),
  104. PreloaderLog.ToString());
  105. PreloaderLog.Dispose();
  106. }
  107. }
  108. }
  109. /// <summary>
  110. /// Scans the assembly for classes that use the patcher contract, and returns a dictionary of the patch methods.
  111. /// </summary>
  112. /// <param name="assembly">The assembly to scan.</param>
  113. /// <returns>A dictionary of delegates which will be used to patch the targeted assemblies.</returns>
  114. public static Dictionary<string, KeyValuePair<AssemblyPatcherDelegate, IEnumerable<string>>> GetPatcherMethods(Assembly assembly)
  115. {
  116. var patcherMethods = new Dictionary<string, KeyValuePair<AssemblyPatcherDelegate, IEnumerable<string>>>();
  117. foreach (var type in assembly.GetExportedTypes())
  118. try
  119. {
  120. if (type.IsInterface)
  121. continue;
  122. var targetsProperty = type.GetProperty("TargetDLLs",
  123. BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase,
  124. null,
  125. typeof(IEnumerable<string>),
  126. Type.EmptyTypes,
  127. null);
  128. //first try get the ref patcher method
  129. var patcher = type.GetMethod("Patch",
  130. BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase,
  131. null,
  132. CallingConventions.Any,
  133. new[] {typeof(AssemblyDefinition).MakeByRefType()},
  134. null);
  135. if (patcher == null) //otherwise try getting the non-ref patcher method
  136. patcher = type.GetMethod("Patch",
  137. BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase,
  138. null,
  139. CallingConventions.Any,
  140. new[] {typeof(AssemblyDefinition)},
  141. null);
  142. if (targetsProperty == null || !targetsProperty.CanRead || patcher == null)
  143. continue;
  144. AssemblyPatcherDelegate patchDelegate = (ref AssemblyDefinition ass) =>
  145. {
  146. //we do the array fuckery here to get the ref result out
  147. object[] args = {ass};
  148. patcher.Invoke(null, args);
  149. ass = (AssemblyDefinition) args[0];
  150. };
  151. var targets = (IEnumerable<string>) targetsProperty.GetValue(null, null);
  152. patcherMethods[$"{assembly.GetName().Name}{type.FullName}"] = new KeyValuePair<AssemblyPatcherDelegate, IEnumerable<string>>(patchDelegate, targets);
  153. var initMethod = type.GetMethod("Initialize",
  154. BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase,
  155. null,
  156. CallingConventions.Any,
  157. Type.EmptyTypes,
  158. null);
  159. if (initMethod != null)
  160. Initializers.Add(() => initMethod.Invoke(null, null));
  161. var finalizeMethod = type.GetMethod("Finish",
  162. BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase,
  163. null,
  164. CallingConventions.Any,
  165. Type.EmptyTypes,
  166. null);
  167. if (finalizeMethod != null)
  168. Finalizers.Add(() => finalizeMethod.Invoke(null, null));
  169. }
  170. catch (Exception ex)
  171. {
  172. Logger.Log(LogLevel.Warning, $"Could not load patcher methods from {assembly.GetName().Name}");
  173. Logger.Log(LogLevel.Warning, $"{ex}");
  174. }
  175. Logger.Log(LogLevel.Info,
  176. $"Loaded {patcherMethods.Select(x => x.Key).Distinct().Count()} patcher methods from {assembly.GetName().Name}");
  177. return patcherMethods;
  178. }
  179. /// <summary>
  180. /// Inserts BepInEx's own chainloader entrypoint into UnityEngine.
  181. /// </summary>
  182. /// <param name="assembly">The assembly that will be attempted to be patched.</param>
  183. public static void PatchEntrypoint(ref AssemblyDefinition assembly)
  184. {
  185. if (assembly.MainModule.AssemblyReferences.Any(x => x.Name.Contains("BepInEx")))
  186. {
  187. throw new Exception("BepInEx has been detected to be patched! Please unpatch before using a patchless variant!");
  188. }
  189. string entrypointType = Config.GetEntry("entrypoint-type", "Application", "Preloader");
  190. string entrypointMethod = Config.GetEntry("entrypoint-method", ".cctor", "Preloader");
  191. bool isCctor = entrypointMethod.IsNullOrWhiteSpace() || entrypointMethod == ".cctor";
  192. var entryType = assembly.MainModule.Types.FirstOrDefault(x => x.Name == entrypointType);
  193. if (entryType == null)
  194. {
  195. throw new Exception("The entrypoint type is invalid! Please check your config.ini");
  196. }
  197. using (var injected = AssemblyDefinition.ReadAssembly(Paths.BepInExAssemblyPath))
  198. {
  199. var originalInitMethod = injected.MainModule.Types.First(x => x.Name == "Chainloader").Methods
  200. .First(x => x.Name == "Initialize");
  201. var originalStartMethod = injected.MainModule.Types.First(x => x.Name == "Chainloader").Methods
  202. .First(x => x.Name == "Start");
  203. var initMethod = assembly.MainModule.ImportReference(originalInitMethod);
  204. var startMethod = assembly.MainModule.ImportReference(originalStartMethod);
  205. List<MethodDefinition> methods = new List<MethodDefinition>();
  206. if (isCctor)
  207. {
  208. MethodDefinition cctor = entryType.Methods.FirstOrDefault(m => m.IsConstructor && m.IsStatic);
  209. if (cctor == null)
  210. {
  211. cctor = new MethodDefinition(".cctor",
  212. MethodAttributes.Static | MethodAttributes.Private | MethodAttributes.HideBySig
  213. | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName,
  214. assembly.MainModule.ImportReference(typeof(void)));
  215. entryType.Methods.Add(cctor);
  216. ILProcessor il = cctor.Body.GetILProcessor();
  217. il.Append(il.Create(OpCodes.Ret));
  218. }
  219. methods.Add(cctor);
  220. }
  221. else
  222. {
  223. methods.AddRange(entryType.Methods.Where(x => x.Name == entrypointMethod));
  224. }
  225. if (!methods.Any())
  226. {
  227. throw new Exception("The entrypoint method is invalid! Please check your config.ini");
  228. }
  229. foreach (var method in methods)
  230. {
  231. var il = method.Body.GetILProcessor();
  232. Instruction ins = il.Body.Instructions.First();
  233. il.InsertBefore(ins, il.Create(OpCodes.Ldstr, Paths.ExecutablePath)); //containerExePath
  234. il.InsertBefore(ins, il.Create(OpCodes.Ldc_I4_0)); //startConsole (always false, we already load the console in Preloader)
  235. il.InsertBefore(ins, il.Create(OpCodes.Call, initMethod)); //Chainloader.Initialize(string containerExePath, bool startConsole = true)
  236. il.InsertBefore(ins, il.Create(OpCodes.Call, startMethod));
  237. }
  238. }
  239. }
  240. /// <summary>
  241. /// Allocates a console window for use by BepInEx safely.
  242. /// </summary>
  243. public static void AllocateConsole()
  244. {
  245. bool console = Utility.SafeParseBool(Config.GetEntry("console", "false", "BepInEx"));
  246. bool shiftjis = Utility.SafeParseBool(Config.GetEntry("console-shiftjis", "false", "BepInEx"));
  247. if (!console)
  248. return;
  249. try
  250. {
  251. ConsoleWindow.Attach();
  252. var encoding = (uint) Encoding.UTF8.CodePage;
  253. if (shiftjis)
  254. encoding = 932;
  255. ConsoleEncoding.ConsoleCodePage = encoding;
  256. Console.OutputEncoding = ConsoleEncoding.GetEncoding(encoding);
  257. }
  258. catch (Exception ex)
  259. {
  260. Logger.Log(LogLevel.Error, "Failed to allocate console!");
  261. Logger.Log(LogLevel.Error, ex);
  262. }
  263. }
  264. /// <summary>
  265. /// Adds the patcher to the patcher dictionary.
  266. /// </summary>
  267. /// <param name="dllNames">The list of DLL filenames to be patched.</param>
  268. /// <param name="patcher">The method that will perform the patching.</param>
  269. public static void AddPatcher(IEnumerable<string> dllNames, AssemblyPatcherDelegate patcher)
  270. {
  271. PatcherDictionary[patcher] = dllNames;
  272. }
  273. }
  274. }