AssemblyPatcher.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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 System.Text;
  8. using BepInEx.Bootstrap;
  9. using BepInEx.Configuration;
  10. using BepInEx.Logging;
  11. using BepInEx.Preloader.RuntimeFixes;
  12. using Mono.Cecil;
  13. namespace BepInEx.Preloader.Patching
  14. {
  15. /// <summary>
  16. /// Delegate used in patching assemblies.
  17. /// </summary>
  18. /// <param name="assembly">The assembly that is being patched.</param>
  19. internal delegate void AssemblyPatcherDelegate(ref AssemblyDefinition assembly);
  20. /// <summary>
  21. /// Worker class which is used for loading and patching entire folders of assemblies, or alternatively patching and
  22. /// loading assemblies one at a time.
  23. /// </summary>
  24. internal static class AssemblyPatcher
  25. {
  26. private const BindingFlags ALL = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.IgnoreCase;
  27. public static List<PatcherPlugin> PatcherPlugins { get; } = new List<PatcherPlugin>();
  28. private static readonly string DumpedAssembliesPath = Path.Combine(Paths.BepInExRootPath, "DumpedAssemblies");
  29. /// <summary>
  30. /// Adds a single assembly patcher to the pool of applicable patches.
  31. /// </summary>
  32. /// <param name="patcher">Patcher to apply.</param>
  33. public static void AddPatcher(PatcherPlugin patcher)
  34. {
  35. PatcherPlugins.Add(patcher);
  36. }
  37. private static T CreateDelegate<T>(MethodInfo method) where T : class => method != null ? Delegate.CreateDelegate(typeof(T), method) as T : null;
  38. private static PatcherPlugin ToPatcherPlugin(TypeDefinition type)
  39. {
  40. if (type.IsInterface || type.IsAbstract && !type.IsSealed)
  41. return null;
  42. var targetDlls = type.Methods.FirstOrDefault(m => m.Name.Equals("get_TargetDLLs", StringComparison.InvariantCultureIgnoreCase) &&
  43. m.IsPublic &&
  44. m.IsStatic);
  45. if (targetDlls == null ||
  46. targetDlls.ReturnType.FullName != "System.Collections.Generic.IEnumerable`1<System.String>")
  47. return null;
  48. var patch = type.Methods.FirstOrDefault(m => m.Name.Equals("Patch") &&
  49. m.IsPublic &&
  50. m.IsStatic &&
  51. m.ReturnType.FullName == "System.Void" &&
  52. m.Parameters.Count == 1 &&
  53. (m.Parameters[0].ParameterType.FullName == "Mono.Cecil.AssemblyDefinition&" ||
  54. m.Parameters[0].ParameterType.FullName == "Mono.Cecil.AssemblyDefinition"));
  55. if (patch == null)
  56. return null;
  57. return new PatcherPlugin
  58. {
  59. TypeName = type.FullName
  60. };
  61. }
  62. /// <summary>
  63. /// Adds all patchers from all managed assemblies specified in a directory.
  64. /// </summary>
  65. /// <param name="directory">Directory to search patcher DLLs from.</param>
  66. /// <param name="patcherLocator">A function that locates assembly patchers in a given managed assembly.</param>
  67. public static void AddPatchersFromDirectory(string directory)
  68. {
  69. if (!Directory.Exists(directory))
  70. return;
  71. var sortedPatchers = new SortedDictionary<string, PatcherPlugin>();
  72. var patchers = TypeLoader.FindPluginTypes(directory, ToPatcherPlugin);
  73. foreach (var keyValuePair in patchers)
  74. {
  75. var assemblyPath = keyValuePair.Key;
  76. var patcherCollection = keyValuePair.Value;
  77. if(patcherCollection.Count == 0)
  78. continue;
  79. var ass = Assembly.LoadFile(assemblyPath);
  80. foreach (var patcherPlugin in patcherCollection)
  81. {
  82. try
  83. {
  84. var type = ass.GetType(patcherPlugin.TypeName);
  85. var methods = type.GetMethods(ALL);
  86. patcherPlugin.Initializer = CreateDelegate<Action>(methods.FirstOrDefault(m => m.Name.Equals("Initialize", StringComparison.InvariantCultureIgnoreCase) &&
  87. m.GetParameters().Length == 0 &&
  88. m.ReturnType == typeof(void)));
  89. patcherPlugin.Finalizer = CreateDelegate<Action>(methods.FirstOrDefault(m => m.Name.Equals("Finish", StringComparison.InvariantCultureIgnoreCase) &&
  90. m.GetParameters().Length == 0 &&
  91. m.ReturnType == typeof(void)));
  92. patcherPlugin.TargetDLLs = CreateDelegate<Func<IEnumerable<string>>>(type.GetProperty("TargetDLLs", ALL).GetGetMethod());
  93. var patcher = methods.FirstOrDefault(m => m.Name.Equals("Patch", StringComparison.CurrentCultureIgnoreCase) &&
  94. m.ReturnType == typeof(void) &&
  95. m.GetParameters().Length == 1 &&
  96. (m.GetParameters()[0].ParameterType == typeof(AssemblyDefinition) ||
  97. m.GetParameters()[0].ParameterType == typeof(AssemblyDefinition).MakeByRefType()));
  98. patcherPlugin.Patcher = (ref AssemblyDefinition pAss) =>
  99. {
  100. //we do the array fuckery here to get the ref result out
  101. object[] args = { pAss };
  102. patcher.Invoke(null, args);
  103. pAss = (AssemblyDefinition)args[0];
  104. };
  105. sortedPatchers.Add($"{ass.GetName().Name}/{type.FullName}", patcherPlugin);
  106. }
  107. catch (Exception e)
  108. {
  109. Logger.LogError($"Failed to load patcher [{patcherPlugin.TypeName}]: {e.Message}");
  110. if (e is ReflectionTypeLoadException re)
  111. Logger.LogDebug(TypeLoader.TypeLoadExceptionToString(re));
  112. else
  113. Logger.LogDebug(e.ToString());
  114. }
  115. }
  116. Logger.Log(patcherCollection.Any() ? LogLevel.Info : LogLevel.Debug,
  117. $"Loaded {patcherCollection.Count} patcher methods from {ass.GetName().FullName}");
  118. }
  119. foreach (KeyValuePair<string, PatcherPlugin> patcher in sortedPatchers)
  120. AddPatcher(patcher.Value);
  121. }
  122. private static void InitializePatchers()
  123. {
  124. foreach (var assemblyPatcher in PatcherPlugins)
  125. assemblyPatcher.Initializer?.Invoke();
  126. }
  127. private static void FinalizePatching()
  128. {
  129. foreach (var assemblyPatcher in PatcherPlugins)
  130. assemblyPatcher.Finalizer?.Invoke();
  131. }
  132. /// <summary>
  133. /// Releases all patchers to let them be collected by GC.
  134. /// </summary>
  135. public static void DisposePatchers()
  136. {
  137. PatcherPlugins.Clear();
  138. }
  139. /// <summary>
  140. /// Applies patchers to all assemblies in the given directory and loads patched assemblies into memory.
  141. /// </summary>
  142. /// <param name="directory">Directory to load CLR assemblies from.</param>
  143. public static void PatchAndLoad(string directory)
  144. {
  145. // First, load patchable assemblies into Cecil
  146. var assemblies = new Dictionary<string, AssemblyDefinition>();
  147. foreach (string assemblyPath in Directory.GetFiles(directory, "*.dll"))
  148. {
  149. AssemblyDefinition assembly;
  150. try
  151. {
  152. assembly = AssemblyDefinition.ReadAssembly(assemblyPath);
  153. }
  154. catch (BadImageFormatException)
  155. {
  156. // Not a managed assembly, skip
  157. continue;
  158. }
  159. //NOTE: this is special cased here because the dependency handling for System.dll is a bit wonky
  160. //System has an assembly reference to itself, and it also has a reference to Mono.Security causing a circular dependency
  161. //It's also generally dangerous to change system.dll since so many things rely on it,
  162. // and it's already loaded into the appdomain since this loader references it, so we might as well skip it
  163. if (assembly.Name.Name == "System" || assembly.Name.Name == "mscorlib") //mscorlib is already loaded into the appdomain so it can't be patched
  164. {
  165. assembly.Dispose();
  166. continue;
  167. }
  168. if (UnityPatches.AssemblyLocations.ContainsKey(assembly.FullName))
  169. {
  170. Logger.LogWarning($"Tried to load duplicate assembly {Path.GetFileName(assemblyPath)} from Managed folder! Skipping...");
  171. continue;
  172. }
  173. assemblies.Add(Path.GetFileName(assemblyPath), assembly);
  174. UnityPatches.AssemblyLocations.Add(assembly.FullName, Path.GetFullPath(assemblyPath));
  175. }
  176. // Next, initialize all the patchers
  177. InitializePatchers();
  178. // Then, perform the actual patching
  179. var patchedAssemblies = new HashSet<string>();
  180. var resolvedAssemblies = new Dictionary<string, string>();
  181. foreach (var assemblyPatcher in PatcherPlugins)
  182. foreach (string targetDll in assemblyPatcher.TargetDLLs())
  183. if (assemblies.TryGetValue(targetDll, out var assembly))
  184. {
  185. Logger.LogInfo($"Patching [{assembly.Name.Name}] with [{assemblyPatcher.TypeName}]");
  186. assemblyPatcher.Patcher?.Invoke(ref assembly);
  187. assemblies[targetDll] = assembly;
  188. patchedAssemblies.Add(targetDll);
  189. foreach (var resolvedAss in AppDomain.CurrentDomain.GetAssemblies())
  190. {
  191. var name = new AssemblyName(resolvedAss.FullName).Name;
  192. // Report only the first type that caused the assembly to load, because any subsequent ones can be false positives
  193. if (!resolvedAssemblies.ContainsKey(name))
  194. resolvedAssemblies[name] = assemblyPatcher.TypeName;
  195. }
  196. }
  197. // Check if any patched assemblies have been already resolved by the CLR
  198. // If there are any, they cannot be loaded by the preloader
  199. var patchedAssemblyNames = new HashSet<string>(assemblies.Where(kv => patchedAssemblies.Contains(kv.Key)).Select(kv => kv.Value.Name.Name));
  200. var earlyLoadAssemblies = resolvedAssemblies.Where(kv => patchedAssemblyNames.Contains(kv.Key)).ToList();
  201. if (earlyLoadAssemblies.Count != 0)
  202. {
  203. Logger.LogWarning(new StringBuilder()
  204. .AppendLine("The following assemblies have been loaded too early and will not be patched by preloader:")
  205. .AppendLine(string.Join(Environment.NewLine, earlyLoadAssemblies.Select(kv => $"* [{kv.Key}] (first loaded by [{kv.Value}])").ToArray()))
  206. .AppendLine("Expect unexpected behavior and issues with plugins and patchers not being loaded.")
  207. .ToString());
  208. }
  209. // Finally, load patched assemblies into memory
  210. if (ConfigDumpAssemblies.Value || ConfigLoadDumpedAssemblies.Value)
  211. {
  212. if (!Directory.Exists(DumpedAssembliesPath))
  213. Directory.CreateDirectory(DumpedAssembliesPath);
  214. foreach (KeyValuePair<string, AssemblyDefinition> kv in assemblies)
  215. {
  216. string filename = kv.Key;
  217. var assembly = kv.Value;
  218. if (patchedAssemblies.Contains(filename))
  219. assembly.Write(Path.Combine(DumpedAssembliesPath, filename));
  220. }
  221. }
  222. if (ConfigBreakBeforeLoadAssemblies.Value)
  223. {
  224. Logger.LogInfo($"BepInEx is about load the following assemblies:\n{String.Join("\n", patchedAssemblies.ToArray())}");
  225. Logger.LogInfo($"The assemblies were dumped into {DumpedAssembliesPath}");
  226. Logger.LogInfo("Load any assemblies into the debugger, set breakpoints and continue execution.");
  227. Debugger.Break();
  228. }
  229. foreach (var kv in assemblies)
  230. {
  231. string filename = kv.Key;
  232. var assembly = kv.Value;
  233. // Note that since we only *load* assemblies, they shouldn't trigger dependency loading
  234. // Not loading all assemblies is very important not only because of memory reasons,
  235. // but because some games *rely* on that because of messed up internal dependencies.
  236. if (patchedAssemblies.Contains(filename))
  237. Load(assembly, filename);
  238. // Though we have to dispose of all assemblies regardless of them being patched or not
  239. assembly.Dispose();
  240. }
  241. //run all finalizers
  242. FinalizePatching();
  243. }
  244. /// <summary>
  245. /// Loads an individual assembly definition into the CLR.
  246. /// </summary>
  247. /// <param name="assembly">The assembly to load.</param>
  248. public static void Load(AssemblyDefinition assembly, string filename)
  249. {
  250. if (ConfigLoadDumpedAssemblies.Value)
  251. Assembly.LoadFile(Path.Combine(DumpedAssembliesPath, filename));
  252. else
  253. using (var assemblyStream = new MemoryStream())
  254. {
  255. assembly.Write(assemblyStream);
  256. Assembly.Load(assemblyStream.ToArray());
  257. }
  258. }
  259. #region Config
  260. private static readonly ConfigEntry<bool> ConfigDumpAssemblies = ConfigFile.CoreConfig.Bind(
  261. "Preloader", "DumpAssemblies",
  262. false,
  263. "If enabled, BepInEx will save patched assemblies into BepInEx/DumpedAssemblies.\nThis can be used by developers to inspect and debug preloader patchers.");
  264. private static readonly ConfigEntry<bool> ConfigLoadDumpedAssemblies = ConfigFile.CoreConfig.Bind(
  265. "Preloader", "LoadDumpedAssemblies",
  266. false,
  267. "If enabled, BepInEx will load patched assemblies from BepInEx/DumpedAssemblies instead of memory.\nThis can be used to be able to load patched assemblies into debuggers like dnSpy.\nIf set to true, will override DumpAssemblies.");
  268. private static readonly ConfigEntry<bool> ConfigBreakBeforeLoadAssemblies = ConfigFile.CoreConfig.Bind(
  269. "Preloader", "BreakBeforeLoadAssemblies",
  270. false,
  271. "If enabled, BepInEx will call Debugger.Break() once before loading patched assemblies.\nThis can be used with debuggers like dnSpy to install breakpoints into patched assemblies before they are loaded.");
  272. #endregion
  273. }
  274. }