AssemblyPatcher.cs 6.2 KB

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