AssemblyPatcher.cs 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Reflection;
  6. using BepInEx.Common;
  7. using Mono.Cecil;
  8. namespace BepInEx.Bootstrap
  9. {
  10. /// <summary>
  11. /// Delegate used in patching assemblies.
  12. /// </summary>
  13. /// <param name="assembly">The assembly that is being patched.</param>
  14. public 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 loading assemblies one at a time.
  17. /// </summary>
  18. public static class AssemblyPatcher
  19. {
  20. /// <summary>
  21. /// Configuration value of whether assembly dumping is enabled or not.
  22. /// </summary>
  23. private static bool DumpingEnabled => bool.TryParse(Config.GetEntry("preloader-dumpassemblies", "false"), out bool result) ? result : false;
  24. /// <summary>
  25. /// Patches and loads an entire directory of assemblies.
  26. /// </summary>
  27. /// <param name="directory">The directory to load assemblies from.</param>
  28. /// <param name="patcherMethodDictionary">The dictionary of patchers and their targeted assembly filenames which they are patching.</param>
  29. /// <param name="initializers">List of initializers to run before any patching starts</param>
  30. /// <param name="finalizers">List of finalizers to run before returning</param>
  31. public static void PatchAll(string directory, IDictionary<AssemblyPatcherDelegate, IEnumerable<string>> patcherMethodDictionary, IEnumerable<Action> initializers = null, IEnumerable<Action> finalizers = null)
  32. {
  33. //run all initializers
  34. if (initializers != null)
  35. foreach (Action init in initializers)
  36. init.Invoke();
  37. //load all the requested assemblies
  38. List<AssemblyDefinition> assemblies = new List<AssemblyDefinition>();
  39. Dictionary<AssemblyDefinition, string> assemblyFilenames = new Dictionary<AssemblyDefinition, string>();
  40. foreach (string assemblyPath in Directory.GetFiles(directory, "*.dll"))
  41. {
  42. var assembly = AssemblyDefinition.ReadAssembly(assemblyPath);
  43. //NOTE: this is special cased here because the dependency handling for System.dll is a bit wonky
  44. //System has an assembly reference to itself, and it also has a reference to Mono.Security causing a circular dependency
  45. //It's also generally dangerous to change system.dll since so many things rely on it,
  46. // and it's already loaded into the appdomain since this loader references it, so we might as well skip it
  47. if (assembly.Name.Name == "System"
  48. || assembly.Name.Name == "mscorlib") //mscorlib is already loaded into the appdomain so it can't be patched
  49. {
  50. #if CECIL_10
  51. assembly.Dispose();
  52. #endif
  53. continue;
  54. }
  55. assemblies.Add(assembly);
  56. assemblyFilenames[assembly] = Path.GetFileName(assemblyPath);
  57. }
  58. //generate a dictionary of each assembly's dependencies
  59. Dictionary<AssemblyDefinition, IList<AssemblyDefinition>> assemblyDependencyDict = new Dictionary<AssemblyDefinition, IList<AssemblyDefinition>>();
  60. foreach (AssemblyDefinition assembly in assemblies)
  61. {
  62. assemblyDependencyDict[assembly] = new List<AssemblyDefinition>();
  63. foreach (var dependencyRef in assembly.MainModule.AssemblyReferences)
  64. {
  65. var dependencyAssembly = assemblies.FirstOrDefault(x => x.FullName == dependencyRef.FullName);
  66. if (dependencyAssembly != null)
  67. assemblyDependencyDict[assembly].Add(dependencyAssembly);
  68. }
  69. }
  70. //sort the assemblies so load the assemblies that are dependant upon first
  71. AssemblyDefinition[] sortedAssemblies = Utility.TopologicalSort(assemblies, x => assemblyDependencyDict[x]).ToArray();
  72. Dictionary<string, AssemblyDefinition> sortedAssemblyFilenames = sortedAssemblies.ToDictionary(ass => assemblyFilenames[ass]);
  73. HashSet<string> patchedAssemblies = new HashSet<string>();
  74. //call the patchers on the assemblies
  75. foreach (var patcherMethod in patcherMethodDictionary)
  76. {
  77. foreach (string assemblyFilename in patcherMethod.Value)
  78. {
  79. if (sortedAssemblyFilenames.TryGetValue(assemblyFilename, out var assembly))
  80. {
  81. Patch(ref assembly, patcherMethod.Key);
  82. patchedAssemblies.Add(assemblyFilenames[assembly]);
  83. }
  84. }
  85. }
  86. // Finally, load all assemblies into memory
  87. foreach (var assembly in sortedAssemblies)
  88. {
  89. string filename = Path.GetFileName(assemblyFilenames[assembly]);
  90. if (DumpingEnabled && patchedAssemblies.Contains(filename))
  91. {
  92. using (MemoryStream mem = new MemoryStream())
  93. {
  94. string dirPath = Path.Combine(Preloader.PluginPath, "DumpedAssemblies");
  95. if (!Directory.Exists(dirPath))
  96. Directory.CreateDirectory(dirPath);
  97. assembly.Write(mem);
  98. File.WriteAllBytes(Path.Combine(dirPath, filename), mem.ToArray());
  99. }
  100. }
  101. Load(assembly);
  102. #if CECIL_10
  103. assembly.Dispose();
  104. #endif
  105. }
  106. //run all finalizers
  107. if (finalizers != null)
  108. foreach (Action finalizer in finalizers)
  109. finalizer.Invoke();
  110. }
  111. /// <summary>
  112. /// Patches an individual assembly, without loading it.
  113. /// </summary>
  114. /// <param name="assembly">The assembly definition to apply the patch to.</param>
  115. /// <param name="patcherMethod">The patcher to use to patch the assembly definition.</param>
  116. public static void Patch(ref AssemblyDefinition assembly, AssemblyPatcherDelegate patcherMethod)
  117. {
  118. patcherMethod.Invoke(ref assembly);
  119. }
  120. /// <summary>
  121. /// Loads an individual assembly defintion into the CLR.
  122. /// </summary>
  123. /// <param name="assembly">The assembly to load.</param>
  124. public static void Load(AssemblyDefinition assembly)
  125. {
  126. using (MemoryStream assemblyStream = new MemoryStream())
  127. {
  128. assembly.Write(assemblyStream);
  129. Assembly.Load(assemblyStream.ToArray());
  130. }
  131. }
  132. }
  133. }