Preloader.cs 9.0 KB

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