AssemblyPatcher.cs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Reflection;
  5. using Harmony;
  6. using Mono.Cecil;
  7. namespace BepInEx.Bootstrap
  8. {
  9. /// <summary>
  10. /// Delegate used in patching assemblies.
  11. /// </summary>
  12. /// <param name="assembly">The assembly that is being patched.</param>
  13. public delegate void AssemblyPatcherDelegate(ref AssemblyDefinition assembly);
  14. /// <summary>
  15. /// Worker class which is used for loading and patching entire folders of assemblies, or alternatively patching and loading assemblies one at a time.
  16. /// </summary>
  17. public static class AssemblyPatcher
  18. {
  19. /// <summary>
  20. /// Configuration value of whether assembly dumping is enabled or not.
  21. /// </summary>
  22. private static bool DumpingEnabled => Utility.SafeParseBool(Config.GetEntry("dump-assemblies", "false", "Preloader"));
  23. /// <summary>
  24. /// Patches and loads an entire directory of assemblies.
  25. /// </summary>
  26. /// <param name="directory">The directory to load assemblies from.</param>
  27. /// <param name="patcherMethodDictionary">The dictionary of patchers and their targeted assembly filenames which they are patching.</param>
  28. /// <param name="initializers">List of initializers to run before any patching starts</param>
  29. /// <param name="finalizers">List of finalizers to run before returning</param>
  30. public static void PatchAll(string directory, IDictionary<AssemblyPatcherDelegate, IEnumerable<string>> patcherMethodDictionary, IEnumerable<Action> initializers = null, IEnumerable<Action> finalizers = null)
  31. {
  32. //run all initializers
  33. if (initializers != null)
  34. foreach (Action init in initializers)
  35. init.Invoke();
  36. //load all the requested assemblies
  37. Dictionary<string, AssemblyDefinition> assemblies = new Dictionary<string, AssemblyDefinition>();
  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. assembly.Dispose();
  49. continue;
  50. }
  51. assemblies.Add(Path.GetFileName(assemblyPath), assembly);
  52. PatchedAssemblyResolver.AssemblyLocations.Add(assembly.FullName, Path.GetFullPath(assemblyPath));
  53. }
  54. HashSet<string> patchedAssemblies = new HashSet<string>();
  55. //call the patchers on the assemblies
  56. foreach (var patcherMethod in patcherMethodDictionary)
  57. {
  58. foreach (string assemblyFilename in patcherMethod.Value)
  59. {
  60. if (assemblies.TryGetValue(assemblyFilename, out var assembly))
  61. {
  62. Patch(ref assembly, patcherMethod.Key);
  63. assemblies[assemblyFilename] = assembly;
  64. patchedAssemblies.Add(assemblyFilename);
  65. }
  66. }
  67. }
  68. // Finally, load all assemblies into memory
  69. foreach (var kv in assemblies)
  70. {
  71. string filename = kv.Key;
  72. var assembly = kv.Value;
  73. if (DumpingEnabled && patchedAssemblies.Contains(filename))
  74. {
  75. using (MemoryStream mem = new MemoryStream())
  76. {
  77. string dirPath = Path.Combine(Paths.PluginPath, "DumpedAssemblies");
  78. if (!Directory.Exists(dirPath))
  79. Directory.CreateDirectory(dirPath);
  80. assembly.Write(mem);
  81. File.WriteAllBytes(Path.Combine(dirPath, filename), mem.ToArray());
  82. }
  83. }
  84. Load(assembly);
  85. assembly.Dispose();
  86. }
  87. // Patch Assembly.Location and Assembly.CodeBase only if the assemblies were loaded from memory
  88. PatchedAssemblyResolver.ApplyPatch();
  89. //run all finalizers
  90. if (finalizers != null)
  91. foreach (Action finalizer in finalizers)
  92. finalizer.Invoke();
  93. }
  94. /// <summary>
  95. /// Patches an individual assembly, without loading it.
  96. /// </summary>
  97. /// <param name="assembly">The assembly definition to apply the patch to.</param>
  98. /// <param name="patcherMethod">The patcher to use to patch the assembly definition.</param>
  99. public static void Patch(ref AssemblyDefinition assembly, AssemblyPatcherDelegate patcherMethod)
  100. {
  101. patcherMethod.Invoke(ref assembly);
  102. }
  103. /// <summary>
  104. /// Loads an individual assembly defintion into the CLR.
  105. /// </summary>
  106. /// <param name="assembly">The assembly to load.</param>
  107. public static void Load(AssemblyDefinition assembly)
  108. {
  109. using (MemoryStream assemblyStream = new MemoryStream())
  110. {
  111. assembly.Write(assemblyStream);
  112. Assembly.Load(assemblyStream.ToArray());
  113. }
  114. }
  115. }
  116. internal static class PatchedAssemblyResolver
  117. {
  118. public static Dictionary<string, string> AssemblyLocations { get; } = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
  119. public static void ApplyPatch()
  120. {
  121. HarmonyInstance.Create("com.bepis.bepinex.asmlocationfix").PatchAll(typeof(PatchedAssemblyResolver));
  122. }
  123. [HarmonyPatch(typeof(Assembly))]
  124. [HarmonyPatch(nameof(Assembly.Location), PropertyMethod.Getter)]
  125. [HarmonyPostfix]
  126. public static void GetLocation(ref string __result, Assembly __instance)
  127. {
  128. if (AssemblyLocations.TryGetValue(__instance.FullName, out string location))
  129. __result = location;
  130. }
  131. [HarmonyPatch(typeof(Assembly))]
  132. [HarmonyPatch(nameof(Assembly.CodeBase), PropertyMethod.Getter)]
  133. [HarmonyPostfix]
  134. public static void GetCodeBase(ref string __result, Assembly __instance)
  135. {
  136. if (AssemblyLocations.TryGetValue(__instance.FullName, out string location))
  137. __result = $"file://{location.Replace('\\', '/')}";
  138. }
  139. }
  140. }