UnityPreloader.cs 9.2 KB

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