TypeLoader.cs 7.9 KB

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