AssemblyPatcher.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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.Configuration;
  8. using BepInEx.Logging;
  9. using BepInEx.Preloader.RuntimeFixes;
  10. using Mono.Cecil;
  11. namespace BepInEx.Preloader.Patching
  12. {
  13. /// <summary>
  14. /// Delegate used in patching assemblies.
  15. /// </summary>
  16. /// <param name="assembly">The assembly that is being patched.</param>
  17. internal delegate void AssemblyPatcherDelegate(ref AssemblyDefinition assembly);
  18. /// <summary>
  19. /// Worker class which is used for loading and patching entire folders of assemblies, or alternatively patching and
  20. /// loading assemblies one at a time.
  21. /// </summary>
  22. internal static class AssemblyPatcher
  23. {
  24. public static List<PatcherPlugin> PatcherPlugins { get; } = new List<PatcherPlugin>();
  25. private static readonly string DumpedAssembliesPath = Path.Combine(Paths.BepInExRootPath, "DumpedAssemblies");
  26. /// <summary>
  27. /// Adds a single assembly patcher to the pool of applicable patches.
  28. /// </summary>
  29. /// <param name="patcher">Patcher to apply.</param>
  30. public static void AddPatcher(PatcherPlugin patcher)
  31. {
  32. PatcherPlugins.Add(patcher);
  33. }
  34. /// <summary>
  35. /// Adds all patchers from all managed assemblies specified in a directory.
  36. /// </summary>
  37. /// <param name="directory">Directory to search patcher DLLs from.</param>
  38. /// <param name="patcherLocator">A function that locates assembly patchers in a given managed assembly.</param>
  39. public static void AddPatchersFromDirectory(string directory,
  40. Func<Assembly, List<PatcherPlugin>> patcherLocator)
  41. {
  42. if (!Directory.Exists(directory))
  43. return;
  44. var sortedPatchers = new SortedDictionary<string, PatcherPlugin>();
  45. foreach (string assemblyPath in Directory.GetFiles(directory, "*.dll", SearchOption.AllDirectories))
  46. try
  47. {
  48. var assembly = Assembly.LoadFrom(assemblyPath);
  49. foreach (var patcher in patcherLocator(assembly))
  50. sortedPatchers.Add(patcher.Name, patcher);
  51. }
  52. catch (BadImageFormatException) { } //unmanaged DLL
  53. catch (ReflectionTypeLoadException) { } //invalid references
  54. foreach (KeyValuePair<string, PatcherPlugin> patcher in sortedPatchers)
  55. AddPatcher(patcher.Value);
  56. }
  57. private static void InitializePatchers()
  58. {
  59. foreach (var assemblyPatcher in PatcherPlugins)
  60. assemblyPatcher.Initializer?.Invoke();
  61. }
  62. private static void FinalizePatching()
  63. {
  64. foreach (var assemblyPatcher in PatcherPlugins)
  65. assemblyPatcher.Finalizer?.Invoke();
  66. }
  67. /// <summary>
  68. /// Releases all patchers to let them be collected by GC.
  69. /// </summary>
  70. public static void DisposePatchers()
  71. {
  72. PatcherPlugins.Clear();
  73. }
  74. /// <summary>
  75. /// Applies patchers to all assemblies in the given directory and loads patched assemblies into memory.
  76. /// </summary>
  77. /// <param name="directory">Directory to load CLR assemblies from.</param>
  78. public static void PatchAndLoad(string directory)
  79. {
  80. // First, load patchable assemblies into Cecil
  81. var assemblies = new Dictionary<string, AssemblyDefinition>();
  82. foreach (string assemblyPath in Directory.GetFiles(directory, "*.dll"))
  83. {
  84. var assembly = AssemblyDefinition.ReadAssembly(assemblyPath);
  85. //NOTE: this is special cased here because the dependency handling for System.dll is a bit wonky
  86. //System has an assembly reference to itself, and it also has a reference to Mono.Security causing a circular dependency
  87. //It's also generally dangerous to change system.dll since so many things rely on it,
  88. // and it's already loaded into the appdomain since this loader references it, so we might as well skip it
  89. if (assembly.Name.Name == "System" || assembly.Name.Name == "mscorlib") //mscorlib is already loaded into the appdomain so it can't be patched
  90. {
  91. assembly.Dispose();
  92. continue;
  93. }
  94. if (UnityPatches.AssemblyLocations.ContainsKey(assembly.FullName))
  95. {
  96. Logger.LogWarning($"Tried to load duplicate assembly {Path.GetFileName(assemblyPath)} from Managed folder! Skipping...");
  97. continue;
  98. }
  99. assemblies.Add(Path.GetFileName(assemblyPath), assembly);
  100. UnityPatches.AssemblyLocations.Add(assembly.FullName, Path.GetFullPath(assemblyPath));
  101. }
  102. // Next, initialize all the patchers
  103. InitializePatchers();
  104. // Then, perform the actual patching
  105. var patchedAssemblies = new HashSet<string>();
  106. foreach (var assemblyPatcher in PatcherPlugins)
  107. foreach (string targetDll in assemblyPatcher.TargetDLLs)
  108. if (assemblies.TryGetValue(targetDll, out var assembly))
  109. {
  110. Logger.LogInfo($"Patching [{assembly.Name.Name}] with [{assemblyPatcher.Name}]");
  111. assemblyPatcher.Patcher?.Invoke(ref assembly);
  112. assemblies[targetDll] = assembly;
  113. patchedAssemblies.Add(targetDll);
  114. }
  115. // Finally, load patched assemblies into memory
  116. if (ConfigDumpAssemblies.Value || ConfigLoadDumpedAssemblies.Value)
  117. {
  118. if (!Directory.Exists(DumpedAssembliesPath))
  119. Directory.CreateDirectory(DumpedAssembliesPath);
  120. foreach (KeyValuePair<string, AssemblyDefinition> kv in assemblies)
  121. {
  122. string filename = kv.Key;
  123. var assembly = kv.Value;
  124. if (patchedAssemblies.Contains(filename))
  125. assembly.Write(Path.Combine(DumpedAssembliesPath, filename));
  126. }
  127. }
  128. if (ConfigBreakBeforeLoadAssemblies.Value)
  129. {
  130. Logger.LogInfo($"BepInEx is about load the following assemblies:\n{string.Join("\n", patchedAssemblies.ToArray())}");
  131. Logger.LogInfo($"The assemblies were dumped into {DumpedAssembliesPath}");
  132. Logger.LogInfo("Load any assemblies into the debugger, set breakpoints and continue execution.");
  133. Debugger.Break();
  134. }
  135. foreach (var kv in assemblies)
  136. {
  137. string filename = kv.Key;
  138. var assembly = kv.Value;
  139. // Note that since we only *load* assemblies, they shouldn't trigger dependency loading
  140. // Not loading all assemblies is very important not only because of memory reasons,
  141. // but because some games *rely* on that because of messed up internal dependencies.
  142. if (patchedAssemblies.Contains(filename))
  143. Load(assembly, filename);
  144. // Though we have to dispose of all assemblies regardless of them being patched or not
  145. assembly.Dispose();
  146. }
  147. //run all finalizers
  148. FinalizePatching();
  149. }
  150. /// <summary>
  151. /// Loads an individual assembly definition into the CLR.
  152. /// </summary>
  153. /// <param name="assembly">The assembly to load.</param>
  154. public static void Load(AssemblyDefinition assembly, string filename)
  155. {
  156. if (ConfigLoadDumpedAssemblies.Value)
  157. Assembly.LoadFile(Path.Combine(DumpedAssembliesPath, filename));
  158. else
  159. using (var assemblyStream = new MemoryStream())
  160. {
  161. assembly.Write(assemblyStream);
  162. Assembly.Load(assemblyStream.ToArray());
  163. }
  164. }
  165. #region Config
  166. private static readonly ConfigWrapper<bool> ConfigDumpAssemblies = ConfigFile.CoreConfig.Wrap(
  167. "Preloader",
  168. "DumpAssemblies",
  169. "If enabled, BepInEx will save patched assemblies into BepInEx/DumpedAssemblies.\nThis can be used by developers to inspect and debug preloader patchers.",
  170. false);
  171. private static readonly ConfigWrapper<bool> ConfigLoadDumpedAssemblies = ConfigFile.CoreConfig.Wrap(
  172. "Preloader",
  173. "LoadDumpedAssemblies",
  174. "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.",
  175. false);
  176. private static readonly ConfigWrapper<bool> ConfigBreakBeforeLoadAssemblies = ConfigFile.CoreConfig.Wrap(
  177. "Preloader",
  178. "BreakBeforeLoadAssemblies",
  179. "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.",
  180. false);
  181. #endregion
  182. }
  183. }