Preloader.cs 10 KB

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