Preloader.cs 11 KB

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