Preloader.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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.Configuration;
  9. using BepInEx.Logging;
  10. using BepInEx.Preloader.Patching;
  11. using BepInEx.Preloader.RuntimeFixes;
  12. using Mono.Cecil;
  13. using Mono.Cecil.Cil;
  14. using UnityInjector.ConsoleUtil;
  15. using MethodAttributes = Mono.Cecil.MethodAttributes;
  16. namespace BepInEx.Preloader
  17. {
  18. /// <summary>
  19. /// The main entrypoint of BepInEx, and initializes all patchers and the chainloader.
  20. /// </summary>
  21. internal static class Preloader
  22. {
  23. /// <summary>
  24. /// The log writer that is specific to the preloader.
  25. /// </summary>
  26. private static PreloaderConsoleListener PreloaderLog { get; set; }
  27. public static void Run()
  28. {
  29. try
  30. {
  31. AllocateConsole();
  32. if (ConfigApplyRuntimePatches.Value)
  33. UnityPatches.Apply();
  34. Logger.Sources.Add(TraceLogSource.CreateSource());
  35. PreloaderLog = new PreloaderConsoleListener(ConfigPreloaderCOutLogging.Value);
  36. Logger.Listeners.Add(PreloaderLog);
  37. string consoleTile = $"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. #if UNITY_2018
  48. Logger.LogMessage("Compiled in Unity v2018 mode");
  49. #else
  50. Logger.LogMessage("Compiled in Legacy Unity mode");
  51. #endif
  52. Logger.LogInfo($"Running under Unity v{Process.GetCurrentProcess().MainModule.FileVersionInfo.FileVersion}");
  53. Logger.LogMessage("Preloader started");
  54. AssemblyPatcher.AddPatcher(new PatcherPlugin
  55. { TargetDLLs = new[] { ConfigEntrypointAssembly.Value }, Patcher = PatchEntrypoint });
  56. AssemblyPatcher.AddPatchersFromDirectory(Paths.PatcherPluginPath, GetPatcherMethods);
  57. Logger.LogInfo($"{AssemblyPatcher.PatcherPlugins.Count} patcher plugin(s) loaded");
  58. AssemblyPatcher.PatchAndLoad(Paths.ManagedPath);
  59. AssemblyPatcher.DisposePatchers();
  60. Logger.LogMessage("Preloader finished");
  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 = ConfigEntrypointType.Value;
  171. string entrypointMethod = ConfigEntrypointMethod.Value;
  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,
  211. il.Create(OpCodes.Ldstr, Paths.ExecutablePath)); //containerExePath
  212. il.InsertBefore(ins,
  213. il.Create(OpCodes.Ldc_I4_0)); //startConsole (always false, we already load the console in Preloader)
  214. il.InsertBefore(ins,
  215. il.Create(OpCodes.Call, initMethod)); //Chainloader.Initialize(string containerExePath, bool startConsole = true)
  216. il.InsertBefore(ins,
  217. 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. if (!ConfigConsoleEnabled.Value)
  227. return;
  228. try
  229. {
  230. ConsoleWindow.Attach();
  231. var encoding = (uint)Encoding.UTF8.CodePage;
  232. if (ConfigConsoleShiftJis.Value)
  233. encoding = 932;
  234. ConsoleEncoding.ConsoleCodePage = encoding;
  235. Console.OutputEncoding = ConsoleEncoding.GetEncoding(encoding);
  236. }
  237. catch (Exception ex)
  238. {
  239. Logger.LogError("Failed to allocate console!");
  240. Logger.LogError(ex);
  241. }
  242. }
  243. #region Config
  244. private static readonly ConfigWrapper<string> ConfigEntrypointAssembly = ConfigFile.CoreConfig.Wrap(
  245. "Preloader.Entrypoint",
  246. "Assembly",
  247. "The local filename of the assembly to target.",
  248. "UnityEngine.dll");
  249. private static readonly ConfigWrapper<string> ConfigEntrypointType = ConfigFile.CoreConfig.Wrap(
  250. "Preloader.Entrypoint",
  251. "Type",
  252. "The name of the type in the entrypoint assembly to search for the entrypoint method.",
  253. "Application");
  254. private static readonly ConfigWrapper<string> ConfigEntrypointMethod = ConfigFile.CoreConfig.Wrap(
  255. "Preloader.Entrypoint",
  256. "Method",
  257. "The name of the method in the specified entrypoint assembly and type to hook and load Chainloader from.",
  258. ".cctor");
  259. private static readonly ConfigWrapper<bool> ConfigApplyRuntimePatches = ConfigFile.CoreConfig.Wrap(
  260. "Preloader",
  261. "ApplyRuntimePatches",
  262. "Enables or disables runtime patches.\nThis should always be true, unless you cannot start the game due to a Harmony related issue (such as running .NET Standard runtime) or you know what you're doing.",
  263. true);
  264. private static readonly ConfigWrapper<bool> ConfigPreloaderCOutLogging = ConfigFile.CoreConfig.Wrap(
  265. "Logging",
  266. "PreloaderConsoleOutRedirection",
  267. "Redirects text from Console.Out during preloader patch loading to the BepInEx logging system.",
  268. true);
  269. private static readonly ConfigWrapper<bool> ConfigConsoleEnabled = ConfigFile.CoreConfig.Wrap(
  270. "Logging.Console",
  271. "Enabled",
  272. "Enables showing a console for log output.",
  273. false);
  274. private static readonly ConfigWrapper<bool> ConfigConsoleShiftJis = ConfigFile.CoreConfig.Wrap(
  275. "Logging.Console",
  276. "ShiftJisEncoding",
  277. "If true, console is set to the Shift-JIS encoding, otherwise UTF-8 encoding.",
  278. false);
  279. #endregion
  280. }
  281. }