PreloaderPatchManager.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Reflection;
  6. using BepInEx.Logging;
  7. using Mono.Cecil;
  8. using Mono.Cecil.Cil;
  9. namespace BepInEx.Bootstrap
  10. {
  11. public static class PreloaderPatchManager
  12. {
  13. /// <summary>
  14. /// The dictionary of currently loaded patchers. The key is the patcher delegate that will be used to patch, and the value is a list of filenames of assemblies that the patcher is targeting.
  15. /// </summary>
  16. public static Dictionary<AssemblyPatcherDelegate, IEnumerable<string>> PatcherDictionary { get; } =
  17. new Dictionary<AssemblyPatcherDelegate, IEnumerable<string>>();
  18. /// <summary>
  19. /// The list of initializers that were loaded from the patcher contract.
  20. /// </summary>
  21. public static List<Action> Initializers { get; } = new List<Action>();
  22. /// <summary>
  23. /// The list of finalizers that were loaded from the patcher contract.
  24. /// </summary>
  25. public static List<Action> Finalizers { get; } = new List<Action>();
  26. /// <summary>
  27. /// Adds the patcher to the patcher dictionary.
  28. /// </summary>
  29. /// <param name="dllNames">The list of DLL filenames to be patched.</param>
  30. /// <param name="patcher">The method that will perform the patching.</param>
  31. internal static void AddPatcher(IEnumerable<string> dllNames, AssemblyPatcherDelegate patcher)
  32. {
  33. PreloaderPatchManager.PatcherDictionary[patcher] = dllNames;
  34. }
  35. public static void Run()
  36. {
  37. AddPatcher(new[] {"UnityEngine.dll"}, PatchEntrypoint);
  38. if (Directory.Exists(Preloader.PatcherPluginPath))
  39. {
  40. SortedDictionary<string, KeyValuePair<AssemblyPatcherDelegate, IEnumerable<string>>> sortedPatchers =
  41. new SortedDictionary<string, KeyValuePair<AssemblyPatcherDelegate, IEnumerable<string>>>();
  42. foreach (string assemblyPath in Directory.GetFiles(Preloader.PatcherPluginPath, "*.dll"))
  43. {
  44. try
  45. {
  46. var assembly = Assembly.LoadFrom(assemblyPath);
  47. foreach (var kv in GetPatcherMethods(assembly))
  48. sortedPatchers.Add(assembly.GetName().Name, kv);
  49. }
  50. catch (BadImageFormatException) { } //unmanaged DLL
  51. catch (ReflectionTypeLoadException) { } //invalid references
  52. }
  53. foreach (var kv in sortedPatchers)
  54. AddPatcher(kv.Value.Value, kv.Value.Key);
  55. }
  56. AssemblyPatcher.PatchAll(Preloader.ManagedPath, PatcherDictionary, Initializers, Finalizers);
  57. }
  58. /// <summary>
  59. /// Scans the assembly for classes that use the patcher contract, and returns a dictionary of the patch methods.
  60. /// </summary>
  61. /// <param name="assembly">The assembly to scan.</param>
  62. /// <returns>A dictionary of delegates which will be used to patch the targeted assemblies.</returns>
  63. public static Dictionary<AssemblyPatcherDelegate, IEnumerable<string>> GetPatcherMethods(Assembly assembly)
  64. {
  65. var patcherMethods = new Dictionary<AssemblyPatcherDelegate, IEnumerable<string>>();
  66. foreach (var type in assembly.GetExportedTypes())
  67. {
  68. try
  69. {
  70. if (type.IsInterface)
  71. continue;
  72. PropertyInfo targetsProperty = type.GetProperty("TargetDLLs",
  73. BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase,
  74. null,
  75. typeof(IEnumerable<string>),
  76. Type.EmptyTypes,
  77. null);
  78. //first try get the ref patcher method
  79. MethodInfo patcher = type.GetMethod("Patch",
  80. BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase,
  81. null,
  82. CallingConventions.Any,
  83. new[] {typeof(AssemblyDefinition).MakeByRefType()},
  84. null);
  85. if (patcher == null) //otherwise try getting the non-ref patcher method
  86. {
  87. patcher = type.GetMethod("Patch",
  88. BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase,
  89. null,
  90. CallingConventions.Any,
  91. new[] {typeof(AssemblyDefinition)},
  92. null);
  93. }
  94. if (targetsProperty == null || !targetsProperty.CanRead || patcher == null)
  95. continue;
  96. AssemblyPatcherDelegate patchDelegate = (ref AssemblyDefinition ass) =>
  97. {
  98. //we do the array fuckery here to get the ref result out
  99. object[] args = {ass};
  100. patcher.Invoke(null, args);
  101. ass = (AssemblyDefinition) args[0];
  102. };
  103. IEnumerable<string> targets = (IEnumerable<string>) targetsProperty.GetValue(null, null);
  104. patcherMethods[patchDelegate] = targets;
  105. MethodInfo initMethod = type.GetMethod("Initialize",
  106. BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase,
  107. null,
  108. CallingConventions.Any,
  109. Type.EmptyTypes,
  110. null);
  111. if (initMethod != null)
  112. {
  113. Initializers.Add(() => initMethod.Invoke(null, null));
  114. }
  115. MethodInfo finalizeMethod = type.GetMethod("Finish",
  116. BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase,
  117. null,
  118. CallingConventions.Any,
  119. Type.EmptyTypes,
  120. null);
  121. if (finalizeMethod != null)
  122. {
  123. Finalizers.Add(() => finalizeMethod.Invoke(null, null));
  124. }
  125. }
  126. catch (Exception ex)
  127. {
  128. Logger.Log(LogLevel.Warning, $"Could not load patcher methods from {assembly.GetName().Name}");
  129. Logger.Log(LogLevel.Warning, $"{ex}");
  130. }
  131. }
  132. Logger.Log(LogLevel.Info,
  133. $"Loaded {patcherMethods.Select(x => x.Key).Distinct().Count()} patcher methods from {assembly.GetName().Name}");
  134. return patcherMethods;
  135. }
  136. /// <summary>
  137. /// Inserts BepInEx's own chainloader entrypoint into UnityEngine.
  138. /// </summary>
  139. /// <param name="assembly">The assembly that will be attempted to be patched.</param>
  140. public static void PatchEntrypoint(ref AssemblyDefinition assembly)
  141. {
  142. if (assembly.Name.Name == "UnityEngine")
  143. {
  144. #if CECIL_10
  145. using (AssemblyDefinition injected = AssemblyDefinition.ReadAssembly(Preloader.BepInExAssemblyPath))
  146. #elif CECIL_9
  147. AssemblyDefinition injected = AssemblyDefinition.ReadAssembly(BepInExAssemblyPath);
  148. #endif
  149. {
  150. var originalInjectMethod = injected.MainModule.Types.First(x => x.Name == "Chainloader").Methods
  151. .First(x => x.Name == "Initialize");
  152. var injectMethod = assembly.MainModule.ImportReference(originalInjectMethod);
  153. var sceneManager = assembly.MainModule.Types.First(x => x.Name == "Application");
  154. var voidType = assembly.MainModule.ImportReference(typeof(void));
  155. var cctor = new MethodDefinition(".cctor",
  156. Mono.Cecil.MethodAttributes.Static | Mono.Cecil.MethodAttributes.Private
  157. | Mono.Cecil.MethodAttributes.HideBySig
  158. | Mono.Cecil.MethodAttributes.SpecialName
  159. | Mono.Cecil.MethodAttributes.RTSpecialName,
  160. voidType);
  161. var ilp = cctor.Body.GetILProcessor();
  162. ilp.Append(ilp.Create(OpCodes.Call, injectMethod));
  163. ilp.Append(ilp.Create(OpCodes.Ret));
  164. sceneManager.Methods.Add(cctor);
  165. }
  166. }
  167. }
  168. }
  169. }