AssemblyPatcher.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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"
  90. || assembly.Name.Name == "mscorlib"
  91. ) //mscorlib is already loaded into the appdomain so it can't be patched
  92. {
  93. assembly.Dispose();
  94. continue;
  95. }
  96. if (UnityPatches.AssemblyLocations.ContainsKey(assembly.FullName))
  97. {
  98. Logger.LogWarning($"Tried to load duplicate assembly {Path.GetFileName(assemblyPath)} from Managed folder! Skipping...");
  99. continue;
  100. }
  101. assemblies.Add(Path.GetFileName(assemblyPath), assembly);
  102. UnityPatches.AssemblyLocations.Add(assembly.FullName, Path.GetFullPath(assemblyPath));
  103. }
  104. // Next, initialize all the patchers
  105. InitializePatchers();
  106. // Then, perform the actual patching
  107. var patchedAssemblies = new HashSet<string>();
  108. foreach (var assemblyPatcher in PatcherPlugins)
  109. foreach (string targetDll in assemblyPatcher.TargetDLLs)
  110. if (assemblies.TryGetValue(targetDll, out var assembly))
  111. {
  112. Logger.LogInfo($"Patching [{assembly.Name.Name}] with [{assemblyPatcher.Name}]");
  113. assemblyPatcher.Patcher?.Invoke(ref assembly);
  114. assemblies[targetDll] = assembly;
  115. patchedAssemblies.Add(targetDll);
  116. }
  117. // Finally, load patched assemblies into memory
  118. if (ConfigDumpAssemblies.Value || ConfigLoadDumpedAssemblies.Value)
  119. {
  120. if (!Directory.Exists(DumpedAssembliesPath))
  121. Directory.CreateDirectory(DumpedAssembliesPath);
  122. foreach (KeyValuePair<string, AssemblyDefinition> kv in assemblies)
  123. {
  124. string filename = kv.Key;
  125. var assembly = kv.Value;
  126. if (patchedAssemblies.Contains(filename))
  127. assembly.Write(Path.Combine(DumpedAssembliesPath, filename));
  128. }
  129. }
  130. if (ConfigBreakBeforeLoadAssemblies.Value)
  131. {
  132. Logger.LogInfo($"BepInEx is about load the following assemblies:\n{string.Join("\n", patchedAssemblies.ToArray())}");
  133. Logger.LogInfo($"The assemblies were dumped into {DumpedAssembliesPath}");
  134. Logger.LogInfo("Load any assemblies into the debugger, set breakpoints and continue execution.");
  135. Debugger.Break();
  136. }
  137. foreach (var kv in assemblies)
  138. {
  139. string filename = kv.Key;
  140. var assembly = kv.Value;
  141. // Note that since we only *load* assemblies, they shouldn't trigger dependency loading
  142. // Not loading all assemblies is very important not only because of memory reasons,
  143. // but because some games *rely* on that because of messed up internal dependencies.
  144. if (patchedAssemblies.Contains(filename))
  145. Load(assembly, filename);
  146. // Though we have to dispose of all assemblies regardless of them being patched or not
  147. assembly.Dispose();
  148. }
  149. //run all finalizers
  150. FinalizePatching();
  151. }
  152. /// <summary>
  153. /// Loads an individual assembly definition into the CLR.
  154. /// </summary>
  155. /// <param name="assembly">The assembly to load.</param>
  156. public static void Load(AssemblyDefinition assembly, string filename)
  157. {
  158. if (ConfigLoadDumpedAssemblies.Value)
  159. Assembly.LoadFile(Path.Combine(DumpedAssembliesPath, filename));
  160. else
  161. using (var assemblyStream = new MemoryStream())
  162. {
  163. assembly.Write(assemblyStream);
  164. Assembly.Load(assemblyStream.ToArray());
  165. }
  166. }
  167. #region Config
  168. private static readonly ConfigWrapper<bool> ConfigDumpAssemblies = ConfigFile.CoreConfig.Wrap(
  169. "Preloader",
  170. "DumpAssemblies",
  171. "If enabled, BepInEx will save patched assemblies into BepInEx/DumpedAssemblies.\nThis can be used by developers to inspect and debug preloader patchers.",
  172. false);
  173. private static readonly ConfigWrapper<bool> ConfigLoadDumpedAssemblies = ConfigFile.CoreConfig.Wrap(
  174. "Preloader",
  175. "LoadDumpedAssemblies",
  176. "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.",
  177. false);
  178. private static readonly ConfigWrapper<bool> ConfigBreakBeforeLoadAssemblies = ConfigFile.CoreConfig.Wrap(
  179. "Preloader",
  180. "BreakBeforeLoadAssemblies",
  181. "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.",
  182. false);
  183. #endregion
  184. }
  185. }