AssemblyPatcher.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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. if(patcherCollection.Count == 0)
  77. continue;
  78. var ass = Assembly.LoadFile(assemblyPath);
  79. foreach (var patcherPlugin in patcherCollection)
  80. {
  81. try
  82. {
  83. var type = ass.GetType(patcherPlugin.TypeName);
  84. var methods = type.GetMethods(ALL);
  85. patcherPlugin.Initializer = CreateDelegate<Action>(methods.FirstOrDefault(m => m.Name.Equals("Initialize", StringComparison.InvariantCultureIgnoreCase) &&
  86. m.GetParameters().Length == 0 &&
  87. m.ReturnType == typeof(void)));
  88. patcherPlugin.Finalizer = CreateDelegate<Action>(methods.FirstOrDefault(m => m.Name.Equals("Finish", StringComparison.InvariantCultureIgnoreCase) &&
  89. m.GetParameters().Length == 0 &&
  90. m.ReturnType == typeof(void)));
  91. patcherPlugin.TargetDLLs = CreateDelegate<Func<IEnumerable<string>>>(type.GetProperty("TargetDLLs", ALL).GetGetMethod());
  92. var patcher = methods.FirstOrDefault(m => m.Name.Equals("Patch", StringComparison.CurrentCultureIgnoreCase) &&
  93. m.ReturnType == typeof(void) &&
  94. m.GetParameters().Length == 1 &&
  95. (m.GetParameters()[0].ParameterType == typeof(AssemblyDefinition) ||
  96. m.GetParameters()[0].ParameterType == typeof(AssemblyDefinition).MakeByRefType()));
  97. patcherPlugin.Patcher = (ref AssemblyDefinition pAss) =>
  98. {
  99. //we do the array fuckery here to get the ref result out
  100. object[] args = { pAss };
  101. patcher.Invoke(null, args);
  102. pAss = (AssemblyDefinition)args[0];
  103. };
  104. sortedPatchers.Add($"{ass.GetName().Name}/{type.FullName}", patcherPlugin);
  105. }
  106. catch (Exception e)
  107. {
  108. Logger.LogError($"Failed to load patcher [{patcherPlugin.TypeName}]: {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 {ass.GetName().FullName}");
  117. }
  118. foreach (KeyValuePair<string, PatcherPlugin> patcher in sortedPatchers)
  119. AddPatcher(patcher.Value);
  120. }
  121. private static void InitializePatchers()
  122. {
  123. foreach (var assemblyPatcher in PatcherPlugins)
  124. assemblyPatcher.Initializer?.Invoke();
  125. }
  126. private static void FinalizePatching()
  127. {
  128. foreach (var assemblyPatcher in PatcherPlugins)
  129. assemblyPatcher.Finalizer?.Invoke();
  130. }
  131. /// <summary>
  132. /// Releases all patchers to let them be collected by GC.
  133. /// </summary>
  134. public static void DisposePatchers()
  135. {
  136. PatcherPlugins.Clear();
  137. }
  138. /// <summary>
  139. /// Applies patchers to all assemblies in the given directory and loads patched assemblies into memory.
  140. /// </summary>
  141. /// <param name="directory">Directory to load CLR assemblies from.</param>
  142. public static void PatchAndLoad(string directory)
  143. {
  144. // First, load patchable assemblies into Cecil
  145. var assemblies = new Dictionary<string, AssemblyDefinition>();
  146. foreach (string assemblyPath in Directory.GetFiles(directory, "*.dll"))
  147. {
  148. var assembly = AssemblyDefinition.ReadAssembly(assemblyPath);
  149. //NOTE: this is special cased here because the dependency handling for System.dll is a bit wonky
  150. //System has an assembly reference to itself, and it also has a reference to Mono.Security causing a circular dependency
  151. //It's also generally dangerous to change system.dll since so many things rely on it,
  152. // and it's already loaded into the appdomain since this loader references it, so we might as well skip it
  153. if (assembly.Name.Name == "System" || assembly.Name.Name == "mscorlib") //mscorlib is already loaded into the appdomain so it can't be patched
  154. {
  155. assembly.Dispose();
  156. continue;
  157. }
  158. if (UnityPatches.AssemblyLocations.ContainsKey(assembly.FullName))
  159. {
  160. Logger.LogWarning($"Tried to load duplicate assembly {Path.GetFileName(assemblyPath)} from Managed folder! Skipping...");
  161. continue;
  162. }
  163. assemblies.Add(Path.GetFileName(assemblyPath), assembly);
  164. UnityPatches.AssemblyLocations.Add(assembly.FullName, Path.GetFullPath(assemblyPath));
  165. }
  166. // Next, initialize all the patchers
  167. InitializePatchers();
  168. // Then, perform the actual patching
  169. var patchedAssemblies = new HashSet<string>();
  170. foreach (var assemblyPatcher in PatcherPlugins)
  171. foreach (string targetDll in assemblyPatcher.TargetDLLs())
  172. if (assemblies.TryGetValue(targetDll, out var assembly))
  173. {
  174. if (AppDomain.CurrentDomain.GetAssemblies().Any(x => x.GetName().Name == assembly.Name.Name))
  175. Logger.LogWarning($"Trying to patch an already loaded assembly [{assembly.Name.Name}] with [{assemblyPatcher.TypeName}]");
  176. Logger.LogInfo($"Patching [{assembly.Name.Name}] with [{assemblyPatcher.TypeName}]");
  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 ConfigEntry<bool> ConfigDumpAssemblies = ConfigFile.CoreConfig.AddSetting(
  233. "Preloader", "DumpAssemblies",
  234. false,
  235. "If enabled, BepInEx will save patched assemblies into BepInEx/DumpedAssemblies.\nThis can be used by developers to inspect and debug preloader patchers.");
  236. private static readonly ConfigEntry<bool> ConfigLoadDumpedAssemblies = ConfigFile.CoreConfig.AddSetting(
  237. "Preloader", "LoadDumpedAssemblies",
  238. false,
  239. "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.");
  240. private static readonly ConfigEntry<bool> ConfigBreakBeforeLoadAssemblies = ConfigFile.CoreConfig.AddSetting(
  241. "Preloader", "BreakBeforeLoadAssemblies",
  242. false,
  243. "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.");
  244. #endregion
  245. }
  246. }