TypeLoader.cs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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 Resolver;
  52. /// <summary>
  53. /// Default reader parameters used by <see cref="TypeLoader"/>
  54. /// </summary>
  55. public static readonly ReaderParameters ReaderParameters;
  56. static TypeLoader()
  57. {
  58. Resolver = new DefaultAssemblyResolver();
  59. ReaderParameters = new ReaderParameters { AssemblyResolver = Resolver };
  60. Resolver.ResolveFailure += (sender, reference) =>
  61. {
  62. var name = new AssemblyName(reference.FullName);
  63. if (Utility.TryResolveDllAssembly(name, Paths.BepInExAssemblyDirectory, ReaderParameters, out var assembly) ||
  64. Utility.TryResolveDllAssembly(name, Paths.PluginPath, ReaderParameters, out assembly) ||
  65. Utility.TryResolveDllAssembly(name, Paths.ManagedPath, ReaderParameters, out assembly))
  66. return assembly;
  67. return AssemblyResolve?.Invoke(sender, reference);
  68. };
  69. }
  70. public static event AssemblyResolveEventHandler AssemblyResolve;
  71. /// <summary>
  72. /// Looks up assemblies in the given directory and locates all types that can be loaded and collects their metadata.
  73. /// </summary>
  74. /// <typeparam name="T">The specific base type to search for.</typeparam>
  75. /// <param name="directory">The directory to search for assemblies.</param>
  76. /// <param name="typeSelector">A function to check if a type should be selected and to build the type metadata.</param>
  77. /// <param name="assemblyFilter">A filter function to quickly determine if the assembly can be loaded.</param>
  78. /// <param name="cacheName">The name of the cache to get cached types from.</param>
  79. /// <returns>A dictionary of all assemblies in the directory and the list of type metadatas of types that match the selector.</returns>
  80. public static Dictionary<string, List<T>> FindPluginTypes<T>(string directory, Func<TypeDefinition, T> typeSelector, Func<AssemblyDefinition, bool> assemblyFilter = null, string cacheName = null) where T : ICacheable, new()
  81. {
  82. var result = new Dictionary<string, List<T>>();
  83. Dictionary<string, CachedAssembly<T>> cache = null;
  84. if (cacheName != null)
  85. cache = LoadAssemblyCache<T>(cacheName);
  86. foreach (string dll in Directory.GetFiles(Path.GetFullPath(directory), "*.dll", SearchOption.AllDirectories))
  87. try
  88. {
  89. if (cache != null && cache.TryGetValue(dll, out var cacheEntry))
  90. {
  91. long lastWrite = File.GetLastWriteTimeUtc(dll).Ticks;
  92. if (lastWrite == cacheEntry.Timestamp)
  93. {
  94. result[dll] = cacheEntry.CacheItems;
  95. continue;
  96. }
  97. }
  98. var ass = AssemblyDefinition.ReadAssembly(dll, ReaderParameters);
  99. if (!assemblyFilter?.Invoke(ass) ?? false)
  100. {
  101. result[dll] = new List<T>();
  102. ass.Dispose();
  103. continue;
  104. }
  105. var matches = ass.MainModule.Types.Select(typeSelector).Where(t => t != null).ToList();
  106. result[dll] = matches;
  107. ass.Dispose();
  108. }
  109. catch (Exception e)
  110. {
  111. Logger.LogError(e.ToString());
  112. }
  113. if (cacheName != null)
  114. SaveAssemblyCache(cacheName, result);
  115. return result;
  116. }
  117. /// <summary>
  118. /// Loads an index of type metadatas from a cache.
  119. /// </summary>
  120. /// <param name="cacheName">Name of the cache</param>
  121. /// <typeparam name="T">Cacheable item</typeparam>
  122. /// <returns>Cached type metadatas indexed by the path of the assembly that defines the type. If no cache is defined, return null.</returns>
  123. public static Dictionary<string, CachedAssembly<T>> LoadAssemblyCache<T>(string cacheName) where T : ICacheable, new()
  124. {
  125. if (!EnableAssemblyCache.Value)
  126. return null;
  127. var result = new Dictionary<string, CachedAssembly<T>>();
  128. try
  129. {
  130. string path = Path.Combine(Paths.CachePath, $"{cacheName}_typeloader.dat");
  131. if (!File.Exists(path))
  132. return null;
  133. using (var br = new BinaryReader(File.OpenRead(path)))
  134. {
  135. int entriesCount = br.ReadInt32();
  136. for (var i = 0; i < entriesCount; i++)
  137. {
  138. string entryIdentifier = br.ReadString();
  139. long entryDate = br.ReadInt64();
  140. int itemsCount = br.ReadInt32();
  141. var items = new List<T>();
  142. for (var j = 0; j < itemsCount; j++)
  143. {
  144. var entry = new T();
  145. entry.Load(br);
  146. items.Add(entry);
  147. }
  148. result[entryIdentifier] = new CachedAssembly<T> { Timestamp = entryDate, CacheItems = items };
  149. }
  150. }
  151. }
  152. catch (Exception e)
  153. {
  154. Logger.LogWarning($"Failed to load cache \"{cacheName}\"; skipping loading cache. Reason: {e.Message}.");
  155. }
  156. return result;
  157. }
  158. /// <summary>
  159. /// Saves indexed type metadata into a cache.
  160. /// </summary>
  161. /// <param name="cacheName">Name of the cache</param>
  162. /// <param name="entries">List of plugin metadatas indexed by the path to the assembly that contains the types</param>
  163. /// <typeparam name="T">Cacheable item</typeparam>
  164. public static void SaveAssemblyCache<T>(string cacheName, Dictionary<string, List<T>> entries) where T : ICacheable
  165. {
  166. if (!EnableAssemblyCache.Value)
  167. return;
  168. try
  169. {
  170. if (!Directory.Exists(Paths.CachePath))
  171. Directory.CreateDirectory(Paths.CachePath);
  172. string path = Path.Combine(Paths.CachePath, $"{cacheName}_typeloader.dat");
  173. using (var bw = new BinaryWriter(File.OpenWrite(path)))
  174. {
  175. bw.Write(entries.Count);
  176. foreach (var kv in entries)
  177. {
  178. bw.Write(kv.Key);
  179. bw.Write(File.GetLastWriteTimeUtc(kv.Key).Ticks);
  180. bw.Write(kv.Value.Count);
  181. foreach (var item in kv.Value)
  182. item.Save(bw);
  183. }
  184. }
  185. }
  186. catch (Exception e)
  187. {
  188. Logger.LogWarning($"Failed to save cache \"{cacheName}\"; skipping saving cache. Reason: {e.Message}.");
  189. }
  190. }
  191. /// <summary>
  192. /// Converts TypeLoadException to a readable string.
  193. /// </summary>
  194. /// <param name="ex">TypeLoadException</param>
  195. /// <returns>Readable representation of the exception</returns>
  196. public static string TypeLoadExceptionToString(ReflectionTypeLoadException ex)
  197. {
  198. var sb = new StringBuilder();
  199. foreach (var exSub in ex.LoaderExceptions)
  200. {
  201. sb.AppendLine(exSub.Message);
  202. if (exSub is FileNotFoundException exFileNotFound)
  203. {
  204. if (!string.IsNullOrEmpty(exFileNotFound.FusionLog))
  205. {
  206. sb.AppendLine("Fusion Log:");
  207. sb.AppendLine(exFileNotFound.FusionLog);
  208. }
  209. }
  210. else if (exSub is FileLoadException exLoad)
  211. {
  212. if (!string.IsNullOrEmpty(exLoad.FusionLog))
  213. {
  214. sb.AppendLine("Fusion Log:");
  215. sb.AppendLine(exLoad.FusionLog);
  216. }
  217. }
  218. sb.AppendLine();
  219. }
  220. return sb.ToString();
  221. }
  222. #region Config
  223. private static readonly ConfigEntry<bool> EnableAssemblyCache = ConfigFile.CoreConfig.Bind(
  224. "Caching", "EnableAssemblyCache",
  225. true,
  226. "Enable/disable assembly metadata cache\nEnabling this will speed up discovery of plugins and patchers by caching the metadata of all types BepInEx discovers.");
  227. #endregion
  228. }
  229. }