AssemblyPatcher.cs 11 KB

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