UnityPreloader.cs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Linq;
  6. using BepInEx.Bootstrap;
  7. using BepInEx.Configuration;
  8. using BepInEx.Core.Logging;
  9. using BepInEx.Logging;
  10. using BepInEx.Preloader.Core;
  11. using BepInEx.Preloader.Core.Logging;
  12. using BepInEx.Preloader.RuntimeFixes;
  13. using Mono.Cecil;
  14. using Mono.Cecil.Cil;
  15. using MonoMod.Utils;
  16. using MethodAttributes = Mono.Cecil.MethodAttributes;
  17. namespace BepInEx.Preloader.Unity
  18. {
  19. /// <summary>
  20. /// The main entrypoint of BepInEx, and initializes all patchers and the chainloader.
  21. /// </summary>
  22. internal static class UnityPreloader
  23. {
  24. /// <summary>
  25. /// The log writer that is specific to the preloader.
  26. /// </summary>
  27. private static PreloaderConsoleListener PreloaderLog { get; set; }
  28. private static ManualLogSource Log => PreloaderLogger.Log;
  29. public static string ManagedPath { get; private set; } = Utility.CombinePaths(Paths.GameRootPath, $"{Paths.ProcessName}_Data", "Managed");
  30. public static bool IsPostUnity2017 { get; } = File.Exists(Path.Combine(ManagedPath, "UnityEngine.CoreModule.dll"));
  31. public static void Run(string managedDirectory)
  32. {
  33. try
  34. {
  35. ConsoleManager.Initialize(false);
  36. AllocateConsole();
  37. if (managedDirectory != null)
  38. ManagedPath = managedDirectory;
  39. Utility.TryDo(() =>
  40. {
  41. if (ConfigApplyRuntimePatches.Value)
  42. UnityPatches.Apply();
  43. }, out var runtimePatchException);
  44. Logger.Sources.Add(TraceLogSource.CreateSource());
  45. Logger.Sources.Add(new HarmonyLogSource());
  46. PreloaderLog = new PreloaderConsoleListener(ConfigPreloaderCOutLogging.Value);
  47. Logger.Listeners.Add(PreloaderLog);
  48. ChainloaderLogHelper.PrintLogInfo(Log);
  49. Log.LogInfo($"Running under Unity v{GetUnityVersion()}");
  50. Log.LogInfo($"CLR runtime version: {Environment.Version}");
  51. Log.LogInfo($"Supports SRE: {Utility.CLRSupportsDynamicAssemblies}");
  52. Log.LogDebug($"Game executable path: {Paths.ExecutablePath}");
  53. Log.LogDebug($"Unity Managed directory: {ManagedPath}");
  54. Log.LogDebug($"BepInEx root path: {Paths.BepInExRootPath}");
  55. if (runtimePatchException != null)
  56. Log.LogWarning($"Failed to apply runtime patches for Mono. See more info in the output log. Error message: {runtimePatchException.Message}");
  57. Log.LogMessage("Preloader started");
  58. TypeLoader.SearchDirectories.Add(ManagedPath);
  59. using (var assemblyPatcher = new AssemblyPatcher())
  60. {
  61. assemblyPatcher.PatcherPlugins.Add(new PatcherPlugin
  62. {
  63. TargetDLLs = () => new[] { ConfigEntrypointAssembly.Value },
  64. Patcher = PatchEntrypoint,
  65. TypeName = "BepInEx.Chainloader"
  66. });
  67. assemblyPatcher.AddPatchersFromDirectory(Paths.PatcherPluginPath);
  68. Log.LogInfo($"{assemblyPatcher.PatcherPlugins.Count} patcher plugin(s) loaded");
  69. assemblyPatcher.LoadAssemblyDirectory(ManagedPath);
  70. Log.LogInfo($"{assemblyPatcher.PatcherPlugins.Count} assemblies discovered");
  71. assemblyPatcher.PatchAndLoad();
  72. }
  73. Log.LogMessage("Preloader finished");
  74. Logger.Listeners.Remove(PreloaderLog);
  75. Logger.Listeners.Add(new ConsoleLogListener());
  76. PreloaderLog.Dispose();
  77. Logger.Listeners.Add(new StdOutLogListener());
  78. }
  79. catch (Exception ex)
  80. {
  81. try
  82. {
  83. Log.LogFatal("Could not run preloader!");
  84. Log.LogFatal(ex);
  85. if (!ConsoleManager.ConsoleActive)
  86. {
  87. //if we've already attached the console, then the log will already be written to the console
  88. AllocateConsole();
  89. Console.Write(PreloaderLog);
  90. }
  91. }
  92. catch { }
  93. string log = string.Empty;
  94. try
  95. {
  96. // We could use platform-dependent newlines, however the developers use Windows so this will be easier to read :)
  97. log = string.Join("\r\n", PreloaderConsoleListener.LogEvents.Select(x => x.ToString()).ToArray());
  98. log += "\r\n";
  99. PreloaderLog?.Dispose();
  100. PreloaderLog = null;
  101. }
  102. catch { }
  103. File.WriteAllText(
  104. Path.Combine(Paths.GameRootPath, $"preloader_{DateTime.Now:yyyyMMdd_HHmmss_fff}.log"),
  105. log + ex);
  106. }
  107. }
  108. /// <summary>
  109. /// Inserts BepInEx's own chainloader entrypoint into UnityEngine.
  110. /// </summary>
  111. /// <param name="assembly">The assembly that will be attempted to be patched.</param>
  112. public static void PatchEntrypoint(ref AssemblyDefinition assembly)
  113. {
  114. if (assembly.MainModule.AssemblyReferences.Any(x => x.Name.Contains("BepInEx")))
  115. throw new Exception("BepInEx has been detected to be patched! Please unpatch before using a patchless variant!");
  116. string entrypointType = ConfigEntrypointType.Value;
  117. string entrypointMethod = ConfigEntrypointMethod.Value;
  118. bool isCctor = entrypointMethod.IsNullOrWhiteSpace() || entrypointMethod == ".cctor";
  119. var entryType = assembly.MainModule.Types.FirstOrDefault(x => x.Name == entrypointType);
  120. if (entryType == null)
  121. throw new Exception("The entrypoint type is invalid! Please check your config/BepInEx.cfg file");
  122. string chainloaderAssemblyPath = Path.Combine(Paths.BepInExAssemblyDirectory, "BepInEx.Unity.dll");
  123. var readerParameters = new ReaderParameters
  124. {
  125. AssemblyResolver = TypeLoader.CecilResolver
  126. };
  127. using (var chainloaderAssemblyDefinition = AssemblyDefinition.ReadAssembly(chainloaderAssemblyPath, readerParameters))
  128. {
  129. var chainloaderType = chainloaderAssemblyDefinition.MainModule.Types.First(x => x.Name == "UnityChainloader");
  130. var originalStartMethod = chainloaderType.EnumerateAllMethods().First(x => x.Name == "StaticStart");
  131. var startMethod = assembly.MainModule.ImportReference(originalStartMethod);
  132. var methods = new List<MethodDefinition>();
  133. if (isCctor)
  134. {
  135. var cctor = entryType.Methods.FirstOrDefault(m => m.IsConstructor && m.IsStatic);
  136. if (cctor == null)
  137. {
  138. cctor = new MethodDefinition(".cctor",
  139. MethodAttributes.Static | MethodAttributes.Private | MethodAttributes.HideBySig
  140. | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName,
  141. assembly.MainModule.ImportReference(typeof(void)));
  142. entryType.Methods.Add(cctor);
  143. var il = cctor.Body.GetILProcessor();
  144. il.Append(il.Create(OpCodes.Ret));
  145. }
  146. methods.Add(cctor);
  147. }
  148. else
  149. {
  150. methods.AddRange(entryType.Methods.Where(x => x.Name == entrypointMethod));
  151. }
  152. if (!methods.Any())
  153. throw new Exception("The entrypoint method is invalid! Please check your config.ini");
  154. foreach (var method in methods)
  155. {
  156. var il = method.Body.GetILProcessor();
  157. var ins = il.Body.Instructions.First();
  158. il.InsertBefore(ins,
  159. il.Create(OpCodes.Ldnull)); // gameExePath (always null, we initialize the Paths class in Entrypoint
  160. il.InsertBefore(ins,
  161. il.Create(OpCodes.Call, startMethod)); // UnityChainloader.StaticStart(string gameExePath)
  162. }
  163. }
  164. }
  165. /// <summary>
  166. /// Allocates a console window for use by BepInEx safely.
  167. /// </summary>
  168. public static void AllocateConsole()
  169. {
  170. if (!ConsoleManager.ConfigConsoleEnabled.Value)
  171. return;
  172. try
  173. {
  174. ConsoleManager.CreateConsole();
  175. }
  176. catch (Exception ex)
  177. {
  178. Log.LogError("Failed to allocate console!");
  179. Log.LogError(ex);
  180. }
  181. }
  182. public static string GetUnityVersion()
  183. {
  184. if (Utility.CurrentPlatform == Platform.Windows)
  185. return FileVersionInfo.GetVersionInfo(Paths.ExecutablePath).FileVersion;
  186. return $"Unknown ({(IsPostUnity2017 ? "post" : "pre")}-2017)";
  187. }
  188. #region Config
  189. private static readonly ConfigEntry<string> ConfigEntrypointAssembly = ConfigFile.CoreConfig.Bind(
  190. "Preloader.Entrypoint", "Assembly",
  191. IsPostUnity2017 ? "UnityEngine.CoreModule.dll" : "UnityEngine.dll",
  192. "The local filename of the assembly to target.");
  193. private static readonly ConfigEntry<string> ConfigEntrypointType = ConfigFile.CoreConfig.Bind(
  194. "Preloader.Entrypoint", "Type",
  195. "Application",
  196. "The name of the type in the entrypoint assembly to search for the entrypoint method.");
  197. private static readonly ConfigEntry<string> ConfigEntrypointMethod = ConfigFile.CoreConfig.Bind(
  198. "Preloader.Entrypoint", "Method",
  199. ".cctor",
  200. "The name of the method in the specified entrypoint assembly and type to hook and load Chainloader from.");
  201. internal static readonly ConfigEntry<bool> ConfigApplyRuntimePatches = ConfigFile.CoreConfig.Bind(
  202. "Preloader", "ApplyRuntimePatches",
  203. true,
  204. "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.");
  205. private static readonly ConfigEntry<bool> ConfigPreloaderCOutLogging = ConfigFile.CoreConfig.Bind(
  206. "Logging", "PreloaderConsoleOutRedirection",
  207. true,
  208. "Redirects text from Console.Out during preloader patch loading to the BepInEx logging system.");
  209. #endregion
  210. }
  211. }