AssemblyPatcher.cs 5.1 KB

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