Preloader.cs 9.0 KB

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