AssemblyPatcher.cs 5.7 KB

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