AssemblyPatcher.cs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  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. public static void PatchAll(string directory, IDictionary<AssemblyPatcherDelegate, IEnumerable<string>> patcherMethodDictionary, IEnumerable<Action> Initializers = null, IEnumerable<Action> Finalizers = null)
  30. {
  31. //run all initializers
  32. if (Initializers != null)
  33. foreach (Action init in Initializers)
  34. init.Invoke();
  35. //load all the requested assemblies
  36. List<AssemblyDefinition> assemblies = new List<AssemblyDefinition>();
  37. Dictionary<AssemblyDefinition, string> assemblyFilenames = new Dictionary<AssemblyDefinition, string>();
  38. foreach (string assemblyPath in Directory.GetFiles(directory, "*.dll"))
  39. {
  40. var assembly = AssemblyDefinition.ReadAssembly(assemblyPath);
  41. //NOTE: this is special cased here because the dependency handling for System.dll is a bit wonky
  42. //System has an assembly reference to itself, and it also has a reference to Mono.Security causing a circular dependency
  43. //It's also generally dangerous to change system.dll since so many things rely on it,
  44. // and it's already loaded into the appdomain since this loader references it, so we might as well skip it
  45. if (assembly.Name.Name == "System"
  46. || assembly.Name.Name == "mscorlib") //mscorlib is already loaded into the appdomain so it can't be patched
  47. {
  48. #if CECIL_10
  49. assembly.Dispose();
  50. #endif
  51. continue;
  52. }
  53. assemblies.Add(assembly);
  54. assemblyFilenames[assembly] = Path.GetFileName(assemblyPath);
  55. }
  56. //generate a dictionary of each assembly's dependencies
  57. Dictionary<AssemblyDefinition, IList<AssemblyDefinition>> assemblyDependencyDict = new Dictionary<AssemblyDefinition, IList<AssemblyDefinition>>();
  58. foreach (AssemblyDefinition assembly in assemblies)
  59. {
  60. assemblyDependencyDict[assembly] = new List<AssemblyDefinition>();
  61. foreach (var dependencyRef in assembly.MainModule.AssemblyReferences)
  62. {
  63. var dependencyAssembly = assemblies.FirstOrDefault(x => x.FullName == dependencyRef.FullName);
  64. if (dependencyAssembly != null)
  65. assemblyDependencyDict[assembly].Add(dependencyAssembly);
  66. }
  67. }
  68. //sort the assemblies so load the assemblies that are dependant upon first
  69. AssemblyDefinition[] sortedAssemblies = Utility.TopologicalSort(assemblies, x => assemblyDependencyDict[x]).ToArray();
  70. List<string> sortedAssemblyFilenames = sortedAssemblies.Select(x => assemblyFilenames[x]).ToList();
  71. //call the patchers on the assemblies
  72. foreach (var patcherMethod in patcherMethodDictionary)
  73. {
  74. foreach (string assemblyFilename in patcherMethod.Value)
  75. {
  76. int index = sortedAssemblyFilenames.FindIndex(x => x == assemblyFilename);
  77. if (index < 0)
  78. continue;
  79. Patch(ref sortedAssemblies[index], patcherMethod.Key);
  80. }
  81. }
  82. for (int i = 0; i < sortedAssemblies.Length; i++)
  83. {
  84. string filename = Path.GetFileName(assemblyFilenames[sortedAssemblies[i]]);
  85. if (DumpingEnabled)
  86. {
  87. using (MemoryStream mem = new MemoryStream())
  88. {
  89. string dirPath = Path.Combine(Preloader.PluginPath, "DumpedAssemblies");
  90. if (!Directory.Exists(dirPath))
  91. Directory.CreateDirectory(dirPath);
  92. sortedAssemblies[i].Write(mem);
  93. File.WriteAllBytes(Path.Combine(dirPath, filename), mem.ToArray());
  94. }
  95. }
  96. Load(sortedAssemblies[i]);
  97. #if CECIL_10
  98. sortedAssemblies[i].Dispose();
  99. #endif
  100. }
  101. //run all finalizers
  102. if (Finalizers != null)
  103. foreach (Action finalizer in Finalizers)
  104. finalizer.Invoke();
  105. }
  106. /// <summary>
  107. /// Patches an individual assembly, without loading it.
  108. /// </summary>
  109. /// <param name="assembly">The assembly definition to apply the patch to.</param>
  110. /// <param name="patcherMethod">The patcher to use to patch the assembly definition.</param>
  111. public static void Patch(ref AssemblyDefinition assembly, AssemblyPatcherDelegate patcherMethod)
  112. {
  113. patcherMethod.Invoke(ref assembly);
  114. }
  115. /// <summary>
  116. /// Loads an individual assembly defintion into the CLR.
  117. /// </summary>
  118. /// <param name="assembly">The assembly to load.</param>
  119. public static void Load(AssemblyDefinition assembly)
  120. {
  121. using (MemoryStream assemblyStream = new MemoryStream())
  122. {
  123. assembly.Write(assemblyStream);
  124. Assembly.Load(assemblyStream.ToArray());
  125. }
  126. }
  127. }
  128. }