Preloader.cs 9.1 KB

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