Preloader.cs 10.0 KB

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