Preloader.cs 9.4 KB

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