You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1033 lines
45 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. #nullable enable
  2. using IPA.Config;
  3. using IPA.Loader.Features;
  4. using IPA.Logging;
  5. using IPA.Utilities;
  6. using Mono.Cecil;
  7. using Newtonsoft.Json;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Reflection;
  13. using System.Text.RegularExpressions;
  14. using System.Diagnostics.CodeAnalysis;
  15. using System.Diagnostics;
  16. using IPA.AntiMalware;
  17. using Hive.Versioning;
  18. #if NET4
  19. using Task = System.Threading.Tasks.Task;
  20. using TaskEx = System.Threading.Tasks.Task;
  21. #endif
  22. #if NET3
  23. using Net3_Proxy;
  24. using Path = Net3_Proxy.Path;
  25. using File = Net3_Proxy.File;
  26. using Directory = Net3_Proxy.Directory;
  27. #endif
  28. namespace IPA.Loader
  29. {
  30. /// <summary>
  31. /// A type to manage the loading of plugins.
  32. /// </summary>
  33. internal partial class PluginLoader
  34. {
  35. internal static PluginMetadata SelfMeta = null!;
  36. internal static Task LoadTask() =>
  37. TaskEx.Run(() =>
  38. {
  39. YeetIfNeeded();
  40. var sw = Stopwatch.StartNew();
  41. LoadMetadata();
  42. sw.Stop();
  43. Logger.Loader.Info($"Loading metadata took {sw.Elapsed}");
  44. sw.Reset();
  45. sw.Start();
  46. // Features contribute to load order considerations
  47. InitFeatures();
  48. DoOrderResolution();
  49. sw.Stop();
  50. Logger.Loader.Info($"Calculating load order took {sw.Elapsed}");
  51. });
  52. internal static void YeetIfNeeded()
  53. {
  54. string pluginDir = UnityGame.PluginsPath;
  55. if (SelfConfig.YeetMods_ && UnityGame.IsGameVersionBoundary)
  56. {
  57. var oldPluginsName = Path.Combine(UnityGame.InstallPath, $"Old {UnityGame.OldVersion} Plugins");
  58. var newPluginsName = Path.Combine(UnityGame.InstallPath, $"Old {UnityGame.GameVersion} Plugins");
  59. if (Directory.Exists(oldPluginsName))
  60. Directory.Delete(oldPluginsName, true);
  61. Directory.Move(pluginDir, oldPluginsName);
  62. if (Directory.Exists(newPluginsName))
  63. Directory.Move(newPluginsName, pluginDir);
  64. else
  65. _ = Directory.CreateDirectory(pluginDir);
  66. }
  67. }
  68. internal static List<PluginMetadata> PluginsMetadata = new();
  69. internal static List<PluginMetadata> DisabledPlugins = new();
  70. private static readonly Regex embeddedTextDescriptionPattern = new(@"#!\[(.+)\]", RegexOptions.Compiled | RegexOptions.Singleline);
  71. internal static void LoadMetadata()
  72. {
  73. string[] plugins = Directory.GetFiles(UnityGame.PluginsPath, "*.dll");
  74. try
  75. {
  76. var selfMeta = new PluginMetadata
  77. {
  78. Assembly = Assembly.GetExecutingAssembly(),
  79. File = new FileInfo(Path.Combine(UnityGame.InstallPath, "IPA.exe")),
  80. PluginType = null,
  81. IsSelf = true
  82. };
  83. string manifest;
  84. using (var manifestReader =
  85. new StreamReader(
  86. selfMeta.Assembly.GetManifestResourceStream(typeof(PluginLoader), "manifest.json") ??
  87. throw new InvalidOperationException()))
  88. manifest = manifestReader.ReadToEnd();
  89. var manifestObj = JsonConvert.DeserializeObject<PluginManifest>(manifest);
  90. selfMeta.Manifest = manifestObj ?? throw new InvalidOperationException("Deserialized manifest was null");
  91. PluginsMetadata.Add(selfMeta);
  92. SelfMeta = selfMeta;
  93. }
  94. catch (Exception e)
  95. {
  96. Logger.Loader.Critical("Error loading own manifest");
  97. Logger.Loader.Critical(e);
  98. }
  99. using var resolver = new CecilLibLoader();
  100. resolver.AddSearchDirectory(UnityGame.LibraryPath);
  101. resolver.AddSearchDirectory(UnityGame.PluginsPath);
  102. foreach (var plugin in plugins)
  103. {
  104. var metadata = new PluginMetadata
  105. {
  106. File = new FileInfo(Path.Combine(UnityGame.PluginsPath, plugin)),
  107. IsSelf = false
  108. };
  109. try
  110. {
  111. var scanResult = AntiMalwareEngine.Engine.ScanFile(metadata.File);
  112. if (scanResult is ScanResult.Detected)
  113. {
  114. Logger.Loader.Warn($"Scan of {plugin} found malware; not loading");
  115. continue;
  116. }
  117. if (!SelfConfig.AntiMalware_.RunPartialThreatCode_ && scanResult is not ScanResult.KnownSafe and not ScanResult.NotDetected)
  118. {
  119. Logger.Loader.Warn($"Scan of {plugin} found partial threat; not loading. To load this, set AntiMalware.RunPartialThreatCode in the config.");
  120. continue;
  121. }
  122. var pluginModule = AssemblyDefinition.ReadAssembly(metadata.File.FullName, new ReaderParameters
  123. {
  124. ReadingMode = ReadingMode.Immediate,
  125. ReadWrite = false,
  126. AssemblyResolver = resolver
  127. }).MainModule;
  128. string pluginNs = "";
  129. PluginManifest? pluginManifest = null;
  130. foreach (var resource in pluginModule.Resources)
  131. {
  132. const string manifestSuffix = ".manifest.json";
  133. if (resource is not EmbeddedResource embedded ||
  134. !embedded.Name.EndsWith(manifestSuffix, StringComparison.Ordinal)) continue;
  135. pluginNs = embedded.Name.Substring(0, embedded.Name.Length - manifestSuffix.Length);
  136. string manifest;
  137. using (var manifestReader = new StreamReader(embedded.GetResourceStream()))
  138. manifest = manifestReader.ReadToEnd();
  139. pluginManifest = JsonConvert.DeserializeObject<PluginManifest?>(manifest);
  140. break;
  141. }
  142. if (pluginManifest == null)
  143. {
  144. #if DIRE_LOADER_WARNINGS
  145. Logger.loader.Error($"Could not find manifest.json for {Path.GetFileName(plugin)}");
  146. #else
  147. Logger.Loader.Notice($"No manifest.json in {Path.GetFileName(plugin)}");
  148. #endif
  149. continue;
  150. }
  151. if (pluginManifest.Id == null)
  152. {
  153. Logger.Loader.Warn($"Plugin '{pluginManifest.Name}' does not have a listed ID, using name");
  154. pluginManifest.Id = pluginManifest.Name;
  155. }
  156. metadata.Manifest = pluginManifest;
  157. bool TryPopulatePluginType(TypeDefinition type, PluginMetadata meta)
  158. {
  159. if (!type.HasCustomAttributes)
  160. return false;
  161. var attr = type.CustomAttributes.FirstOrDefault(a => a.Constructor.DeclaringType.FullName == typeof(PluginAttribute).FullName);
  162. if (attr is null)
  163. return false;
  164. if (!attr.HasConstructorArguments)
  165. {
  166. Logger.Loader.Warn($"Attribute plugin found in {type.FullName}, but attribute has no arguments");
  167. return false;
  168. }
  169. var args = attr.ConstructorArguments;
  170. if (args.Count != 1)
  171. {
  172. Logger.Loader.Warn($"Attribute plugin found in {type.FullName}, but attribute has unexpected number of arguments");
  173. return false;
  174. }
  175. var rtOptionsArg = args[0];
  176. if (rtOptionsArg.Type.FullName != typeof(RuntimeOptions).FullName)
  177. {
  178. Logger.Loader.Warn($"Attribute plugin found in {type.FullName}, but first argument is of unexpected type {rtOptionsArg.Type.FullName}");
  179. return false;
  180. }
  181. var rtOptionsValInt = (int)rtOptionsArg.Value; // `int` is the underlying type of RuntimeOptions
  182. meta.RuntimeOptions = (RuntimeOptions)rtOptionsValInt;
  183. meta.PluginType = type;
  184. return true;
  185. }
  186. void TryGetNamespacedPluginType(string ns, PluginMetadata meta)
  187. {
  188. foreach (var type in pluginModule.Types)
  189. {
  190. if (type.Namespace != ns) continue;
  191. if (TryPopulatePluginType(type, meta))
  192. return;
  193. }
  194. }
  195. var hint = metadata.Manifest.Misc?.PluginMainHint;
  196. if (hint != null)
  197. {
  198. var type = pluginModule.GetType(hint);
  199. if (type == null || !TryPopulatePluginType(type, metadata))
  200. TryGetNamespacedPluginType(hint, metadata);
  201. }
  202. if (metadata.PluginType == null)
  203. TryGetNamespacedPluginType(pluginNs, metadata);
  204. if (metadata.PluginType == null)
  205. {
  206. Logger.Loader.Error($"No plugin found in the manifest {(hint != null ? $"hint path ({hint}) or " : "")}namespace ({pluginNs}) in {Path.GetFileName(plugin)}");
  207. continue;
  208. }
  209. Logger.Loader.Debug($"Adding info for {Path.GetFileName(plugin)}");
  210. PluginsMetadata.Add(metadata);
  211. }
  212. catch (Exception e)
  213. {
  214. Logger.Loader.Error($"Could not load data for plugin {Path.GetFileName(plugin)}");
  215. Logger.Loader.Error(e);
  216. ignoredPlugins.Add(metadata, new IgnoreReason(Reason.Error)
  217. {
  218. ReasonText = "An error occurred loading the data",
  219. Error = e
  220. });
  221. }
  222. }
  223. IEnumerable<string> bareManifests = Directory.GetFiles(UnityGame.PluginsPath, "*.json");
  224. bareManifests = bareManifests.Concat(Directory.GetFiles(UnityGame.PluginsPath, "*.manifest"));
  225. foreach (var manifest in bareManifests)
  226. {
  227. try
  228. {
  229. var metadata = new PluginMetadata
  230. {
  231. File = new FileInfo(Path.Combine(UnityGame.PluginsPath, manifest)),
  232. IsSelf = false,
  233. IsBare = true,
  234. };
  235. var manifestObj = JsonConvert.DeserializeObject<PluginManifest>(File.ReadAllText(manifest));
  236. if (manifestObj is null)
  237. {
  238. Logger.Loader.Error($"Bare manifest {Path.GetFileName(manifest)} deserialized to null");
  239. continue;
  240. }
  241. metadata.Manifest = manifestObj;
  242. if (metadata.Manifest.Files.Length < 1)
  243. Logger.Loader.Warn($"Bare manifest {Path.GetFileName(manifest)} does not declare any files. " +
  244. $"Dependency resolution and verification cannot be completed.");
  245. Logger.Loader.Debug($"Adding info for bare manifest {Path.GetFileName(manifest)}");
  246. PluginsMetadata.Add(metadata);
  247. }
  248. catch (Exception e)
  249. {
  250. Logger.Loader.Error($"Could not load data for bare manifest {Path.GetFileName(manifest)}");
  251. Logger.Loader.Error(e);
  252. }
  253. }
  254. foreach (var meta in PluginsMetadata)
  255. { // process description include
  256. var lines = meta.Manifest.Description.Split('\n');
  257. var m = embeddedTextDescriptionPattern.Match(lines[0]);
  258. if (m.Success)
  259. {
  260. if (meta.IsBare)
  261. {
  262. Logger.Loader.Warn($"Bare manifest cannot specify description file");
  263. meta.Manifest.Description = string.Join("\n", lines.Skip(1).StrJP()); // ignore first line
  264. continue;
  265. }
  266. var name = m.Groups[1].Value;
  267. string description;
  268. if (!meta.IsSelf)
  269. {
  270. // plugin type must be non-null for non-self plugins
  271. var resc = meta.PluginType!.Module.Resources.Select(r => r as EmbeddedResource)
  272. .NonNull()
  273. .FirstOrDefault(r => r.Name == name);
  274. if (resc == null)
  275. {
  276. Logger.Loader.Warn($"Could not find description file for plugin {meta.Name} ({name}); ignoring include");
  277. meta.Manifest.Description = string.Join("\n", lines.Skip(1).StrJP()); // ignore first line
  278. continue;
  279. }
  280. using var reader = new StreamReader(resc.GetResourceStream());
  281. description = reader.ReadToEnd();
  282. }
  283. else
  284. {
  285. using var descriptionReader = new StreamReader(meta.Assembly.GetManifestResourceStream(name));
  286. description = descriptionReader.ReadToEnd();
  287. }
  288. meta.Manifest.Description = description;
  289. }
  290. }
  291. }
  292. }
  293. #region Ignore stuff
  294. /// <summary>
  295. /// An enum that represents several categories of ignore reasons that the loader may encounter.
  296. /// </summary>
  297. /// <seealso cref="IgnoreReason"/>
  298. public enum Reason
  299. {
  300. /// <summary>
  301. /// An error was thrown either loading plugin information from disk, or when initializing the plugin.
  302. /// </summary>
  303. /// <remarks>
  304. /// When this is the set <see cref="Reason"/> in an <see cref="IgnoreReason"/> structure, the member
  305. /// <see cref="IgnoreReason.Error"/> will contain the thrown exception.
  306. /// </remarks>
  307. Error,
  308. /// <summary>
  309. /// The plugin this reason is associated with has the same ID as another plugin whose information was
  310. /// already loaded.
  311. /// </summary>
  312. /// <remarks>
  313. /// When this is the set <see cref="Reason"/> in an <see cref="IgnoreReason"/> structure, the member
  314. /// <see cref="IgnoreReason.RelatedTo"/> will contain the metadata of the already loaded plugin.
  315. /// </remarks>
  316. Duplicate,
  317. /// <summary>
  318. /// The plugin this reason is associated with conflicts with another already loaded plugin.
  319. /// </summary>
  320. /// <remarks>
  321. /// When this is the set <see cref="Reason"/> in an <see cref="IgnoreReason"/> structure, the member
  322. /// <see cref="IgnoreReason.RelatedTo"/> will contain the metadata of the plugin it conflicts with.
  323. /// </remarks>
  324. Conflict,
  325. /// <summary>
  326. /// The plugin this reason is associated with is missing a dependency.
  327. /// </summary>
  328. /// <remarks>
  329. /// Since this is only given when a dependency is missing, <see cref="IgnoreReason.RelatedTo"/> will
  330. /// not be set.
  331. /// </remarks>
  332. Dependency,
  333. /// <summary>
  334. /// The plugin this reason is associated with was released for a game update, but is still considered
  335. /// present for the purposes of updating.
  336. /// </summary>
  337. Released,
  338. /// <summary>
  339. /// The plugin this reason is associated with was denied from loading by a <see cref="Features.Feature"/>
  340. /// that it marks.
  341. /// </summary>
  342. Feature,
  343. /// <summary>
  344. /// The plugin this reason is associated with is unsupported.
  345. /// </summary>
  346. /// <remarks>
  347. /// Currently, there is no path in the loader that emits this <see cref="Reason"/>, however there may
  348. /// be in the future.
  349. /// </remarks>
  350. Unsupported,
  351. /// <summary>
  352. /// One of the files that a plugin declared in its manifest is missing.
  353. /// </summary>
  354. MissingFiles
  355. }
  356. /// <summary>
  357. /// A structure describing the reason that a plugin was ignored.
  358. /// </summary>
  359. public struct IgnoreReason : IEquatable<IgnoreReason>
  360. {
  361. /// <summary>
  362. /// Gets the ignore reason, as represented by the <see cref="Loader.Reason"/> enum.
  363. /// </summary>
  364. public Reason Reason { get; }
  365. /// <summary>
  366. /// Gets the textual description of the particular ignore reason. This will typically
  367. /// include details about why the plugin was ignored, if it is present.
  368. /// </summary>
  369. public string? ReasonText { get; internal set; }
  370. /// <summary>
  371. /// Gets the <see cref="Exception"/> that caused this plugin to be ignored, if any.
  372. /// </summary>
  373. public Exception? Error { get; internal set; }
  374. /// <summary>
  375. /// Gets the metadata of the plugin that this ignore was related to, if any.
  376. /// </summary>
  377. public PluginMetadata? RelatedTo { get; internal set; }
  378. /// <summary>
  379. /// Initializes an <see cref="IgnoreReason"/> with the provided data.
  380. /// </summary>
  381. /// <param name="reason">the <see cref="Loader.Reason"/> enum value that describes this reason</param>
  382. /// <param name="reasonText">the textual description of this ignore reason, if any</param>
  383. /// <param name="error">the <see cref="Exception"/> that caused this <see cref="IgnoreReason"/>, if any</param>
  384. /// <param name="relatedTo">the <see cref="PluginMetadata"/> this reason is related to, if any</param>
  385. public IgnoreReason(Reason reason, string? reasonText = null, Exception? error = null, PluginMetadata? relatedTo = null)
  386. {
  387. Reason = reason;
  388. ReasonText = reasonText;
  389. Error = error;
  390. RelatedTo = relatedTo;
  391. }
  392. /// <inheritdoc/>
  393. public override bool Equals(object obj)
  394. => obj is IgnoreReason ir && Equals(ir);
  395. /// <summary>
  396. /// Compares this <see cref="IgnoreReason"/> with <paramref name="other"/> for equality.
  397. /// </summary>
  398. /// <param name="other">the reason to compare to</param>
  399. /// <returns><see langword="true"/> if the two reasons compare equal, <see langword="false"/> otherwise</returns>
  400. public bool Equals(IgnoreReason other)
  401. => Reason == other.Reason && ReasonText == other.ReasonText
  402. && Error == other.Error && RelatedTo == other.RelatedTo;
  403. /// <inheritdoc/>
  404. public override int GetHashCode()
  405. {
  406. int hashCode = 778404373;
  407. hashCode = (hashCode * -1521134295) + Reason.GetHashCode();
  408. hashCode = (hashCode * -1521134295) + ReasonText?.GetHashCode() ?? 0;
  409. hashCode = (hashCode * -1521134295) + Error?.GetHashCode() ?? 0;
  410. hashCode = (hashCode * -1521134295) + RelatedTo?.GetHashCode() ?? 0;
  411. return hashCode;
  412. }
  413. /// <summary>
  414. /// Checks if two <see cref="IgnoreReason"/>s are equal.
  415. /// </summary>
  416. /// <param name="left">the first <see cref="IgnoreReason"/> to compare</param>
  417. /// <param name="right">the second <see cref="IgnoreReason"/> to compare</param>
  418. /// <returns><see langword="true"/> if the two reasons compare equal, <see langword="false"/> otherwise</returns>
  419. public static bool operator ==(IgnoreReason left, IgnoreReason right)
  420. => left.Equals(right);
  421. /// <summary>
  422. /// Checks if two <see cref="IgnoreReason"/>s are not equal.
  423. /// </summary>
  424. /// <param name="left">the first <see cref="IgnoreReason"/> to compare</param>
  425. /// <param name="right">the second <see cref="IgnoreReason"/> to compare</param>
  426. /// <returns><see langword="true"/> if the two reasons are not equal, <see langword="false"/> otherwise</returns>
  427. public static bool operator !=(IgnoreReason left, IgnoreReason right)
  428. => !(left == right);
  429. }
  430. #endregion
  431. internal partial class PluginLoader
  432. {
  433. // keep track of these for the updater; it should still be able to update mods not loaded
  434. // the thing -> the reason
  435. internal static Dictionary<PluginMetadata, IgnoreReason> ignoredPlugins = new();
  436. internal static void DoOrderResolution()
  437. {
  438. #if DEBUG
  439. // print starting order
  440. Logger.Loader.Debug(string.Join(", ", PluginsMetadata.StrJP()));
  441. #endif
  442. PluginsMetadata.Sort((a, b) => b.HVersion.CompareTo(a.HVersion));
  443. #if DEBUG
  444. // print base resolution order
  445. Logger.Loader.Debug(string.Join(", ", PluginsMetadata.StrJP()));
  446. #endif
  447. var metadataCache = new Dictionary<string, (PluginMetadata Meta, bool Enabled)>(PluginsMetadata.Count);
  448. var pluginsToProcess = new List<PluginMetadata>(PluginsMetadata.Count);
  449. var disabledIds = DisabledConfig.Instance.DisabledModIds;
  450. var disabledPlugins = new List<PluginMetadata>();
  451. // build metadata cache
  452. foreach (var meta in PluginsMetadata)
  453. {
  454. if (!metadataCache.TryGetValue(meta.Id, out var existing))
  455. {
  456. if (disabledIds.Contains(meta.Id))
  457. {
  458. metadataCache.Add(meta.Id, (meta, false));
  459. disabledPlugins.Add(meta);
  460. }
  461. else
  462. {
  463. metadataCache.Add(meta.Id, (meta, true));
  464. pluginsToProcess.Add(meta);
  465. }
  466. }
  467. else
  468. {
  469. Logger.Loader.Warn($"Found duplicates of {meta.Id}, using newest");
  470. ignoredPlugins.Add(meta, new(Reason.Duplicate)
  471. {
  472. ReasonText = $"Duplicate entry of same ID ({meta.Id})",
  473. RelatedTo = existing.Meta
  474. });
  475. }
  476. }
  477. // preprocess LoadBefore into LoadAfter
  478. foreach (var (_, (meta, _)) in metadataCache)
  479. { // we iterate the metadata cache because it contains both disabled and enabled plugins
  480. var loadBefore = meta.Manifest.LoadBefore;
  481. foreach (var id in loadBefore)
  482. {
  483. if (metadataCache.TryGetValue(id, out var plugin))
  484. {
  485. // if the id exists in our metadata cache, make sure it knows to load after the plugin in kvp
  486. _ = plugin.Meta.LoadsAfter.Add(meta);
  487. }
  488. }
  489. }
  490. // preprocess conflicts to be mutual
  491. foreach (var (_, (meta, _)) in metadataCache)
  492. {
  493. foreach (var (id, range) in meta.Manifest.Conflicts)
  494. {
  495. if (metadataCache.TryGetValue(id, out var plugin)
  496. && range.Matches(plugin.Meta.HVersion))
  497. {
  498. // make sure that there's a mutual dependency
  499. var targetRange = VersionRange.ForVersion(meta.HVersion);
  500. var targetConflicts = plugin.Meta.Manifest.Conflicts;
  501. if (!targetConflicts.TryGetValue(meta.Id, out var realRange))
  502. {
  503. // there's not already a listed conflict
  504. targetConflicts.Add(meta.Id, targetRange);
  505. }
  506. else if (!realRange.Matches(meta.HVersion))
  507. {
  508. // there is already a listed conflict that isn't mutual
  509. targetRange = realRange | targetRange;
  510. targetConflicts[meta.Id] = targetRange;
  511. }
  512. }
  513. }
  514. }
  515. var loadedPlugins = new Dictionary<string, (PluginMetadata Meta, bool Disabled, bool Ignored)>();
  516. var outputOrder = new List<PluginMetadata>(PluginsMetadata.Count);
  517. var isProcessing = new HashSet<PluginMetadata>();
  518. {
  519. bool TryResolveId(string id, [MaybeNullWhen(false)] out PluginMetadata meta, out bool disabled, out bool ignored, bool partial = false)
  520. {
  521. meta = null;
  522. disabled = false;
  523. ignored = true;
  524. Logger.Loader.Trace($"Trying to resolve plugin '{id}' partial:{partial}");
  525. if (loadedPlugins.TryGetValue(id, out var foundMeta))
  526. {
  527. meta = foundMeta.Meta;
  528. disabled = foundMeta.Disabled;
  529. ignored = foundMeta.Ignored;
  530. Logger.Loader.Trace($"- Found already processed");
  531. return true;
  532. }
  533. if (metadataCache!.TryGetValue(id, out var plugin))
  534. {
  535. Logger.Loader.Trace($"- In metadata cache");
  536. if (partial)
  537. {
  538. Logger.Loader.Trace($" - but requested in a partial lookup");
  539. return false;
  540. }
  541. disabled = !plugin.Enabled;
  542. meta = plugin.Meta;
  543. if (!disabled)
  544. {
  545. try
  546. {
  547. ignored = false;
  548. Resolve(plugin.Meta, ref disabled, out ignored);
  549. }
  550. catch (Exception e)
  551. {
  552. if (e is not DependencyResolutionLoopException)
  553. {
  554. Logger.Loader.Error($"While performing load order resolution for {id}:");
  555. Logger.Loader.Error(e);
  556. }
  557. if (!ignored)
  558. {
  559. ignoredPlugins.Add(plugin.Meta, new(Reason.Error)
  560. {
  561. Error = e
  562. });
  563. }
  564. ignored = true;
  565. }
  566. }
  567. if (!loadedPlugins.ContainsKey(id))
  568. {
  569. // this condition is specifically for when we fail resolution because of a graph loop
  570. Logger.Loader.Trace($"- '{id}' resolved as ignored:{ignored},disabled:{disabled}");
  571. loadedPlugins.Add(id, (plugin.Meta, disabled, ignored));
  572. }
  573. return true;
  574. }
  575. Logger.Loader.Trace($"- Not found");
  576. return false;
  577. }
  578. void Resolve(PluginMetadata plugin, ref bool disabled, out bool ignored)
  579. {
  580. Logger.Loader.Trace($">Resolving '{plugin.Name}'");
  581. // first we need to check for loops in the resolution graph to prevent stack overflows
  582. if (isProcessing.Contains(plugin))
  583. {
  584. Logger.Loader.Error($"Loop detected while processing '{plugin.Name}'; flagging as ignored");
  585. throw new DependencyResolutionLoopException();
  586. }
  587. isProcessing.Add(plugin);
  588. using var _removeProcessing = Utils.ScopeGuard(() => isProcessing.Remove(plugin));
  589. // if this method is being called, this is the first and only time that it has been called for this plugin.
  590. ignored = false;
  591. // perform file existence check before attempting to load dependencies
  592. foreach (var file in plugin.AssociatedFiles)
  593. {
  594. if (!file.Exists)
  595. {
  596. ignoredPlugins.Add(plugin, new IgnoreReason(Reason.MissingFiles)
  597. {
  598. ReasonText = $"File {Utils.GetRelativePath(file.FullName, UnityGame.InstallPath)} does not exist"
  599. });
  600. Logger.Loader.Warn($"File {Utils.GetRelativePath(file.FullName, UnityGame.InstallPath)}" +
  601. $" (declared by '{plugin.Name}') does not exist! Mod installation is incomplete, not loading it.");
  602. ignored = true;
  603. return;
  604. }
  605. }
  606. // first load dependencies
  607. var dependsOnSelf = false;
  608. foreach (var (id, range) in plugin.Manifest.Dependencies)
  609. {
  610. if (id == SelfMeta.Id)
  611. dependsOnSelf = true;
  612. if (!TryResolveId(id, out var depMeta, out var depDisabled, out var depIgnored)
  613. || !range.Matches(depMeta.HVersion))
  614. {
  615. Logger.Loader.Warn($"'{plugin.Id}' is missing dependency '{id}@{range}'; ignoring");
  616. ignoredPlugins.Add(plugin, new(Reason.Dependency)
  617. {
  618. ReasonText = $"Dependency '{id}@{range}' not found",
  619. });
  620. ignored = true;
  621. return;
  622. }
  623. // make a point to propagate ignored
  624. if (depIgnored)
  625. {
  626. Logger.Loader.Warn($"Dependency '{id}' for '{plugin.Id}' previously ignored; ignoring '{plugin.Id}'");
  627. ignoredPlugins.Add(plugin, new(Reason.Dependency)
  628. {
  629. ReasonText = $"Dependency '{id}' ignored",
  630. RelatedTo = depMeta
  631. });
  632. ignored = true;
  633. return;
  634. }
  635. // make a point to propagate disabled
  636. if (depDisabled)
  637. {
  638. Logger.Loader.Warn($"Dependency '{id}' for '{plugin.Id}' disabled; disabling");
  639. disabledPlugins!.Add(plugin);
  640. _ = disabledIds!.Add(plugin.Id);
  641. disabled = true;
  642. }
  643. // we found our dep, lets save the metadata and keep going
  644. _ = plugin.Dependencies.Add(depMeta);
  645. }
  646. // make sure the plugin depends on the loader (assuming it actually needs to)
  647. if (!dependsOnSelf && !plugin.IsSelf && !plugin.IsBare)
  648. {
  649. Logger.Loader.Warn($"Plugin '{plugin.Id}' does not depend on any particular loader version; assuming its incompatible");
  650. ignoredPlugins.Add(plugin, new(Reason.Dependency)
  651. {
  652. ReasonText = "Does not depend on any loader version, so it is assumed to be incompatible",
  653. RelatedTo = SelfMeta
  654. });
  655. ignored = true;
  656. return;
  657. }
  658. // exit early if we've decided we need to be disabled
  659. if (disabled)
  660. return;
  661. // handle LoadsAfter populated by Features processing
  662. foreach (var loadAfter in plugin.LoadsAfter)
  663. {
  664. if (TryResolveId(loadAfter.Id, out _, out _, out _))
  665. {
  666. // do nothing, because the plugin is already in the LoadsAfter set
  667. }
  668. }
  669. // then handle loadafters
  670. foreach (var id in plugin.Manifest.LoadAfter)
  671. {
  672. if (TryResolveId(id, out var meta, out var depDisabled, out var depIgnored))
  673. {
  674. // we only want to make sure to loadafter if its not ignored
  675. // if its disabled, we still wanna track it where possible
  676. _ = plugin.LoadsAfter.Add(meta);
  677. }
  678. }
  679. // after we handle dependencies and loadafters, then check conflicts
  680. foreach (var (id, range) in plugin.Manifest.Conflicts)
  681. {
  682. Logger.Loader.Trace($">- Checking conflict '{id}' {range}");
  683. // this lookup must be partial to prevent loadBefore/conflictsWith from creating a recursion loop
  684. if (TryResolveId(id, out var meta, out var conflDisabled, out var conflIgnored, partial: true)
  685. && range.Matches(meta.HVersion)
  686. && !conflIgnored && !conflDisabled) // the conflict is only *actually* a problem if it is both not ignored and not disabled
  687. {
  688. Logger.Loader.Warn($"Plugin '{plugin.Id}' conflicts with {meta.Id}@{meta.HVersion}; ignoring '{plugin.Id}'");
  689. ignoredPlugins.Add(plugin, new(Reason.Conflict)
  690. {
  691. ReasonText = $"Conflicts with {meta.Id}@{meta.HVersion}",
  692. RelatedTo = meta
  693. });
  694. ignored = true;
  695. return;
  696. }
  697. }
  698. // specifically check if some strange stuff happened (like graph loops) causing this to be ignored
  699. // from some other invocation
  700. if (!ignoredPlugins.ContainsKey(plugin))
  701. {
  702. // we can now load the current plugin
  703. Logger.Loader.Trace($"->'{plugin.Name}' loads here");
  704. outputOrder!.Add(plugin);
  705. }
  706. // loadbefores have already been preprocessed into loadafters
  707. Logger.Loader.Trace($">Processed '{plugin.Name}'");
  708. }
  709. // run TryResolveId over every plugin, which recursively calculates load order
  710. foreach (var plugin in pluginsToProcess)
  711. {
  712. _ = TryResolveId(plugin.Id, out _, out _, out _);
  713. }
  714. // by this point, outputOrder contains the full load order
  715. }
  716. DisabledConfig.Instance.Changed();
  717. DisabledPlugins = disabledPlugins;
  718. PluginsMetadata = outputOrder;
  719. }
  720. internal static void InitFeatures()
  721. {
  722. foreach (var meta in PluginsMetadata)
  723. {
  724. foreach (var feature in meta.Manifest.Features
  725. .SelectMany(f => f.Value.Select(o => (f.Key, o)))
  726. .Select(t => new Feature.Instance(meta, t.Key, t.o)))
  727. {
  728. if (feature.TryGetDefiningPlugin(out var plugin) && plugin == null)
  729. { // this is a DefineFeature, so we want to initialize it early
  730. if (!feature.TryCreate(out var inst))
  731. {
  732. Logger.Features.Error($"Error evaluating {feature.Name}: {inst.InvalidMessage}");
  733. }
  734. else
  735. {
  736. meta.InternalFeatures.Add(inst);
  737. }
  738. }
  739. else
  740. { // this is literally any other feature, so we want to delay its initialization
  741. _ = meta.UnloadedFeatures.Add(feature);
  742. }
  743. }
  744. }
  745. // at this point we have pre-initialized all features, so we can go ahead and use them to add stuff to the dep resolver
  746. foreach (var meta in PluginsMetadata)
  747. {
  748. foreach (var feature in meta.UnloadedFeatures)
  749. {
  750. if (feature.TryGetDefiningPlugin(out var plugin))
  751. {
  752. if (plugin != meta && plugin != null)
  753. { // if the feature is not applied to the defining feature
  754. _ = meta.LoadsAfter.Add(plugin);
  755. }
  756. if (plugin != null)
  757. {
  758. plugin.CreateFeaturesWhenLoaded.Add(feature);
  759. }
  760. }
  761. else
  762. {
  763. Logger.Features.Warn($"No such feature {feature.Name}");
  764. }
  765. }
  766. }
  767. }
  768. internal static void ReleaseAll(bool full = false)
  769. {
  770. if (full)
  771. {
  772. ignoredPlugins = new();
  773. }
  774. else
  775. {
  776. foreach (var m in PluginsMetadata)
  777. ignoredPlugins.Add(m, new IgnoreReason(Reason.Released));
  778. foreach (var m in ignoredPlugins.Keys)
  779. { // clean them up so we can still use the metadata for updates
  780. m.InternalFeatures.Clear();
  781. m.PluginType = null;
  782. m.Assembly = null!;
  783. }
  784. }
  785. PluginsMetadata = new List<PluginMetadata>();
  786. DisabledPlugins = new List<PluginMetadata>();
  787. Feature.Reset();
  788. GC.Collect();
  789. GC.WaitForPendingFinalizers();
  790. }
  791. internal static void Load(PluginMetadata meta)
  792. {
  793. if (meta is { Assembly: null, PluginType: not null })
  794. meta.Assembly = Assembly.LoadFrom(meta.File.FullName);
  795. }
  796. internal static PluginExecutor? InitPlugin(PluginMetadata meta, IEnumerable<PluginMetadata> alreadyLoaded)
  797. {
  798. if (meta.Manifest.GameVersion is { } gv && gv != UnityGame.GameVersion)
  799. Logger.Loader.Warn($"Mod {meta.Name} developed for game version {gv}, so it may not work properly.");
  800. if (meta.IsSelf)
  801. return new PluginExecutor(meta, PluginExecutor.Special.Self);
  802. foreach (var dep in meta.Dependencies)
  803. {
  804. if (alreadyLoaded.Contains(dep)) continue;
  805. // otherwise...
  806. if (ignoredPlugins.TryGetValue(dep, out var reason))
  807. { // was added to the ignore list
  808. ignoredPlugins.Add(meta, new IgnoreReason(Reason.Dependency)
  809. {
  810. ReasonText = $"Dependency was ignored at load time: {reason.ReasonText}",
  811. RelatedTo = dep
  812. });
  813. }
  814. else
  815. { // was not added to ignore list
  816. ignoredPlugins.Add(meta, new IgnoreReason(Reason.Dependency)
  817. {
  818. ReasonText = $"Dependency was not already loaded at load time, but was also not ignored",
  819. RelatedTo = dep
  820. });
  821. }
  822. return null;
  823. }
  824. if (meta.IsBare)
  825. return new PluginExecutor(meta, PluginExecutor.Special.Bare);
  826. Load(meta);
  827. PluginExecutor exec;
  828. try
  829. {
  830. exec = new PluginExecutor(meta);
  831. }
  832. catch (Exception e)
  833. {
  834. Logger.Loader.Error($"Error creating executor for {meta.Name}");
  835. Logger.Loader.Error(e);
  836. return null;
  837. }
  838. foreach (var feature in meta.Features)
  839. {
  840. try
  841. {
  842. feature.BeforeInit(meta);
  843. }
  844. catch (Exception e)
  845. {
  846. Logger.Loader.Critical($"Feature errored in {nameof(Feature.BeforeInit)}:");
  847. Logger.Loader.Critical(e);
  848. }
  849. }
  850. try
  851. {
  852. exec.Create();
  853. }
  854. catch (Exception e)
  855. {
  856. Logger.Loader.Error($"Could not init plugin {meta.Name}");
  857. Logger.Loader.Error(e);
  858. ignoredPlugins.Add(meta, new IgnoreReason(Reason.Error)
  859. {
  860. ReasonText = "Error occurred while initializing",
  861. Error = e
  862. });
  863. return null;
  864. }
  865. // TODO: make this new features system behave better wrt DynamicInit plugins
  866. foreach (var feature in meta.CreateFeaturesWhenLoaded)
  867. {
  868. if (!feature.TryCreate(out var inst))
  869. {
  870. Logger.Features.Warn($"Could not create instance of feature {feature.Name}: {inst.InvalidMessage}");
  871. }
  872. else
  873. {
  874. feature.AppliedTo.InternalFeatures.Add(inst);
  875. _ = feature.AppliedTo.UnloadedFeatures.Remove(feature);
  876. }
  877. }
  878. meta.CreateFeaturesWhenLoaded.Clear(); // if a plugin is loaded twice, for the moment, we don't want to create the feature twice
  879. foreach (var feature in meta.Features)
  880. try
  881. {
  882. feature.AfterInit(meta, exec.Instance);
  883. }
  884. catch (Exception e)
  885. {
  886. Logger.Loader.Critical($"Feature errored in {nameof(Feature.AfterInit)}:");
  887. Logger.Loader.Critical(e);
  888. }
  889. return exec;
  890. }
  891. internal static bool IsFirstLoadComplete { get; private set; }
  892. internal static List<PluginExecutor> LoadPlugins()
  893. {
  894. DisabledPlugins.ForEach(Load); // make sure they get loaded into memory so their metadata and stuff can be read more easily
  895. var list = new List<PluginExecutor>();
  896. var loaded = new HashSet<PluginMetadata>();
  897. foreach (var meta in PluginsMetadata)
  898. {
  899. try
  900. {
  901. var exec = InitPlugin(meta, loaded);
  902. if (exec != null)
  903. {
  904. list.Add(exec);
  905. _ = loaded.Add(meta);
  906. }
  907. }
  908. catch (Exception e)
  909. {
  910. Logger.Default.Critical($"Uncaught exception while loading plugin {meta.Name}:");
  911. Logger.Default.Critical(e);
  912. }
  913. }
  914. // TODO: should this be somewhere else?
  915. IsFirstLoadComplete = true;
  916. return list;
  917. }
  918. }
  919. }