Preloader.cs 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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. {
  56. TargetDLLs = () => new[] { ConfigEntrypointAssembly.Value },
  57. Patcher = PatchEntrypoint,
  58. Name = "BepInEx.Chainloader"
  59. });
  60. AssemblyPatcher.AddPatchersFromDirectory(Paths.PatcherPluginPath, ToPatcherPlugin);
  61. Logger.LogInfo($"{AssemblyPatcher.PatcherPlugins.Count} patcher plugin(s) loaded");
  62. AssemblyPatcher.PatchAndLoad(Paths.ManagedPath);
  63. AssemblyPatcher.DisposePatchers();
  64. Logger.LogMessage("Preloader finished");
  65. Logger.Listeners.Remove(PreloaderLog);
  66. Logger.Listeners.Add(new ConsoleLogListener());
  67. PreloaderLog.Dispose();
  68. }
  69. catch (Exception ex)
  70. {
  71. try
  72. {
  73. Logger.LogFatal("Could not run preloader!");
  74. Logger.LogFatal(ex);
  75. PreloaderLog?.Dispose();
  76. if (!ConsoleWindow.IsAttached)
  77. {
  78. //if we've already attached the console, then the log will already be written to the console
  79. AllocateConsole();
  80. Console.Write(PreloaderLog);
  81. }
  82. PreloaderLog = null;
  83. }
  84. finally
  85. {
  86. File.WriteAllText(
  87. Path.Combine(Paths.GameRootPath, $"preloader_{DateTime.Now:yyyyMMdd_HHmmss_fff}.log"),
  88. PreloaderLog + "\r\n" + ex);
  89. PreloaderLog?.Dispose();
  90. PreloaderLog = null;
  91. }
  92. }
  93. }
  94. public static PatcherPlugin ToPatcherPlugin(TypeDefinition type)
  95. {
  96. if (type.IsInterface || type.IsAbstract)
  97. return null;
  98. var targetDlls = type.Methods.FirstOrDefault(m => m.Name.Equals("get_TargetDLLs", StringComparison.InvariantCultureIgnoreCase) &&
  99. m.IsPublic &&
  100. m.IsStatic);
  101. if (targetDlls == null ||
  102. targetDlls.ReturnType.FullName != "System.Collections.Generic.IEnumerable`1<System.String>")
  103. return null;
  104. var patch = type.Methods.FirstOrDefault(m => m.Name.Equals("Patch") &&
  105. m.IsPublic &&
  106. m.IsStatic &&
  107. m.ReturnType.FullName == "System.Void" &&
  108. m.Parameters.Count == 1 &&
  109. (m.Parameters[0].ParameterType.FullName == "Mono.Cecil.AssemblyDefinition&" ||
  110. m.Parameters[0].ParameterType.FullName == "Mono.Cecil.AssemblyDefinition"));
  111. if (patch == null)
  112. return null;
  113. return new PatcherPlugin
  114. {
  115. Type = type
  116. };
  117. }
  118. /// <summary>
  119. /// Inserts BepInEx's own chainloader entrypoint into UnityEngine.
  120. /// </summary>
  121. /// <param name="assembly">The assembly that will be attempted to be patched.</param>
  122. public static void PatchEntrypoint(ref AssemblyDefinition assembly)
  123. {
  124. if (assembly.MainModule.AssemblyReferences.Any(x => x.Name.Contains("BepInEx")))
  125. throw new Exception("BepInEx has been detected to be patched! Please unpatch before using a patchless variant!");
  126. string entrypointType = ConfigEntrypointType.Value;
  127. string entrypointMethod = ConfigEntrypointMethod.Value;
  128. bool isCctor = entrypointMethod.IsNullOrWhiteSpace() || entrypointMethod == ".cctor";
  129. var entryType = assembly.MainModule.Types.FirstOrDefault(x => x.Name == entrypointType);
  130. if (entryType == null)
  131. throw new Exception("The entrypoint type is invalid! Please check your config.ini");
  132. using (var injected = AssemblyDefinition.ReadAssembly(Paths.BepInExAssemblyPath))
  133. {
  134. var originalInitMethod = injected.MainModule.Types.First(x => x.Name == "Chainloader").Methods
  135. .First(x => x.Name == "Initialize");
  136. var originalStartMethod = injected.MainModule.Types.First(x => x.Name == "Chainloader").Methods
  137. .First(x => x.Name == "Start");
  138. var initMethod = assembly.MainModule.ImportReference(originalInitMethod);
  139. var startMethod = assembly.MainModule.ImportReference(originalStartMethod);
  140. var methods = new List<MethodDefinition>();
  141. if (isCctor)
  142. {
  143. var cctor = entryType.Methods.FirstOrDefault(m => m.IsConstructor && m.IsStatic);
  144. if (cctor == null)
  145. {
  146. cctor = new MethodDefinition(".cctor",
  147. MethodAttributes.Static | MethodAttributes.Private | MethodAttributes.HideBySig
  148. | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName,
  149. assembly.MainModule.ImportReference(typeof(void)));
  150. entryType.Methods.Add(cctor);
  151. var il = cctor.Body.GetILProcessor();
  152. il.Append(il.Create(OpCodes.Ret));
  153. }
  154. methods.Add(cctor);
  155. }
  156. else
  157. {
  158. methods.AddRange(entryType.Methods.Where(x => x.Name == entrypointMethod));
  159. }
  160. if (!methods.Any())
  161. throw new Exception("The entrypoint method is invalid! Please check your config.ini");
  162. foreach (var method in methods)
  163. {
  164. var il = method.Body.GetILProcessor();
  165. var ins = il.Body.Instructions.First();
  166. il.InsertBefore(ins,
  167. il.Create(OpCodes.Ldstr, Paths.ExecutablePath)); //containerExePath
  168. il.InsertBefore(ins,
  169. il.Create(OpCodes.Ldc_I4_0)); //startConsole (always false, we already load the console in Preloader)
  170. il.InsertBefore(ins,
  171. il.Create(OpCodes.Call, initMethod)); //Chainloader.Initialize(string containerExePath, bool startConsole = true)
  172. il.InsertBefore(ins,
  173. il.Create(OpCodes.Call, startMethod));
  174. }
  175. }
  176. }
  177. /// <summary>
  178. /// Allocates a console window for use by BepInEx safely.
  179. /// </summary>
  180. public static void AllocateConsole()
  181. {
  182. if (!ConsoleWindow.ConfigConsoleEnabled.Value)
  183. return;
  184. try
  185. {
  186. ConsoleWindow.Attach();
  187. var encoding = (uint)Encoding.UTF8.CodePage;
  188. if (ConsoleWindow.ConfigConsoleShiftJis.Value)
  189. encoding = 932;
  190. ConsoleEncoding.ConsoleCodePage = encoding;
  191. Console.OutputEncoding = ConsoleEncoding.GetEncoding(encoding);
  192. }
  193. catch (Exception ex)
  194. {
  195. Logger.LogError("Failed to allocate console!");
  196. Logger.LogError(ex);
  197. }
  198. }
  199. #region Config
  200. private static readonly ConfigWrapper<string> ConfigEntrypointAssembly = ConfigFile.CoreConfig.Wrap(
  201. "Preloader.Entrypoint",
  202. "Assembly",
  203. "The local filename of the assembly to target.",
  204. #if UNITY_2018
  205. "UnityEngine.CoreModule.dll"
  206. #else
  207. "UnityEngine.dll"
  208. #endif
  209. );
  210. private static readonly ConfigWrapper<string> ConfigEntrypointType = ConfigFile.CoreConfig.Wrap(
  211. "Preloader.Entrypoint",
  212. "Type",
  213. "The name of the type in the entrypoint assembly to search for the entrypoint method.",
  214. "Application");
  215. private static readonly ConfigWrapper<string> ConfigEntrypointMethod = ConfigFile.CoreConfig.Wrap(
  216. "Preloader.Entrypoint",
  217. "Method",
  218. "The name of the method in the specified entrypoint assembly and type to hook and load Chainloader from.",
  219. ".cctor");
  220. private static readonly ConfigWrapper<bool> ConfigApplyRuntimePatches = ConfigFile.CoreConfig.Wrap(
  221. "Preloader",
  222. "ApplyRuntimePatches",
  223. "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.",
  224. true);
  225. private static readonly ConfigWrapper<bool> ConfigPreloaderCOutLogging = ConfigFile.CoreConfig.Wrap(
  226. "Logging",
  227. "PreloaderConsoleOutRedirection",
  228. "Redirects text from Console.Out during preloader patch loading to the BepInEx logging system.",
  229. true);
  230. #endregion
  231. }
  232. }