UnityPreloader.cs 9.5 KB

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