UnityPreloader.cs 9.5 KB

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