AssemblyPatcher.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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 System.Text;
  8. using BepInEx.Bootstrap;
  9. using BepInEx.Configuration;
  10. using BepInEx.Logging;
  11. using Mono.Cecil;
  12. namespace BepInEx.Preloader.Core
  13. {
  14. /// <summary>
  15. /// Delegate used in patching assemblies.
  16. /// </summary>
  17. /// <param name="assembly">The assembly that is being patched.</param>
  18. public 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. public class AssemblyPatcher : IDisposable
  24. {
  25. private const BindingFlags ALL = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.IgnoreCase;
  26. /// <summary>
  27. /// A list of plugins that will be initialized and executed, in the order of the list.
  28. /// </summary>
  29. public List<PatcherPlugin> PatcherPlugins { get; } = new List<PatcherPlugin>();
  30. /// <summary>
  31. /// <para>Contains a list of assemblies that will be patched and loaded into the runtime.</para>
  32. /// <para>The dictionary has the name of the file, without any directories. These are used by the dumping functionality, and as such, these are also required to be unique. They do not have to be exactly the same as the real filename, however they have to be mapped deterministically.</para>
  33. /// <para>Order is not respected, as it will be sorted by dependencies.</para>
  34. /// </summary>
  35. public Dictionary<string, AssemblyDefinition> AssembliesToPatch { get; } = new Dictionary<string, AssemblyDefinition>();
  36. /// <summary>
  37. /// The directory location as to where patched assemblies will be saved to and loaded from disk, for debugging purposes. Defaults to BepInEx/DumpedAssemblies
  38. /// </summary>
  39. public string DumpedAssembliesPath { get; set; } = Path.Combine(Paths.BepInExRootPath, "DumpedAssemblies");
  40. public ManualLogSource Logger { get; } = BepInEx.Logging.Logger.CreateLogSource("AssemblyPatcher");
  41. private static T CreateDelegate<T>(MethodInfo method) where T : class => method != null ? Delegate.CreateDelegate(typeof(T), method) as T : null;
  42. private static PatcherPlugin ToPatcherPlugin(TypeDefinition type, string assemblyPath)
  43. {
  44. if (type.IsInterface || type.IsAbstract && !type.IsSealed)
  45. return null;
  46. var targetDlls = type.Methods.FirstOrDefault(m => m.Name.Equals("get_TargetDLLs", StringComparison.InvariantCultureIgnoreCase) &&
  47. m.IsPublic &&
  48. m.IsStatic);
  49. if (targetDlls == null ||
  50. targetDlls.ReturnType.FullName != "System.Collections.Generic.IEnumerable`1<System.String>")
  51. return null;
  52. var patch = type.Methods.FirstOrDefault(m => m.Name.Equals("Patch") &&
  53. m.IsPublic &&
  54. m.IsStatic &&
  55. m.ReturnType.FullName == "System.Void" &&
  56. m.Parameters.Count == 1 &&
  57. (m.Parameters[0].ParameterType.FullName == "Mono.Cecil.AssemblyDefinition&" ||
  58. m.Parameters[0].ParameterType.FullName == "Mono.Cecil.AssemblyDefinition"));
  59. if (patch == null)
  60. return null;
  61. return new PatcherPlugin
  62. {
  63. TypeName = type.FullName
  64. };
  65. }
  66. /// <summary>
  67. /// Adds all patchers from all managed assemblies specified in a directory.
  68. /// </summary>
  69. /// <param name="directory">Directory to search patcher DLLs from.</param>
  70. /// <param name="patcherLocator">A function that locates assembly patchers in a given managed assembly.</param>
  71. public void AddPatchersFromDirectory(string directory)
  72. {
  73. if (!Directory.Exists(directory))
  74. return;
  75. var sortedPatchers = new SortedDictionary<string, PatcherPlugin>();
  76. var patchers = TypeLoader.FindPluginTypes(directory, ToPatcherPlugin);
  77. foreach (var keyValuePair in patchers)
  78. {
  79. var assemblyPath = keyValuePair.Key;
  80. var patcherCollection = keyValuePair.Value;
  81. if(patcherCollection.Count == 0)
  82. continue;
  83. var ass = Assembly.LoadFile(assemblyPath);
  84. foreach (var patcherPlugin in patcherCollection)
  85. {
  86. try
  87. {
  88. var type = ass.GetType(patcherPlugin.TypeName);
  89. var methods = type.GetMethods(ALL);
  90. patcherPlugin.Initializer = CreateDelegate<Action>(methods.FirstOrDefault(m => m.Name.Equals("Initialize", StringComparison.InvariantCultureIgnoreCase) &&
  91. m.GetParameters().Length == 0 &&
  92. m.ReturnType == typeof(void)));
  93. patcherPlugin.Finalizer = CreateDelegate<Action>(methods.FirstOrDefault(m => m.Name.Equals("Finish", StringComparison.InvariantCultureIgnoreCase) &&
  94. m.GetParameters().Length == 0 &&
  95. m.ReturnType == typeof(void)));
  96. patcherPlugin.TargetDLLs = CreateDelegate<Func<IEnumerable<string>>>(type.GetProperty("TargetDLLs", ALL).GetGetMethod());
  97. var patcher = methods.FirstOrDefault(m => m.Name.Equals("Patch", StringComparison.CurrentCultureIgnoreCase) &&
  98. m.ReturnType == typeof(void) &&
  99. m.GetParameters().Length == 1 &&
  100. (m.GetParameters()[0].ParameterType == typeof(AssemblyDefinition) ||
  101. m.GetParameters()[0].ParameterType == typeof(AssemblyDefinition).MakeByRefType()));
  102. patcherPlugin.Patcher = (ref AssemblyDefinition pAss) =>
  103. {
  104. //we do the array fuckery here to get the ref result out
  105. object[] args = { pAss };
  106. patcher.Invoke(null, args);
  107. pAss = (AssemblyDefinition)args[0];
  108. };
  109. sortedPatchers.Add($"{ass.GetName().Name}/{type.FullName}", patcherPlugin);
  110. }
  111. catch (Exception e)
  112. {
  113. Logger.LogError($"Failed to load patcher [{patcherPlugin.TypeName}]: {e.Message}");
  114. if (e is ReflectionTypeLoadException re)
  115. Logger.LogDebug(TypeLoader.TypeLoadExceptionToString(re));
  116. else
  117. Logger.LogDebug(e.ToString());
  118. }
  119. }
  120. Logger.Log(patcherCollection.Any() ? LogLevel.Info : LogLevel.Debug,
  121. $"Loaded {patcherCollection.Count} patcher methods from {ass.GetName().FullName}");
  122. }
  123. foreach (KeyValuePair<string, PatcherPlugin> patcher in sortedPatchers)
  124. PatcherPlugins.Add(patcher.Value);
  125. }
  126. /// <summary>
  127. /// Adds all .dll assemblies in a directory to be patched and loaded by this patcher instance. Non-managed assemblies are skipped.
  128. /// </summary>
  129. /// <param name="directory">The directory to search.</param>
  130. public void LoadAssemblyDirectory(string directory)
  131. {
  132. LoadAssemblyDirectory(directory, "dll");
  133. }
  134. /// <summary>
  135. /// Adds all assemblies in a directory to be patched and loaded by this patcher instance. Non-managed assemblies are skipped.
  136. /// </summary>
  137. /// <param name="directory">The directory to search.</param>
  138. /// <param name="assemblyExtensions">The file extensions to attempt to load.</param>
  139. public void LoadAssemblyDirectory(string directory, params string[] assemblyExtensions)
  140. {
  141. var filesToSearch = assemblyExtensions
  142. .SelectMany(ext => Directory.GetFiles(directory, "*." + ext, SearchOption.TopDirectoryOnly));
  143. foreach (string assemblyPath in filesToSearch)
  144. {
  145. if (!TryLoadAssembly(assemblyPath, out var assembly))
  146. continue;
  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. AssembliesToPatch.Add(Path.GetFileName(assemblyPath), assembly);
  157. Logger.LogDebug($"Assembly loaded: {Path.GetFileName(assemblyPath)}");
  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. }
  167. /// <summary>
  168. /// Attempts to load a managed assembly as an <see cref="AssemblyDefinition"/>. Returns true if successful.
  169. /// </summary>
  170. /// <param name="path">The path of the assembly.</param>
  171. /// <param name="assembly">The loaded assembly. Null if not successful in loading.</param>
  172. public static bool TryLoadAssembly(string path, out AssemblyDefinition assembly)
  173. {
  174. try
  175. {
  176. assembly = AssemblyDefinition.ReadAssembly(path);
  177. return true;
  178. }
  179. catch (BadImageFormatException)
  180. {
  181. // Not a managed assembly
  182. assembly = null;
  183. return false;
  184. }
  185. }
  186. /// <summary>
  187. /// Performs work to dispose collection objects.
  188. /// </summary>
  189. public void Dispose()
  190. {
  191. foreach (var assembly in AssembliesToPatch)
  192. assembly.Value.Dispose();
  193. AssembliesToPatch.Clear();
  194. // Clear to allow GC collection.
  195. PatcherPlugins.Clear();
  196. }
  197. private static string GetAssemblyName(string fullName)
  198. {
  199. // We need to manually parse full name to avoid issues with encoding on mono
  200. try
  201. {
  202. return new AssemblyName(fullName).Name;
  203. }
  204. catch (Exception e)
  205. {
  206. return fullName;
  207. }
  208. }
  209. /// <summary>
  210. /// Applies patchers to all assemblies in the given directory and loads patched assemblies into memory.
  211. /// </summary>
  212. /// <param name="directory">Directory to load CLR assemblies from.</param>
  213. public void PatchAndLoad()
  214. {
  215. // First, create a copy of the assembly dictionary as the initializer can change them
  216. var assemblies = new Dictionary<string, AssemblyDefinition>(AssembliesToPatch);
  217. // Next, initialize all the patchers
  218. foreach (var assemblyPatcher1 in PatcherPlugins)
  219. assemblyPatcher1.Initializer?.Invoke();
  220. // Then, perform the actual patching
  221. var patchedAssemblies = new HashSet<string>();
  222. var resolvedAssemblies = new Dictionary<string, string>();
  223. foreach (var assemblyPatcher in PatcherPlugins)
  224. foreach (string targetDll in assemblyPatcher.TargetDLLs())
  225. if (AssembliesToPatch.TryGetValue(targetDll, out var assembly))
  226. {
  227. Logger.LogInfo($"Patching [{assembly.Name.Name}] with [{assemblyPatcher.TypeName}]");
  228. assemblyPatcher.Patcher?.Invoke(ref assembly);
  229. AssembliesToPatch[targetDll] = assembly;
  230. patchedAssemblies.Add(targetDll);
  231. foreach (var resolvedAss in AppDomain.CurrentDomain.GetAssemblies())
  232. {
  233. var name = GetAssemblyName(resolvedAss.FullName);
  234. // Report only the first type that caused the assembly to load, because any subsequent ones can be false positives
  235. if (!resolvedAssemblies.ContainsKey(name))
  236. resolvedAssemblies[name] = assemblyPatcher.TypeName;
  237. }
  238. }
  239. // Check if any patched assemblies have been already resolved by the CLR
  240. // If there are any, they cannot be loaded by the preloader
  241. var patchedAssemblyNames = new HashSet<string>(assemblies.Where(kv => patchedAssemblies.Contains(kv.Key)).Select(kv => kv.Value.Name.Name));
  242. var earlyLoadAssemblies = resolvedAssemblies.Where(kv => patchedAssemblyNames.Contains(kv.Key)).ToList();
  243. if (earlyLoadAssemblies.Count != 0)
  244. {
  245. Logger.LogWarning(new StringBuilder()
  246. .AppendLine("The following assemblies have been loaded too early and will not be patched by preloader:")
  247. .AppendLine(string.Join(Environment.NewLine, earlyLoadAssemblies.Select(kv => $"* [{kv.Key}] (first loaded by [{kv.Value}])").ToArray()))
  248. .AppendLine("Expect unexpected behavior and issues with plugins and patchers not being loaded.")
  249. .ToString());
  250. }
  251. // Finally, load patched assemblies into memory
  252. if (ConfigDumpAssemblies.Value || ConfigLoadDumpedAssemblies.Value)
  253. {
  254. if (!Directory.Exists(DumpedAssembliesPath))
  255. Directory.CreateDirectory(DumpedAssembliesPath);
  256. foreach (KeyValuePair<string, AssemblyDefinition> kv in assemblies)
  257. {
  258. string filename = kv.Key;
  259. var assembly = kv.Value;
  260. if (patchedAssemblies.Contains(filename))
  261. assembly.Write(Path.Combine(DumpedAssembliesPath, filename));
  262. }
  263. }
  264. if (ConfigBreakBeforeLoadAssemblies.Value)
  265. {
  266. Logger.LogInfo($"BepInEx is about load the following assemblies:\n{String.Join("\n", patchedAssemblies.ToArray())}");
  267. Logger.LogInfo($"The assemblies were dumped into {DumpedAssembliesPath}");
  268. Logger.LogInfo("Load any assemblies into the debugger, set breakpoints and continue execution.");
  269. Debugger.Break();
  270. }
  271. foreach (var kv in assemblies)
  272. {
  273. string filename = kv.Key;
  274. var assembly = kv.Value;
  275. // Note that since we only *load* assemblies, they shouldn't trigger dependency loading
  276. // Not loading all assemblies is very important not only because of memory reasons,
  277. // but because some games *rely* on that because of messed up internal dependencies.
  278. if (patchedAssemblies.Contains(filename))
  279. {
  280. if (ConfigLoadDumpedAssemblies.Value)
  281. Assembly.LoadFile(Path.Combine(DumpedAssembliesPath, filename));
  282. else
  283. {
  284. using (var assemblyStream = new MemoryStream())
  285. {
  286. assembly.Write(assemblyStream);
  287. Assembly.Load(assemblyStream.ToArray());
  288. }
  289. }
  290. Logger.LogDebug($"Loaded '{assembly.FullName}' into memory");
  291. }
  292. // Though we have to dispose of all assemblies regardless of them being patched or not
  293. assembly.Dispose();
  294. }
  295. // Finally, run all finalizers
  296. foreach (var assemblyPatcher2 in PatcherPlugins)
  297. assemblyPatcher2.Finalizer?.Invoke();
  298. }
  299. #region Config
  300. private static readonly ConfigEntry<bool> ConfigDumpAssemblies = ConfigFile.CoreConfig.Bind(
  301. "Preloader", "DumpAssemblies",
  302. false,
  303. "If enabled, BepInEx will save patched assemblies into BepInEx/DumpedAssemblies.\nThis can be used by developers to inspect and debug preloader patchers.");
  304. private static readonly ConfigEntry<bool> ConfigLoadDumpedAssemblies = ConfigFile.CoreConfig.Bind(
  305. "Preloader", "LoadDumpedAssemblies",
  306. false,
  307. "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.");
  308. private static readonly ConfigEntry<bool> ConfigBreakBeforeLoadAssemblies = ConfigFile.CoreConfig.Bind(
  309. "Preloader", "BreakBeforeLoadAssemblies",
  310. false,
  311. "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.");
  312. #endregion
  313. }
  314. }