UnityPreloader.cs 8.7 KB

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