Preloader.cs 9.7 KB

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