Preloader.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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.Common;
  9. using BepInEx.Logging;
  10. using Mono.Cecil;
  11. using Mono.Cecil.Cil;
  12. using UnityInjector.ConsoleUtil;
  13. using MethodAttributes = Mono.Cecil.MethodAttributes;
  14. namespace BepInEx.Bootstrap
  15. {
  16. public static class Preloader
  17. {
  18. #region Path Properties
  19. public static string ExecutablePath { get; private set; }
  20. public static string CurrentExecutingAssemblyPath => Assembly.GetExecutingAssembly().CodeBase.Replace("file:///", "").Replace('/', '\\');
  21. public static string CurrentExecutingAssemblyDirectoryPath => Path.GetDirectoryName(CurrentExecutingAssemblyPath);
  22. public static string GameName => Path.GetFileNameWithoutExtension(Process.GetCurrentProcess().ProcessName);
  23. public static string GameRootPath => Path.GetDirectoryName(ExecutablePath);
  24. public static string ManagedPath => Utility.CombinePaths(GameRootPath, $"{GameName}_Data", "Managed");
  25. public static string PluginPath => Utility.CombinePaths(GameRootPath, "BepInEx");
  26. public static string PatcherPluginPath => Utility.CombinePaths(GameRootPath, "BepInEx", "patchers");
  27. #endregion
  28. public static PreloaderLogWriter PreloaderLog { get; private set; }
  29. public static Dictionary<string, IList<AssemblyPatcherDelegate>> PatcherDictionary = new Dictionary<string, IList<AssemblyPatcherDelegate>>(StringComparer.OrdinalIgnoreCase);
  30. public static void AddPatcher(string dllName, AssemblyPatcherDelegate patcher)
  31. {
  32. if (PatcherDictionary.TryGetValue(dllName, out IList<AssemblyPatcherDelegate> patcherList))
  33. patcherList.Add(patcher);
  34. else
  35. {
  36. patcherList = new List<AssemblyPatcherDelegate>();
  37. patcherList.Add(patcher);
  38. PatcherDictionary[dllName] = patcherList;
  39. }
  40. }
  41. private static bool TryGetConfigBool(string key, string defaultValue)
  42. {
  43. try
  44. {
  45. string result = Config.GetEntry(key, defaultValue);
  46. return bool.Parse(result);
  47. }
  48. catch
  49. {
  50. return false;
  51. }
  52. }
  53. internal static void AllocateConsole()
  54. {
  55. bool console = TryGetConfigBool("console", "false");
  56. bool shiftjis = TryGetConfigBool("console-shiftjis", "false");
  57. if (console)
  58. {
  59. try
  60. {
  61. UnityInjector.ConsoleUtil.ConsoleWindow.Attach();
  62. if (shiftjis)
  63. UnityInjector.ConsoleUtil.ConsoleEncoding.ConsoleCodePage = 932;
  64. else
  65. UnityInjector.ConsoleUtil.ConsoleEncoding.ConsoleCodePage = (uint)Encoding.UTF8.CodePage;
  66. }
  67. catch (Exception ex)
  68. {
  69. Logger.Log(LogLevel.Error, "Failed to allocate console!");
  70. Logger.Log(LogLevel.Error, ex);
  71. }
  72. }
  73. }
  74. public static void Main(string[] args)
  75. {
  76. try
  77. {
  78. AppDomain.CurrentDomain.AssemblyResolve += LocalResolve;
  79. ExecutablePath = args[0];
  80. AllocateConsole();
  81. PreloaderLog = new PreloaderLogWriter(TryGetConfigBool("preloader-logconsole", "false"));
  82. PreloaderLog.Enabled = true;
  83. string consoleTile = $"BepInEx {Assembly.GetExecutingAssembly().GetName().Version} - {Process.GetCurrentProcess().ProcessName}";
  84. ConsoleWindow.Title = consoleTile;
  85. Logger.SetLogger(PreloaderLog);
  86. PreloaderLog.WriteLine(consoleTile);
  87. Logger.Log(LogLevel.Message, "Preloader started");
  88. AddPatcher("UnityEngine.dll", PatchEntrypoint);
  89. if (Directory.Exists(PatcherPluginPath))
  90. foreach (string assemblyPath in Directory.GetFiles(PatcherPluginPath, "*.dll"))
  91. {
  92. try
  93. {
  94. var assembly = Assembly.LoadFrom(assemblyPath);
  95. foreach (var kv in GetPatcherMethods(assembly))
  96. foreach (var patcher in kv.Value)
  97. AddPatcher(kv.Key, patcher);
  98. }
  99. catch (BadImageFormatException) { } //unmanaged DLL
  100. catch (ReflectionTypeLoadException) { } //invalid references
  101. }
  102. AssemblyPatcher.PatchAll(ManagedPath, PatcherDictionary);
  103. }
  104. catch (Exception ex)
  105. {
  106. Logger.Log(LogLevel.Fatal, "Could not run preloader!");
  107. Logger.Log(LogLevel.Fatal, ex);
  108. PreloaderLog.Enabled = false;
  109. try
  110. {
  111. UnityInjector.ConsoleUtil.ConsoleWindow.Attach();
  112. Console.Write(PreloaderLog);
  113. }
  114. finally
  115. {
  116. File.WriteAllText(Path.Combine(GameRootPath, $"preloader_{DateTime.Now:yyyyMMdd_HHmmss_fff}.log"),
  117. PreloaderLog.ToString());
  118. PreloaderLog.Dispose();
  119. }
  120. }
  121. }
  122. internal static IDictionary<string, IList<AssemblyPatcherDelegate>> GetPatcherMethods(Assembly assembly)
  123. {
  124. var patcherMethods = new Dictionary<string, IList<AssemblyPatcherDelegate>>(StringComparer.OrdinalIgnoreCase);
  125. foreach (var type in assembly.GetExportedTypes())
  126. {
  127. try
  128. {
  129. if (type.IsInterface)
  130. continue;
  131. PropertyInfo targetsProperty = type.GetProperty(
  132. "TargetDLLs",
  133. BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase,
  134. null,
  135. typeof(IEnumerable<string>),
  136. Type.EmptyTypes,
  137. null);
  138. MethodInfo patcher = type.GetMethod(
  139. "Patch",
  140. BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase,
  141. null,
  142. CallingConventions.Any,
  143. new[] { typeof(AssemblyDefinition) },
  144. null);
  145. if (targetsProperty == null || !targetsProperty.CanRead || patcher == null)
  146. continue;
  147. AssemblyPatcherDelegate patchDelegate = (ass) => { patcher.Invoke(null, new object[] {ass}); };
  148. IEnumerable<string> targets = (IEnumerable<string>)targetsProperty.GetValue(null, null);
  149. foreach (string target in targets)
  150. {
  151. if (patcherMethods.TryGetValue(target, out IList<AssemblyPatcherDelegate> patchers))
  152. patchers.Add(patchDelegate);
  153. else
  154. {
  155. patchers = new List<AssemblyPatcherDelegate>{ patchDelegate };
  156. patcherMethods[target] = patchers;
  157. }
  158. }
  159. }
  160. catch (Exception ex)
  161. {
  162. Logger.Log(LogLevel.Warning, $"Could not load patcher methods from {assembly.GetName().Name}");
  163. Logger.Log(LogLevel.Warning, $"{ex}");
  164. }
  165. }
  166. Logger.Log(LogLevel.Info, $"Loaded {patcherMethods.SelectMany(x => x.Value).Distinct().Count()} patcher methods from {assembly.GetName().Name}");
  167. return patcherMethods;
  168. }
  169. internal static void PatchEntrypoint(AssemblyDefinition assembly)
  170. {
  171. if (assembly.Name.Name == "UnityEngine")
  172. {
  173. #if CECIL_10
  174. using (AssemblyDefinition injected = AssemblyDefinition.ReadAssembly(CurrentExecutingAssemblyPath))
  175. #elif CECIL_9
  176. AssemblyDefinition injected = AssemblyDefinition.ReadAssembly(CurrentExecutingAssemblyPath);
  177. #endif
  178. {
  179. var originalInjectMethod = injected.MainModule.Types.First(x => x.Name == "Chainloader")
  180. .Methods.First(x => x.Name == "Initialize");
  181. var injectMethod = assembly.MainModule.ImportReference(originalInjectMethod);
  182. var sceneManager = assembly.MainModule.Types.First(x => x.Name == "Application");
  183. var voidType = assembly.MainModule.ImportReference(typeof(void));
  184. var cctor = new MethodDefinition(".cctor",
  185. MethodAttributes.Static
  186. | MethodAttributes.Private
  187. | MethodAttributes.HideBySig
  188. | MethodAttributes.SpecialName
  189. | MethodAttributes.RTSpecialName,
  190. voidType);
  191. var ilp = cctor.Body.GetILProcessor();
  192. ilp.Append(ilp.Create(OpCodes.Call, injectMethod));
  193. ilp.Append(ilp.Create(OpCodes.Ret));
  194. sceneManager.Methods.Add(cctor);
  195. }
  196. }
  197. }
  198. internal static Assembly LocalResolve(object sender, ResolveEventArgs args)
  199. {
  200. AssemblyName assemblyName = new AssemblyName(args.Name);
  201. var foundAssembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(x => x.GetName().Name == assemblyName.Name);
  202. if (foundAssembly != null)
  203. return foundAssembly;
  204. if (Utility.TryResolveDllAssembly(assemblyName, CurrentExecutingAssemblyDirectoryPath, out foundAssembly) ||
  205. Utility.TryResolveDllAssembly(assemblyName, PatcherPluginPath, out foundAssembly) ||
  206. Utility.TryResolveDllAssembly(assemblyName, PluginPath, out foundAssembly))
  207. return foundAssembly;
  208. return null;
  209. }
  210. }
  211. }