AssemblyPatcher.cs 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Reflection;
  5. using BepInEx.Logging;
  6. using Mono.Cecil;
  7. namespace BepInEx.Preloader.Patcher
  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. private static readonly List<PatcherPlugin> patchers = 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. patchers.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 patchers)
  60. assemblyPatcher.Initializer?.Invoke();
  61. }
  62. private static void FinalizePatching()
  63. {
  64. foreach (var assemblyPatcher in patchers)
  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. patchers.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.Log(LogLevel.Warning,
  99. $"Tried to load duplicate assembly {Path.GetFileName(assemblyPath)} from Managed folder! Skipping...");
  100. continue;
  101. }
  102. assemblies.Add(Path.GetFileName(assemblyPath), assembly);
  103. UnityPatches.AssemblyLocations.Add(assembly.FullName, Path.GetFullPath(assemblyPath));
  104. }
  105. // Next, initialize all the patchers
  106. InitializePatchers();
  107. // Then, perform the actual patching
  108. var patchedAssemblies = new HashSet<string>();
  109. foreach (var assemblyPatcher in patchers)
  110. foreach (string targetDll in assemblyPatcher.TargetDLLs)
  111. if (assemblies.TryGetValue(targetDll, out var assembly))
  112. {
  113. assemblyPatcher.Patcher?.Invoke(ref assembly);
  114. assemblies[targetDll] = assembly;
  115. patchedAssemblies.Add(targetDll);
  116. }
  117. // Finally, load all assemblies into memory
  118. foreach (KeyValuePair<string, AssemblyDefinition> kv in assemblies)
  119. {
  120. string filename = kv.Key;
  121. var assembly = kv.Value;
  122. if (DumpingEnabled && patchedAssemblies.Contains(filename))
  123. using (var mem = new MemoryStream())
  124. {
  125. string dirPath = Path.Combine(Paths.PluginPath, "DumpedAssemblies");
  126. if (!Directory.Exists(dirPath))
  127. Directory.CreateDirectory(dirPath);
  128. assembly.Write(mem);
  129. File.WriteAllBytes(Path.Combine(dirPath, filename), mem.ToArray());
  130. }
  131. Load(assembly);
  132. assembly.Dispose();
  133. }
  134. //run all finalizers
  135. FinalizePatching();
  136. }
  137. /// <summary>
  138. /// Loads an individual assembly defintion into the CLR.
  139. /// </summary>
  140. /// <param name="assembly">The assembly to load.</param>
  141. public static void Load(AssemblyDefinition assembly)
  142. {
  143. using (var assemblyStream = new MemoryStream())
  144. {
  145. assembly.Write(assemblyStream);
  146. Assembly.Load(assemblyStream.ToArray());
  147. }
  148. }
  149. }
  150. }