Preloader.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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 BepInEx.Preloader.Patcher;
  10. using Mono.Cecil;
  11. using Mono.Cecil.Cil;
  12. using UnityInjector.ConsoleUtil;
  13. using MethodAttributes = Mono.Cecil.MethodAttributes;
  14. namespace BepInEx.Preloader
  15. {
  16. /// <summary>
  17. /// The main entrypoint of BepInEx, and initializes all patchers and the chainloader.
  18. /// </summary>
  19. internal static class Preloader
  20. {
  21. /// <summary>
  22. /// The log writer that is specific to the preloader.
  23. /// </summary>
  24. private static PreloaderLogWriter PreloaderLog { get; set; }
  25. public static void Run()
  26. {
  27. try
  28. {
  29. AllocateConsole();
  30. UnityPatches.Apply();
  31. PreloaderLog =
  32. new PreloaderLogWriter(
  33. Utility.SafeParseBool(Config.GetEntry("preloader-logconsole", "false", "BepInEx")));
  34. PreloaderLog.Enabled = true;
  35. string consoleTile =
  36. $"BepInEx {typeof(Paths).Assembly.GetName().Version} - {Process.GetCurrentProcess().ProcessName}";
  37. ConsoleWindow.Title = consoleTile;
  38. Logger.SetLogger(PreloaderLog);
  39. PreloaderLog.WriteLine(consoleTile);
  40. #if DEBUG
  41. object[] attributes =
  42. typeof(DebugInfoAttribute).Assembly.GetCustomAttributes(typeof(DebugInfoAttribute), false);
  43. if (attributes.Length > 0)
  44. {
  45. var attribute = (DebugInfoAttribute) attributes[0];
  46. PreloaderLog.WriteLine(attribute.Info);
  47. }
  48. #endif
  49. Logger.Log(LogLevel.Message, "Preloader started");
  50. string entrypointAssembly = Config.GetEntry("entrypoint-assembly", "UnityEngine.dll", "Preloader");
  51. AssemblyPatcher.AddPatcher(new PatcherPlugin
  52. {TargetDLLs = new[] {entrypointAssembly}, Patcher = PatchEntrypoint});
  53. AssemblyPatcher.AddPatchersFromDirectory(Paths.PatcherPluginPath, GetPatcherMethods);
  54. AssemblyPatcher.PatchAndLoad(Paths.ManagedPath);
  55. AssemblyPatcher.DisposePatchers();
  56. }
  57. catch (Exception ex)
  58. {
  59. Logger.Log(LogLevel.Fatal, "Could not run preloader!");
  60. Logger.Log(LogLevel.Fatal, ex);
  61. PreloaderLog.Enabled = false;
  62. try
  63. {
  64. if (!ConsoleWindow.IsAttatched)
  65. {
  66. //if we've already attached the console, then the log will already be written to the console
  67. AllocateConsole();
  68. Console.Write(PreloaderLog);
  69. }
  70. }
  71. finally
  72. {
  73. File.WriteAllText(
  74. Path.Combine(Paths.GameRootPath, $"preloader_{DateTime.Now:yyyyMMdd_HHmmss_fff}.log"),
  75. PreloaderLog.ToString());
  76. PreloaderLog.Dispose();
  77. PreloaderLog = null;
  78. }
  79. }
  80. }
  81. /// <summary>
  82. /// Scans the assembly for classes that use the patcher contract, and returns a list of valid patchers.
  83. /// </summary>
  84. /// <param name="assembly">The assembly to scan.</param>
  85. /// <returns>A list of assembly patchers that were found in the assembly.</returns>
  86. public static List<PatcherPlugin> GetPatcherMethods(Assembly assembly)
  87. {
  88. var patcherMethods = new List<PatcherPlugin>();
  89. var flags = BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase;
  90. foreach (var type in assembly.GetExportedTypes())
  91. try
  92. {
  93. if (type.IsInterface)
  94. continue;
  95. var targetsProperty = type.GetProperty("TargetDLLs",
  96. flags,
  97. null,
  98. typeof(IEnumerable<string>),
  99. Type.EmptyTypes,
  100. null);
  101. //first try get the ref patcher method
  102. var patcher = type.GetMethod("Patch",
  103. flags,
  104. null,
  105. CallingConventions.Any,
  106. new[] {typeof(AssemblyDefinition).MakeByRefType()},
  107. null);
  108. if (patcher == null) //otherwise try getting the non-ref patcher method
  109. patcher = type.GetMethod("Patch",
  110. flags,
  111. null,
  112. CallingConventions.Any,
  113. new[] {typeof(AssemblyDefinition)},
  114. null);
  115. if (targetsProperty == null || !targetsProperty.CanRead || patcher == null)
  116. continue;
  117. var assemblyPatcher = new PatcherPlugin();
  118. assemblyPatcher.Name = $"{assembly.GetName().Name}{type.FullName}";
  119. assemblyPatcher.Patcher = (ref AssemblyDefinition ass) =>
  120. {
  121. //we do the array fuckery here to get the ref result out
  122. object[] args = {ass};
  123. patcher.Invoke(null, args);
  124. ass = (AssemblyDefinition) args[0];
  125. };
  126. assemblyPatcher.TargetDLLs = (IEnumerable<string>) targetsProperty.GetValue(null, null);
  127. var initMethod = type.GetMethod("Initialize",
  128. flags,
  129. null,
  130. CallingConventions.Any,
  131. Type.EmptyTypes,
  132. null);
  133. if (initMethod != null)
  134. assemblyPatcher.Initializer = () => initMethod.Invoke(null, null);
  135. var finalizeMethod = type.GetMethod("Finish",
  136. flags,
  137. null,
  138. CallingConventions.Any,
  139. Type.EmptyTypes,
  140. null);
  141. if (finalizeMethod != null)
  142. assemblyPatcher.Finalizer = () => finalizeMethod.Invoke(null, null);
  143. }
  144. catch (Exception ex)
  145. {
  146. Logger.Log(LogLevel.Warning, $"Could not load patcher methods from {assembly.GetName().Name}");
  147. Logger.Log(LogLevel.Warning, $"{ex}");
  148. }
  149. Logger.Log(LogLevel.Info,
  150. $"Loaded {patcherMethods.Count} patcher methods from {assembly.GetName().Name}");
  151. return patcherMethods;
  152. }
  153. /// <summary>
  154. /// Inserts BepInEx's own chainloader entrypoint into UnityEngine.
  155. /// </summary>
  156. /// <param name="assembly">The assembly that will be attempted to be patched.</param>
  157. public static void PatchEntrypoint(ref AssemblyDefinition assembly)
  158. {
  159. if (assembly.MainModule.AssemblyReferences.Any(x => x.Name.Contains("BepInEx")))
  160. throw new Exception(
  161. "BepInEx has been detected to be patched! Please unpatch before using a patchless variant!");
  162. string entrypointType = Config.GetEntry("entrypoint-type", "Application", "Preloader");
  163. string entrypointMethod = Config.GetEntry("entrypoint-method", ".cctor", "Preloader");
  164. bool isCctor = entrypointMethod.IsNullOrWhiteSpace() || entrypointMethod == ".cctor";
  165. var entryType = assembly.MainModule.Types.FirstOrDefault(x => x.Name == entrypointType);
  166. if (entryType == null) throw new Exception("The entrypoint type is invalid! Please check your config.ini");
  167. using (var injected = AssemblyDefinition.ReadAssembly(Paths.BepInExAssemblyPath))
  168. {
  169. var originalInitMethod = injected.MainModule.Types.First(x => x.Name == "Chainloader").Methods
  170. .First(x => x.Name == "Initialize");
  171. var originalStartMethod = injected.MainModule.Types.First(x => x.Name == "Chainloader").Methods
  172. .First(x => x.Name == "Start");
  173. var initMethod = assembly.MainModule.ImportReference(originalInitMethod);
  174. var startMethod = assembly.MainModule.ImportReference(originalStartMethod);
  175. var methods = new List<MethodDefinition>();
  176. if (isCctor)
  177. {
  178. var cctor = entryType.Methods.FirstOrDefault(m => m.IsConstructor && m.IsStatic);
  179. if (cctor == null)
  180. {
  181. cctor = new MethodDefinition(".cctor",
  182. MethodAttributes.Static | MethodAttributes.Private | MethodAttributes.HideBySig
  183. | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName,
  184. assembly.MainModule.ImportReference(typeof(void)));
  185. entryType.Methods.Add(cctor);
  186. var il = cctor.Body.GetILProcessor();
  187. il.Append(il.Create(OpCodes.Ret));
  188. }
  189. methods.Add(cctor);
  190. }
  191. else
  192. {
  193. methods.AddRange(entryType.Methods.Where(x => x.Name == entrypointMethod));
  194. }
  195. if (!methods.Any())
  196. throw new Exception("The entrypoint method is invalid! Please check your config.ini");
  197. foreach (var method in methods)
  198. {
  199. var il = method.Body.GetILProcessor();
  200. var ins = il.Body.Instructions.First();
  201. il.InsertBefore(ins, il.Create(OpCodes.Ldstr, Paths.ExecutablePath)); //containerExePath
  202. il.InsertBefore(ins,
  203. il.Create(OpCodes
  204. .Ldc_I4_0)); //startConsole (always false, we already load the console in Preloader)
  205. il.InsertBefore(ins,
  206. il.Create(OpCodes.Call,
  207. initMethod)); //Chainloader.Initialize(string containerExePath, bool startConsole = true)
  208. il.InsertBefore(ins, il.Create(OpCodes.Call, startMethod));
  209. }
  210. }
  211. }
  212. /// <summary>
  213. /// Allocates a console window for use by BepInEx safely.
  214. /// </summary>
  215. public static void AllocateConsole()
  216. {
  217. bool console = Utility.SafeParseBool(Config.GetEntry("console", "false", "BepInEx"));
  218. bool shiftjis = Utility.SafeParseBool(Config.GetEntry("console-shiftjis", "false", "BepInEx"));
  219. if (!console)
  220. return;
  221. try
  222. {
  223. ConsoleWindow.Attach();
  224. var encoding = (uint) Encoding.UTF8.CodePage;
  225. if (shiftjis)
  226. encoding = 932;
  227. ConsoleEncoding.ConsoleCodePage = encoding;
  228. Console.OutputEncoding = ConsoleEncoding.GetEncoding(encoding);
  229. }
  230. catch (Exception ex)
  231. {
  232. Logger.Log(LogLevel.Error, "Failed to allocate console!");
  233. Logger.Log(LogLevel.Error, ex);
  234. }
  235. }
  236. }
  237. }