Preloader.cs 8.7 KB

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