AssemblyPatcher.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Reflection;
  7. using BepInEx.Bootstrap;
  8. using BepInEx.Configuration;
  9. using BepInEx.Logging;
  10. using BepInEx.Preloader.RuntimeFixes;
  11. using Mono.Cecil;
  12. namespace BepInEx.Preloader.Patching
  13. {
  14. /// <summary>
  15. /// Delegate used in patching assemblies.
  16. /// </summary>
  17. /// <param name="assembly">The assembly that is being patched.</param>
  18. internal delegate void AssemblyPatcherDelegate(ref AssemblyDefinition assembly);
  19. /// <summary>
  20. /// Worker class which is used for loading and patching entire folders of assemblies, or alternatively patching and
  21. /// loading assemblies one at a time.
  22. /// </summary>
  23. internal static class AssemblyPatcher
  24. {
  25. private const BindingFlags ALL = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.IgnoreCase;
  26. public static List<PatcherPlugin> PatcherPlugins { get; } = new List<PatcherPlugin>();
  27. private static readonly string DumpedAssembliesPath = Path.Combine(Paths.BepInExRootPath, "DumpedAssemblies");
  28. /// <summary>
  29. /// Adds a single assembly patcher to the pool of applicable patches.
  30. /// </summary>
  31. /// <param name="patcher">Patcher to apply.</param>
  32. public static void AddPatcher(PatcherPlugin patcher)
  33. {
  34. PatcherPlugins.Add(patcher);
  35. }
  36. private static T CreateDelegate<T>(MethodInfo method) where T : class => method != null ? Delegate.CreateDelegate(typeof(T), method) as T : null;
  37. /// <summary>
  38. /// Adds all patchers from all managed assemblies specified in a directory.
  39. /// </summary>
  40. /// <param name="directory">Directory to search patcher DLLs from.</param>
  41. /// <param name="patcherLocator">A function that locates assembly patchers in a given managed assembly.</param>
  42. public static void AddPatchersFromDirectory(string directory,
  43. Func<TypeDefinition, PatcherPlugin> patcherLocator)
  44. {
  45. if (!Directory.Exists(directory))
  46. return;
  47. var sortedPatchers = new SortedDictionary<string, PatcherPlugin>();
  48. var patchers = TypeLoader.FindPluginTypes(directory, patcherLocator);
  49. foreach (var keyValuePair in patchers)
  50. {
  51. var assembly = keyValuePair.Key;
  52. var patcherCollection = keyValuePair.Value;
  53. var ass = Assembly.LoadFile(assembly.MainModule.FileName);
  54. foreach (var patcherPlugin in patcherCollection)
  55. {
  56. try
  57. {
  58. var type = ass.GetType(patcherPlugin.Type.FullName);
  59. var methods = type.GetMethods(ALL);
  60. patcherPlugin.Initializer = CreateDelegate<Action>(methods.FirstOrDefault(m => m.Name.Equals("Initialize", StringComparison.InvariantCultureIgnoreCase) &&
  61. m.GetParameters().Length == 0 &&
  62. m.ReturnType == typeof(void)));
  63. patcherPlugin.Finalizer = CreateDelegate<Action>(methods.FirstOrDefault(m => m.Name.Equals("Finish", StringComparison.InvariantCultureIgnoreCase) &&
  64. m.GetParameters().Length == 0 &&
  65. m.ReturnType == typeof(void)));
  66. patcherPlugin.TargetDLLs = CreateDelegate<Func<IEnumerable<string>>>(type.GetProperty("TargetDLLs", ALL).GetGetMethod());
  67. var patcher = methods.FirstOrDefault(m => m.Name.Equals("Patch", StringComparison.CurrentCultureIgnoreCase) &&
  68. m.ReturnType == typeof(void) &&
  69. m.GetParameters().Length == 0 &&
  70. (m.GetParameters()[0].ParameterType == typeof(AssemblyDefinition) ||
  71. m.GetParameters()[0].ParameterType == typeof(AssemblyDefinition).MakeByRefType()));
  72. patcherPlugin.Patcher = (ref AssemblyDefinition pAss) =>
  73. {
  74. //we do the array fuckery here to get the ref result out
  75. object[] args = { pAss };
  76. patcher.Invoke(null, args);
  77. pAss = (AssemblyDefinition)args[0];
  78. };
  79. sortedPatchers.Add($"{ass.GetName().Name}/{type.FullName}", patcherPlugin);
  80. patcherPlugin.Type = null;
  81. }
  82. catch (Exception e)
  83. {
  84. Logger.LogError($"Failed to load patcher [{patcherPlugin.Type.FullName}]: {e.Message}");
  85. if (e is ReflectionTypeLoadException re)
  86. Logger.LogDebug(TypeLoader.TypeLoadExceptionToString(re));
  87. else
  88. Logger.LogDebug(e.ToString());
  89. }
  90. }
  91. Logger.Log(patcherCollection.Any() ? LogLevel.Info : LogLevel.Debug,
  92. $"Loaded {patcherCollection.Count} patcher methods from {assembly.Name.Name}");
  93. }
  94. foreach (KeyValuePair<string, PatcherPlugin> patcher in sortedPatchers)
  95. AddPatcher(patcher.Value);
  96. foreach (var assemblyDefinition in patchers.Keys)
  97. assemblyDefinition.Dispose();
  98. }
  99. private static void InitializePatchers()
  100. {
  101. foreach (var assemblyPatcher in PatcherPlugins)
  102. assemblyPatcher.Initializer?.Invoke();
  103. }
  104. private static void FinalizePatching()
  105. {
  106. foreach (var assemblyPatcher in PatcherPlugins)
  107. assemblyPatcher.Finalizer?.Invoke();
  108. }
  109. /// <summary>
  110. /// Releases all patchers to let them be collected by GC.
  111. /// </summary>
  112. public static void DisposePatchers()
  113. {
  114. PatcherPlugins.Clear();
  115. }
  116. /// <summary>
  117. /// Applies patchers to all assemblies in the given directory and loads patched assemblies into memory.
  118. /// </summary>
  119. /// <param name="directory">Directory to load CLR assemblies from.</param>
  120. public static void PatchAndLoad(string directory)
  121. {
  122. // First, load patchable assemblies into Cecil
  123. var assemblies = new Dictionary<string, AssemblyDefinition>();
  124. foreach (string assemblyPath in Directory.GetFiles(directory, "*.dll"))
  125. {
  126. var assembly = AssemblyDefinition.ReadAssembly(assemblyPath);
  127. //NOTE: this is special cased here because the dependency handling for System.dll is a bit wonky
  128. //System has an assembly reference to itself, and it also has a reference to Mono.Security causing a circular dependency
  129. //It's also generally dangerous to change system.dll since so many things rely on it,
  130. // and it's already loaded into the appdomain since this loader references it, so we might as well skip it
  131. if (assembly.Name.Name == "System" || assembly.Name.Name == "mscorlib") //mscorlib is already loaded into the appdomain so it can't be patched
  132. {
  133. assembly.Dispose();
  134. continue;
  135. }
  136. if (UnityPatches.AssemblyLocations.ContainsKey(assembly.FullName))
  137. {
  138. Logger.LogWarning($"Tried to load duplicate assembly {Path.GetFileName(assemblyPath)} from Managed folder! Skipping...");
  139. continue;
  140. }
  141. assemblies.Add(Path.GetFileName(assemblyPath), assembly);
  142. UnityPatches.AssemblyLocations.Add(assembly.FullName, Path.GetFullPath(assemblyPath));
  143. }
  144. // Next, initialize all the patchers
  145. InitializePatchers();
  146. // Then, perform the actual patching
  147. var patchedAssemblies = new HashSet<string>();
  148. foreach (var assemblyPatcher in PatcherPlugins)
  149. foreach (string targetDll in assemblyPatcher.TargetDLLs())
  150. if (assemblies.TryGetValue(targetDll, out var assembly))
  151. {
  152. Logger.LogInfo($"Patching [{assembly.Name.Name}] with [{assemblyPatcher.Name}]");
  153. assemblyPatcher.Patcher?.Invoke(ref assembly);
  154. assemblies[targetDll] = assembly;
  155. patchedAssemblies.Add(targetDll);
  156. }
  157. // Finally, load patched assemblies into memory
  158. if (ConfigDumpAssemblies.Value || ConfigLoadDumpedAssemblies.Value)
  159. {
  160. if (!Directory.Exists(DumpedAssembliesPath))
  161. Directory.CreateDirectory(DumpedAssembliesPath);
  162. foreach (KeyValuePair<string, AssemblyDefinition> kv in assemblies)
  163. {
  164. string filename = kv.Key;
  165. var assembly = kv.Value;
  166. if (patchedAssemblies.Contains(filename))
  167. assembly.Write(Path.Combine(DumpedAssembliesPath, filename));
  168. }
  169. }
  170. if (ConfigBreakBeforeLoadAssemblies.Value)
  171. {
  172. Logger.LogInfo($"BepInEx is about load the following assemblies:\n{string.Join("\n", patchedAssemblies.ToArray())}");
  173. Logger.LogInfo($"The assemblies were dumped into {DumpedAssembliesPath}");
  174. Logger.LogInfo("Load any assemblies into the debugger, set breakpoints and continue execution.");
  175. Debugger.Break();
  176. }
  177. foreach (var kv in assemblies)
  178. {
  179. string filename = kv.Key;
  180. var assembly = kv.Value;
  181. // Note that since we only *load* assemblies, they shouldn't trigger dependency loading
  182. // Not loading all assemblies is very important not only because of memory reasons,
  183. // but because some games *rely* on that because of messed up internal dependencies.
  184. if (patchedAssemblies.Contains(filename))
  185. Load(assembly, filename);
  186. // Though we have to dispose of all assemblies regardless of them being patched or not
  187. assembly.Dispose();
  188. }
  189. //run all finalizers
  190. FinalizePatching();
  191. }
  192. /// <summary>
  193. /// Loads an individual assembly definition into the CLR.
  194. /// </summary>
  195. /// <param name="assembly">The assembly to load.</param>
  196. public static void Load(AssemblyDefinition assembly, string filename)
  197. {
  198. if (ConfigLoadDumpedAssemblies.Value)
  199. Assembly.LoadFile(Path.Combine(DumpedAssembliesPath, filename));
  200. else
  201. using (var assemblyStream = new MemoryStream())
  202. {
  203. assembly.Write(assemblyStream);
  204. Assembly.Load(assemblyStream.ToArray());
  205. }
  206. }
  207. #region Config
  208. private static readonly ConfigWrapper<bool> ConfigDumpAssemblies = ConfigFile.CoreConfig.Wrap(
  209. "Preloader",
  210. "DumpAssemblies",
  211. "If enabled, BepInEx will save patched assemblies into BepInEx/DumpedAssemblies.\nThis can be used by developers to inspect and debug preloader patchers.",
  212. false);
  213. private static readonly ConfigWrapper<bool> ConfigLoadDumpedAssemblies = ConfigFile.CoreConfig.Wrap(
  214. "Preloader",
  215. "LoadDumpedAssemblies",
  216. "If enabled, BepInEx will load patched assemblies from BepInEx/DumpedAssemblies instead of memory.\nThis can be used to be able to load patched assemblies into debuggers like dnSpy.\nIf set to true, will override DumpAssemblies.",
  217. false);
  218. private static readonly ConfigWrapper<bool> ConfigBreakBeforeLoadAssemblies = ConfigFile.CoreConfig.Wrap(
  219. "Preloader",
  220. "BreakBeforeLoadAssemblies",
  221. "If enabled, BepInEx will call Debugger.Break() once before loading patched assemblies.\nThis can be used with debuggers like dnSpy to install breakpoints into patched assemblies before they are loaded.",
  222. false);
  223. #endregion
  224. }
  225. }