TypeLoader.cs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Text;
  7. using BepInEx.Configuration;
  8. using BepInEx.Logging;
  9. using Mono.Cecil;
  10. namespace BepInEx.Bootstrap
  11. {
  12. /// <summary>
  13. /// A cacheable metadata item. Can be used with <see cref="TypeLoader.LoadAssemblyCache{T}"/> and <see cref="TypeLoader.SaveAssemblyCache{T}"/> to cache plugin metadata.
  14. /// </summary>
  15. public interface ICacheable
  16. {
  17. /// <summary>
  18. /// Serialize the object into a binary format.
  19. /// </summary>
  20. /// <param name="bw"></param>
  21. void Save(BinaryWriter bw);
  22. /// <summary>
  23. /// Loads the object from binary format.
  24. /// </summary>
  25. /// <param name="br"></param>
  26. void Load(BinaryReader br);
  27. }
  28. /// <summary>
  29. /// A cached assembly.
  30. /// </summary>
  31. /// <typeparam name="T"></typeparam>
  32. public class CachedAssembly<T> where T : ICacheable
  33. {
  34. /// <summary>
  35. /// List of cached items inside the assembly.
  36. /// </summary>
  37. public List<T> CacheItems { get; set; }
  38. /// <summary>
  39. /// Timestamp of the assembly. Used to check the age of the cache.
  40. /// </summary>
  41. public long Timestamp { get; set; }
  42. }
  43. /// <summary>
  44. /// Provides methods for loading specified types from an assembly.
  45. /// </summary>
  46. public static class TypeLoader
  47. {
  48. /// <summary>
  49. /// Default assembly resolved used by the <see cref="TypeLoader"/>
  50. /// </summary>
  51. public static readonly DefaultAssemblyResolver CecilResolver;
  52. /// <summary>
  53. /// Default reader parameters used by <see cref="TypeLoader"/>
  54. /// </summary>
  55. public static readonly ReaderParameters ReaderParameters;
  56. public static HashSet<string> SearchDirectories = new HashSet<string>();
  57. static TypeLoader()
  58. {
  59. CecilResolver = new DefaultAssemblyResolver();
  60. ReaderParameters = new ReaderParameters { AssemblyResolver = CecilResolver };
  61. CecilResolver.ResolveFailure += CecilResolveOnFailure;
  62. }
  63. public static AssemblyDefinition CecilResolveOnFailure(object sender, AssemblyNameReference reference)
  64. {
  65. if (!Utility.TryParseAssemblyName(reference.FullName, out var name))
  66. return null;
  67. if (Utility.TryResolveDllAssembly(name, Paths.BepInExAssemblyDirectory, ReaderParameters, out var assembly) ||
  68. Utility.TryResolveDllAssembly(name, Paths.PluginPath, ReaderParameters, out assembly))
  69. return assembly;
  70. foreach (var dir in SearchDirectories)
  71. {
  72. if (Utility.TryResolveDllAssembly(name, dir, ReaderParameters, out assembly))
  73. return assembly;
  74. }
  75. return AssemblyResolve?.Invoke(sender, reference);
  76. }
  77. /// <summary>
  78. /// Event fired when <see cref="TypeLoader"/> fails to resolve a type during type loading.
  79. /// </summary>
  80. public static event AssemblyResolveEventHandler AssemblyResolve;
  81. /// <summary>
  82. /// Looks up assemblies in the given directory and locates all types that can be loaded and collects their metadata.
  83. /// </summary>
  84. /// <typeparam name="T">The specific base type to search for.</typeparam>
  85. /// <param name="directory">The directory to search for assemblies.</param>
  86. /// <param name="typeSelector">A function to check if a type should be selected and to build the type metadata.</param>
  87. /// <param name="assemblyFilter">A filter function to quickly determine if the assembly can be loaded.</param>
  88. /// <param name="cacheName">The name of the cache to get cached types from.</param>
  89. /// <returns>A dictionary of all assemblies in the directory and the list of type metadatas of types that match the selector.</returns>
  90. public static Dictionary<string, List<T>> FindPluginTypes<T>(string directory, Func<TypeDefinition, string, T> typeSelector, Func<AssemblyDefinition, bool> assemblyFilter = null, string cacheName = null) where T : ICacheable, new()
  91. {
  92. var result = new Dictionary<string, List<T>>();
  93. Dictionary<string, CachedAssembly<T>> cache = null;
  94. if (cacheName != null)
  95. cache = LoadAssemblyCache<T>(cacheName);
  96. foreach (string dll in Directory.GetFiles(Path.GetFullPath(directory), "*.dll", SearchOption.AllDirectories))
  97. try
  98. {
  99. if (cache != null && cache.TryGetValue(dll, out var cacheEntry))
  100. {
  101. long lastWrite = File.GetLastWriteTimeUtc(dll).Ticks;
  102. if (lastWrite == cacheEntry.Timestamp)
  103. {
  104. result[dll] = cacheEntry.CacheItems;
  105. continue;
  106. }
  107. }
  108. var ass = AssemblyDefinition.ReadAssembly(dll, ReaderParameters);
  109. Logger.LogDebug($"Examining '{dll}'");
  110. if (!assemblyFilter?.Invoke(ass) ?? false)
  111. {
  112. result[dll] = new List<T>();
  113. ass.Dispose();
  114. continue;
  115. }
  116. var matches = ass.MainModule.Types
  117. .Select(t => typeSelector(t, dll))
  118. .Where(t => t != null).ToList();
  119. result[dll] = matches;
  120. ass.Dispose();
  121. }
  122. catch (Exception e)
  123. {
  124. Logger.LogError(e.ToString());
  125. }
  126. if (cacheName != null)
  127. SaveAssemblyCache(cacheName, result);
  128. return result;
  129. }
  130. /// <summary>
  131. /// Loads an index of type metadatas from a cache.
  132. /// </summary>
  133. /// <param name="cacheName">Name of the cache</param>
  134. /// <typeparam name="T">Cacheable item</typeparam>
  135. /// <returns>Cached type metadatas indexed by the path of the assembly that defines the type. If no cache is defined, return null.</returns>
  136. public static Dictionary<string, CachedAssembly<T>> LoadAssemblyCache<T>(string cacheName) where T : ICacheable, new()
  137. {
  138. if (!EnableAssemblyCache.Value)
  139. return null;
  140. var result = new Dictionary<string, CachedAssembly<T>>();
  141. try
  142. {
  143. string path = Path.Combine(Paths.CachePath, $"{cacheName}_typeloader.dat");
  144. if (!File.Exists(path))
  145. return null;
  146. using (var br = new BinaryReader(File.OpenRead(path)))
  147. {
  148. int entriesCount = br.ReadInt32();
  149. for (var i = 0; i < entriesCount; i++)
  150. {
  151. string entryIdentifier = br.ReadString();
  152. long entryDate = br.ReadInt64();
  153. int itemsCount = br.ReadInt32();
  154. var items = new List<T>();
  155. for (var j = 0; j < itemsCount; j++)
  156. {
  157. var entry = new T();
  158. entry.Load(br);
  159. items.Add(entry);
  160. }
  161. result[entryIdentifier] = new CachedAssembly<T> { Timestamp = entryDate, CacheItems = items };
  162. }
  163. }
  164. }
  165. catch (Exception e)
  166. {
  167. Logger.LogWarning($"Failed to load cache \"{cacheName}\"; skipping loading cache. Reason: {e.Message}.");
  168. }
  169. return result;
  170. }
  171. /// <summary>
  172. /// Saves indexed type metadata into a cache.
  173. /// </summary>
  174. /// <param name="cacheName">Name of the cache</param>
  175. /// <param name="entries">List of plugin metadatas indexed by the path to the assembly that contains the types</param>
  176. /// <typeparam name="T">Cacheable item</typeparam>
  177. public static void SaveAssemblyCache<T>(string cacheName, Dictionary<string, List<T>> entries) where T : ICacheable
  178. {
  179. if (!EnableAssemblyCache.Value)
  180. return;
  181. try
  182. {
  183. if (!Directory.Exists(Paths.CachePath))
  184. Directory.CreateDirectory(Paths.CachePath);
  185. string path = Path.Combine(Paths.CachePath, $"{cacheName}_typeloader.dat");
  186. using (var bw = new BinaryWriter(File.OpenWrite(path)))
  187. {
  188. bw.Write(entries.Count);
  189. foreach (var kv in entries)
  190. {
  191. bw.Write(kv.Key);
  192. bw.Write(File.GetLastWriteTimeUtc(kv.Key).Ticks);
  193. bw.Write(kv.Value.Count);
  194. foreach (var item in kv.Value)
  195. item.Save(bw);
  196. }
  197. }
  198. }
  199. catch (Exception e)
  200. {
  201. Logger.LogWarning($"Failed to save cache \"{cacheName}\"; skipping saving cache. Reason: {e.Message}.");
  202. }
  203. }
  204. /// <summary>
  205. /// Converts TypeLoadException to a readable string.
  206. /// </summary>
  207. /// <param name="ex">TypeLoadException</param>
  208. /// <returns>Readable representation of the exception</returns>
  209. public static string TypeLoadExceptionToString(ReflectionTypeLoadException ex)
  210. {
  211. var sb = new StringBuilder();
  212. foreach (var exSub in ex.LoaderExceptions)
  213. {
  214. sb.AppendLine(exSub.Message);
  215. if (exSub is FileNotFoundException exFileNotFound)
  216. {
  217. if (!string.IsNullOrEmpty(exFileNotFound.FusionLog))
  218. {
  219. sb.AppendLine("Fusion Log:");
  220. sb.AppendLine(exFileNotFound.FusionLog);
  221. }
  222. }
  223. else if (exSub is FileLoadException exLoad)
  224. {
  225. if (!string.IsNullOrEmpty(exLoad.FusionLog))
  226. {
  227. sb.AppendLine("Fusion Log:");
  228. sb.AppendLine(exLoad.FusionLog);
  229. }
  230. }
  231. sb.AppendLine();
  232. }
  233. return sb.ToString();
  234. }
  235. #region Config
  236. private static readonly ConfigEntry<bool> EnableAssemblyCache = ConfigFile.CoreConfig.Bind(
  237. "Caching", "EnableAssemblyCache",
  238. true,
  239. "Enable/disable assembly metadata cache\nEnabling this will speed up discovery of plugins and patchers by caching the metadata of all types BepInEx discovers.");
  240. #endregion
  241. }
  242. }