Preloader.cs 11 KB

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