Preloader.cs 9.2 KB

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