Preloader.cs 8.5 KB

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