AssemblyPatcher.cs 11 KB

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