AssemblyPatcher.cs 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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. }
  92. foreach (KeyValuePair<string, PatcherPlugin> patcher in sortedPatchers)
  93. AddPatcher(patcher.Value);
  94. foreach (var assemblyDefinition in patchers.Keys)
  95. assemblyDefinition.Dispose();
  96. }
  97. private static void InitializePatchers()
  98. {
  99. foreach (var assemblyPatcher in PatcherPlugins)
  100. assemblyPatcher.Initializer?.Invoke();
  101. }
  102. private static void FinalizePatching()
  103. {
  104. foreach (var assemblyPatcher in PatcherPlugins)
  105. assemblyPatcher.Finalizer?.Invoke();
  106. }
  107. /// <summary>
  108. /// Releases all patchers to let them be collected by GC.
  109. /// </summary>
  110. public static void DisposePatchers()
  111. {
  112. PatcherPlugins.Clear();
  113. }
  114. /// <summary>
  115. /// Applies patchers to all assemblies in the given directory and loads patched assemblies into memory.
  116. /// </summary>
  117. /// <param name="directory">Directory to load CLR assemblies from.</param>
  118. public static void PatchAndLoad(string directory)
  119. {
  120. // First, load patchable assemblies into Cecil
  121. var assemblies = new Dictionary<string, AssemblyDefinition>();
  122. foreach (string assemblyPath in Directory.GetFiles(directory, "*.dll"))
  123. {
  124. var assembly = AssemblyDefinition.ReadAssembly(assemblyPath);
  125. //NOTE: this is special cased here because the dependency handling for System.dll is a bit wonky
  126. //System has an assembly reference to itself, and it also has a reference to Mono.Security causing a circular dependency
  127. //It's also generally dangerous to change system.dll since so many things rely on it,
  128. // and it's already loaded into the appdomain since this loader references it, so we might as well skip it
  129. if (assembly.Name.Name == "System" || assembly.Name.Name == "mscorlib") //mscorlib is already loaded into the appdomain so it can't be patched
  130. {
  131. assembly.Dispose();
  132. continue;
  133. }
  134. if (UnityPatches.AssemblyLocations.ContainsKey(assembly.FullName))
  135. {
  136. Logger.LogWarning($"Tried to load duplicate assembly {Path.GetFileName(assemblyPath)} from Managed folder! Skipping...");
  137. continue;
  138. }
  139. assemblies.Add(Path.GetFileName(assemblyPath), assembly);
  140. UnityPatches.AssemblyLocations.Add(assembly.FullName, Path.GetFullPath(assemblyPath));
  141. }
  142. // Next, initialize all the patchers
  143. InitializePatchers();
  144. // Then, perform the actual patching
  145. var patchedAssemblies = new HashSet<string>();
  146. foreach (var assemblyPatcher in PatcherPlugins)
  147. foreach (string targetDll in assemblyPatcher.TargetDLLs())
  148. if (assemblies.TryGetValue(targetDll, out var assembly))
  149. {
  150. Logger.LogInfo($"Patching [{assembly.Name.Name}] with [{assemblyPatcher.Name}]");
  151. assemblyPatcher.Patcher?.Invoke(ref assembly);
  152. assemblies[targetDll] = assembly;
  153. patchedAssemblies.Add(targetDll);
  154. }
  155. // Finally, load patched assemblies into memory
  156. if (ConfigDumpAssemblies.Value || ConfigLoadDumpedAssemblies.Value)
  157. {
  158. if (!Directory.Exists(DumpedAssembliesPath))
  159. Directory.CreateDirectory(DumpedAssembliesPath);
  160. foreach (KeyValuePair<string, AssemblyDefinition> kv in assemblies)
  161. {
  162. string filename = kv.Key;
  163. var assembly = kv.Value;
  164. if (patchedAssemblies.Contains(filename))
  165. assembly.Write(Path.Combine(DumpedAssembliesPath, filename));
  166. }
  167. }
  168. if (ConfigBreakBeforeLoadAssemblies.Value)
  169. {
  170. Logger.LogInfo($"BepInEx is about load the following assemblies:\n{string.Join("\n", patchedAssemblies.ToArray())}");
  171. Logger.LogInfo($"The assemblies were dumped into {DumpedAssembliesPath}");
  172. Logger.LogInfo("Load any assemblies into the debugger, set breakpoints and continue execution.");
  173. Debugger.Break();
  174. }
  175. foreach (var kv in assemblies)
  176. {
  177. string filename = kv.Key;
  178. var assembly = kv.Value;
  179. // Note that since we only *load* assemblies, they shouldn't trigger dependency loading
  180. // Not loading all assemblies is very important not only because of memory reasons,
  181. // but because some games *rely* on that because of messed up internal dependencies.
  182. if (patchedAssemblies.Contains(filename))
  183. Load(assembly, filename);
  184. // Though we have to dispose of all assemblies regardless of them being patched or not
  185. assembly.Dispose();
  186. }
  187. //run all finalizers
  188. FinalizePatching();
  189. }
  190. /// <summary>
  191. /// Loads an individual assembly definition into the CLR.
  192. /// </summary>
  193. /// <param name="assembly">The assembly to load.</param>
  194. public static void Load(AssemblyDefinition assembly, string filename)
  195. {
  196. if (ConfigLoadDumpedAssemblies.Value)
  197. Assembly.LoadFile(Path.Combine(DumpedAssembliesPath, filename));
  198. else
  199. using (var assemblyStream = new MemoryStream())
  200. {
  201. assembly.Write(assemblyStream);
  202. Assembly.Load(assemblyStream.ToArray());
  203. }
  204. }
  205. #region Config
  206. private static readonly ConfigWrapper<bool> ConfigDumpAssemblies = ConfigFile.CoreConfig.Wrap(
  207. "Preloader",
  208. "DumpAssemblies",
  209. "If enabled, BepInEx will save patched assemblies into BepInEx/DumpedAssemblies.\nThis can be used by developers to inspect and debug preloader patchers.",
  210. false);
  211. private static readonly ConfigWrapper<bool> ConfigLoadDumpedAssemblies = ConfigFile.CoreConfig.Wrap(
  212. "Preloader",
  213. "LoadDumpedAssemblies",
  214. "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.",
  215. false);
  216. private static readonly ConfigWrapper<bool> ConfigBreakBeforeLoadAssemblies = ConfigFile.CoreConfig.Wrap(
  217. "Preloader",
  218. "BreakBeforeLoadAssemblies",
  219. "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.",
  220. false);
  221. #endregion
  222. }
  223. }