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.

500 lines
25 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. using System;
  2. using System.Collections;
  3. using System.IO;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Reflection;
  7. using System.Runtime.InteropServices;
  8. using System.Text;
  9. using IPA.Config;
  10. using IPA.Old;
  11. using IPA.Utilities;
  12. using Mono.Cecil;
  13. using UnityEngine;
  14. using Logger = IPA.Logging.Logger;
  15. using System.Threading.Tasks;
  16. using System.Threading;
  17. using IPA.Utilities.Async;
  18. #if NET4
  19. using TaskEx = System.Threading.Tasks.Task;
  20. using TaskEx6 = System.Threading.Tasks.Task;
  21. using Task = System.Threading.Tasks.Task;
  22. #endif
  23. #if NET3
  24. using Net3_Proxy;
  25. using Path = Net3_Proxy.Path;
  26. using File = Net3_Proxy.File;
  27. using Directory = Net3_Proxy.Directory;
  28. using Array = Net3_Proxy.Array;
  29. #endif
  30. namespace IPA.Loader
  31. {
  32. /// <summary>
  33. /// The manager class for all plugins.
  34. /// </summary>
  35. public static class PluginManager
  36. {
  37. #pragma warning disable CS0618 // Type or member is obsolete (IPlugin)
  38. private static List<PluginExecutor> _bsPlugins;
  39. internal static IEnumerable<PluginExecutor> BSMetas => _bsPlugins;
  40. /// <summary>
  41. /// Gets info about the enabled plugin with the specified name.
  42. /// </summary>
  43. /// <param name="name">the name of the plugin to get (must be an exact match)</param>
  44. /// <returns>the plugin metadata for the requested plugin or <see langword="null"/> if it doesn't exist or is disabled</returns>
  45. public static PluginMetadata GetPlugin(string name)
  46. => BSMetas.Select(p => p.Metadata).FirstOrDefault(p => p.Name == name);
  47. /// <summary>
  48. /// Gets info about the enabled plugin with the specified ID.
  49. /// </summary>
  50. /// <param name="name">the ID name of the plugin to get (must be an exact match)</param>
  51. /// <returns>the plugin metadata for the requested plugin or <see langword="null"/> if it doesn't exist or is disabled</returns>
  52. public static PluginMetadata GetPluginFromId(string name)
  53. => BSMetas.Select(p => p.Metadata).FirstOrDefault(p => p.Id == name);
  54. /// <summary>
  55. /// Gets a disabled plugin's metadata by its name.
  56. /// </summary>
  57. /// <param name="name">the name of the disabled plugin to get</param>
  58. /// <returns>the metadata for the corresponding plugin</returns>
  59. public static PluginMetadata GetDisabledPlugin(string name) =>
  60. DisabledPlugins.FirstOrDefault(p => p.Name == name);
  61. /// <summary>
  62. /// Gets a disabled plugin's metadata by its ID.
  63. /// </summary>
  64. /// <param name="name">the ID of the disabled plugin to get</param>
  65. /// <returns>the metadata for the corresponding plugin</returns>
  66. public static PluginMetadata GetDisabledPluginFromId(string name) =>
  67. DisabledPlugins.FirstOrDefault(p => p.Id == name);
  68. /// <summary>
  69. /// Creates a new transaction for mod enabling and disabling mods simultaneously.
  70. /// </summary>
  71. /// <returns>a new <see cref="StateTransitionTransaction"/> that captures the current state of loaded mods</returns>
  72. public static StateTransitionTransaction PluginStateTransaction()
  73. => new StateTransitionTransaction(EnabledPlugins, DisabledPlugins);
  74. private static readonly object commitTransactionLockObject = new object();
  75. internal static Task CommitTransaction(StateTransitionTransaction transaction)
  76. {
  77. if (!transaction.HasStateChanged) return TaskEx.WhenAll();
  78. if (!UnityGame.OnMainThread)
  79. {
  80. var transactionCopy = transaction.Clone();
  81. transaction.Dispose();
  82. return UnityMainThreadTaskScheduler.Factory.StartNew(() => CommitTransaction(transactionCopy)).Unwrap();
  83. }
  84. lock (commitTransactionLockObject)
  85. {
  86. if (transaction.CurrentlyEnabled.Except(EnabledPlugins)
  87. .Concat(EnabledPlugins.Except(transaction.CurrentlyEnabled)).Any()
  88. || transaction.CurrentlyDisabled.Except(DisabledPlugins)
  89. .Concat(DisabledPlugins.Except(transaction.CurrentlyDisabled)).Any())
  90. { // ensure that the transaction's base state reflects the current state, otherwise throw
  91. transaction.Dispose();
  92. throw new InvalidOperationException("Transaction no longer resembles the current state of plugins");
  93. }
  94. var toEnable = transaction.ToEnable;
  95. var toDisable = transaction.ToDisable;
  96. transaction.Dispose();
  97. using var disabledChangeTransaction = DisabledConfig.Instance.ChangeTransaction();
  98. {
  99. // first enable the mods that need to be
  100. void DeTree(List<PluginMetadata> into, IEnumerable<PluginMetadata> tree)
  101. {
  102. foreach (var st in tree)
  103. if (toEnable.Contains(st) && !into.Contains(st))
  104. {
  105. DeTree(into, st.Dependencies);
  106. into.Add(st);
  107. }
  108. }
  109. var enableOrder = new List<PluginMetadata>();
  110. DeTree(enableOrder, toEnable);
  111. foreach (var meta in enableOrder)
  112. {
  113. var executor = runtimeDisabledPlugins.FirstOrDefault(e => e.Metadata == meta);
  114. if (meta.RuntimeOptions == RuntimeOptions.DynamicInit)
  115. {
  116. if (executor != null)
  117. runtimeDisabledPlugins.Remove(executor);
  118. else
  119. executor = PluginLoader.InitPlugin(meta, EnabledPlugins);
  120. if (executor == null) continue; // couldn't initialize, skip to next
  121. }
  122. PluginLoader.DisabledPlugins.Remove(meta);
  123. DisabledConfig.Instance.DisabledModIds.Remove(meta.Id ?? meta.Name);
  124. PluginEnabled?.Invoke(meta, meta.RuntimeOptions != RuntimeOptions.DynamicInit);
  125. if (meta.RuntimeOptions == RuntimeOptions.DynamicInit)
  126. {
  127. _bsPlugins.Add(executor);
  128. try
  129. {
  130. executor.Enable();
  131. }
  132. catch (Exception e)
  133. {
  134. Logger.loader.Error($"Error while enabling {meta.Id}:");
  135. Logger.loader.Error(e);
  136. // this should still be considered enabled, hence its position
  137. }
  138. }
  139. }
  140. }
  141. var result = TaskEx.WhenAll();
  142. {
  143. // then disable the mods that need to be
  144. static DisableExecutor MakeDisableExec(PluginExecutor e)
  145. => new DisableExecutor
  146. {
  147. Executor = e,
  148. Dependents = BSMetas.Where(f => f.Metadata.Dependencies.Contains(e.Metadata)).Select(MakeDisableExec)
  149. };
  150. var disableExecs = toDisable.Select(m => BSMetas.FirstOrDefault(e => e.Metadata == m)).NonNull().ToArray(); // eagerly evaluate once
  151. foreach (var exec in disableExecs)
  152. {
  153. PluginLoader.DisabledPlugins.Add(exec.Metadata);
  154. DisabledConfig.Instance.DisabledModIds.Add(exec.Metadata.Id ?? exec.Metadata.Name);
  155. if (exec.Metadata.RuntimeOptions == RuntimeOptions.DynamicInit)
  156. {
  157. runtimeDisabledPlugins.Add(exec);
  158. _bsPlugins.Remove(exec);
  159. }
  160. PluginDisabled?.Invoke(exec.Metadata, exec.Metadata.RuntimeOptions != RuntimeOptions.DynamicInit);
  161. }
  162. var disableStructure = disableExecs.Select(MakeDisableExec);
  163. static Task Disable(DisableExecutor exec, Dictionary<PluginExecutor, Task> alreadyDisabled)
  164. {
  165. if (alreadyDisabled.TryGetValue(exec.Executor, out var task))
  166. return task;
  167. else
  168. {
  169. if (exec.Executor.Metadata.RuntimeOptions != RuntimeOptions.DynamicInit)
  170. return TaskEx6.FromException(new CannotRuntimeDisableException(exec.Executor.Metadata));
  171. var res = TaskEx.WhenAll(exec.Dependents.Select(d => Disable(d, alreadyDisabled)))
  172. .ContinueWith(t => t.IsFaulted
  173. ? TaskEx.WhenAll(t, TaskEx6.FromException(
  174. new CannotRuntimeDisableException(exec.Executor.Metadata, "Dependents cannot be disabled for plugin")))
  175. : exec.Executor.Disable(), UnityMainThreadTaskScheduler.Default).Unwrap();
  176. // We do not want to call the disable method if a dependent couldn't be disabled
  177. // By scheduling on a UnityMainThreadScheduler, we ensure that Disable() is always called on the Unity main thread
  178. alreadyDisabled.Add(exec.Executor, res);
  179. return res;
  180. }
  181. }
  182. var disabled = new Dictionary<PluginExecutor, Task>();
  183. result = TaskEx.WhenAll(disableStructure.Select(d => Disable(d, disabled)));
  184. }
  185. OnAnyPluginsStateChanged?.Invoke(result, toEnable, toDisable);
  186. // if there are any that are capable of enabling/disabling at runtime, run event handler
  187. if (toEnable.Concat(toDisable).Any(m => m.RuntimeOptions == RuntimeOptions.DynamicInit))
  188. OnPluginsStateChanged?.Invoke(result);
  189. //DisabledConfig.Instance.Changed();
  190. // changed is handled by transaction
  191. return result;
  192. }
  193. }
  194. private struct DisableExecutor
  195. {
  196. public PluginExecutor Executor;
  197. public IEnumerable<DisableExecutor> Dependents;
  198. }
  199. /// <summary>
  200. /// Checks if a given plugin is disabled.
  201. /// </summary>
  202. /// <param name="meta">the plugin to check</param>
  203. /// <returns><see langword="true"/> if the plugin is disabled, <see langword="false"/> otherwise.</returns>
  204. public static bool IsDisabled(PluginMetadata meta) => DisabledPlugins.Contains(meta);
  205. /// <summary>
  206. /// Checks if a given plugin is enabled.
  207. /// </summary>
  208. /// <param name="meta">the plugin to check</param>
  209. /// <returns><see langword="true"/> if the plugin is enabled, <see langword="false"/> otherwise.</returns>
  210. public static bool IsEnabled(PluginMetadata meta) => BSMetas.Any(p => p.Metadata == meta);
  211. /// <summary>
  212. /// An invoker for the <see cref="PluginEnabled"/> event.
  213. /// </summary>
  214. /// <param name="plugin">the plugin that was enabled</param>
  215. /// <param name="needsRestart">whether it needs a restart to take effect</param>
  216. public delegate void PluginEnableDelegate(PluginMetadata plugin, bool needsRestart);
  217. /// <summary>
  218. /// An invoker for the <see cref="PluginDisabled"/> event.
  219. /// </summary>
  220. /// <param name="plugin">the plugin that was disabled</param>
  221. /// <param name="needsRestart">whether it needs a restart to take effect</param>
  222. public delegate void PluginDisableDelegate(PluginMetadata plugin, bool needsRestart);
  223. /// <summary>
  224. /// A delegate representing a state change event for any plugin.
  225. /// </summary>
  226. /// <param name="changeTask">the <see cref="Task"/> representing the change</param>
  227. /// <param name="enabled">the plugins that were enabled in the change</param>
  228. /// <param name="disabled">the plugins that were disabled in the change</param>
  229. public delegate void OnAnyPluginsStateChangedDelegate(Task changeTask, IEnumerable<PluginMetadata> enabled, IEnumerable<PluginMetadata> disabled);
  230. /// <summary>
  231. /// Called whenever a plugin is enabled, before the plugin in question is enabled.
  232. /// </summary>
  233. public static event PluginEnableDelegate PluginEnabled;
  234. /// <summary>
  235. /// Called whenever a plugin is disabled, before the plugin in question is enabled.
  236. /// </summary>
  237. public static event PluginDisableDelegate PluginDisabled;
  238. /// <summary>
  239. /// Called whenever any plugins have their state changed at runtime with the <see cref="Task"/> representing that state change.
  240. /// </summary>
  241. /// <remarks>
  242. /// Note that this is called on the Unity main thread, and cannot therefore block, as the <see cref="Task"/>
  243. /// provided represents operations that also run on the Unity main thread.
  244. /// </remarks>
  245. public static event Action<Task> OnPluginsStateChanged;
  246. /// <summary>
  247. /// Called whenever any plugins, regardless of whether or not their change occurs during runtime, have their state changed.
  248. /// </summary>
  249. /// <remarks>
  250. /// Note that this is called on the Unity main thread, and cannot therefore block, as the <see cref="Task"/>
  251. /// provided represents operations that also run on the Unity main thread.
  252. /// </remarks>
  253. public static event OnAnyPluginsStateChangedDelegate OnAnyPluginsStateChanged;
  254. /// <summary>
  255. /// Gets a list of all enabled BSIPA plugins. Use <see cref="EnabledPlugins"/> instead of this.
  256. /// </summary>
  257. /// <value>a collection of all enabled plugins as <see cref="PluginMetadata"/>s</value>
  258. [Obsolete("This is an old name that no longer accurately represents its value. Use EnabledPlugins instead.")]
  259. public static IEnumerable<PluginMetadata> AllPlugins => EnabledPlugins;
  260. /// <summary>
  261. /// Gets a collection of all enabled plugins, as represented by <see cref="PluginMetadata"/>.
  262. /// </summary>
  263. /// <value>a collection of all enabled plugins</value>
  264. public static IEnumerable<PluginMetadata> EnabledPlugins => BSMetas.Select(p => p.Metadata);
  265. /// <summary>
  266. /// Gets a list of disabled BSIPA plugins.
  267. /// </summary>
  268. /// <value>a collection of all disabled plugins as <see cref="PluginMetadata"/></value>
  269. public static IEnumerable<PluginMetadata> DisabledPlugins => PluginLoader.DisabledPlugins;
  270. private static readonly HashSet<PluginExecutor> runtimeDisabledPlugins = new HashSet<PluginExecutor>();
  271. /// <summary>
  272. /// Gets a read-only dictionary of an ignored plugin to the reason it was ignored, as an <see cref="IgnoreReason"/>.
  273. /// </summary>
  274. /// <value>a dictionary of <see cref="PluginMetadata"/> to <see cref="IgnoreReason"/> of ignored plugins</value>
  275. public static IReadOnlyDictionary<PluginMetadata, IgnoreReason> IgnoredPlugins => PluginLoader.ignoredPlugins;
  276. /// <summary>
  277. /// An <see cref="IEnumerable{T}"/> of old IPA plugins.
  278. /// </summary>
  279. /// <value>all legacy plugin instances</value>
  280. [Obsolete("This exists only to provide support for legacy IPA plugins based on the IPlugin interface.")]
  281. public static IEnumerable<Old.IPlugin> Plugins => _ipaPlugins;
  282. private static List<Old.IPlugin> _ipaPlugins;
  283. internal static IConfigProvider SelfConfigProvider { get; set; }
  284. internal static void Load()
  285. {
  286. string pluginDirectory = UnityGame.PluginsPath;
  287. // Process.GetCurrentProcess().MainModule crashes the game and Assembly.GetEntryAssembly() is NULL,
  288. // so we need to resort to P/Invoke
  289. string exeName = Path.GetFileNameWithoutExtension(AppInfo.StartupPath);
  290. _bsPlugins = new List<PluginExecutor>();
  291. _ipaPlugins = new List<Old.IPlugin>();
  292. if (!Directory.Exists(pluginDirectory)) return;
  293. string cacheDir = Path.Combine(pluginDirectory, ".cache");
  294. if (!Directory.Exists(cacheDir))
  295. {
  296. Directory.CreateDirectory(cacheDir);
  297. }
  298. else
  299. {
  300. foreach (string plugin in Directory.GetFiles(cacheDir, "*"))
  301. File.Delete(plugin);
  302. }
  303. // initialize BSIPA plugins first
  304. _bsPlugins.AddRange(PluginLoader.LoadPlugins());
  305. var metadataPaths = PluginLoader.PluginsMetadata.Select(m => m.File.FullName).ToList();
  306. var ignoredPaths = PluginLoader.ignoredPlugins.Select(m => m.Key.File.FullName)
  307. .Concat(PluginLoader.ignoredPlugins.SelectMany(m => m.Key.AssociatedFiles.Select(f => f.FullName))).ToList();
  308. var disabledPaths = DisabledPlugins.Select(m => m.File.FullName).ToList();
  309. //Copy plugins to .cache
  310. string[] originalPlugins = Directory.GetFiles(pluginDirectory, "*.dll");
  311. foreach (string s in originalPlugins)
  312. {
  313. if (metadataPaths.Contains(s)) continue;
  314. if (ignoredPaths.Contains(s)) continue;
  315. if (disabledPaths.Contains(s)) continue;
  316. string pluginCopy = Path.Combine(cacheDir, Path.GetFileName(s));
  317. #region Fix assemblies for refactor
  318. var module = ModuleDefinition.ReadModule(Path.Combine(pluginDirectory, s));
  319. foreach (var @ref in module.AssemblyReferences)
  320. { // fix assembly references
  321. if (@ref.Name == "IllusionPlugin" || @ref.Name == "IllusionInjector")
  322. {
  323. @ref.Name = "IPA.Loader";
  324. }
  325. }
  326. foreach (var @ref in module.GetTypeReferences())
  327. { // fix type references
  328. if (@ref.FullName == "IllusionPlugin.IPlugin") @ref.Namespace = "IPA.Old"; //@ref.Name = "";
  329. if (@ref.FullName == "IllusionPlugin.IEnhancedPlugin") @ref.Namespace = "IPA.Old"; //@ref.Name = "";
  330. if (@ref.FullName == "IllusionPlugin.IniFile") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  331. if (@ref.FullName == "IllusionPlugin.IModPrefs") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  332. if (@ref.FullName == "IllusionPlugin.ModPrefs") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  333. if (@ref.FullName == "IllusionPlugin.Utils.ReflectionUtil") @ref.Namespace = "IPA.Utilities"; //@ref.Name = "";
  334. if (@ref.FullName == "IllusionPlugin.Logging.Logger") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  335. if (@ref.FullName == "IllusionPlugin.Logging.LogPrinter") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  336. if (@ref.FullName == "IllusionInjector.PluginManager") @ref.Namespace = "IPA.Loader"; //@ref.Name = "";
  337. if (@ref.FullName == "IllusionInjector.PluginComponent") @ref.Namespace = "IPA.Loader"; //@ref.Name = "";
  338. if (@ref.FullName == "IllusionInjector.CompositeBSPlugin") @ref.Namespace = "IPA.Loader.Composite"; //@ref.Name = "";
  339. if (@ref.FullName == "IllusionInjector.CompositeIPAPlugin") @ref.Namespace = "IPA.Loader.Composite"; //@ref.Name = "";
  340. if (@ref.FullName == "IllusionInjector.Logging.UnityLogInterceptor") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  341. if (@ref.FullName == "IllusionInjector.Logging.StandardLogger") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  342. if (@ref.FullName == "IllusionInjector.Updating.SelfPlugin") @ref.Namespace = "IPA.Updating"; //@ref.Name = "";
  343. if (@ref.FullName == "IllusionInjector.Updating.Backup.BackupUnit") @ref.Namespace = "IPA.Updating.Backup"; //@ref.Name = "";
  344. if (@ref.Namespace == "IllusionInjector.Utilities") @ref.Namespace = "IPA.Utilities"; //@ref.Name = "";
  345. if (@ref.Namespace == "IllusionInjector.Logging.Printers") @ref.Namespace = "IPA.Logging.Printers"; //@ref.Name = "";
  346. }
  347. module.Write(pluginCopy);
  348. #endregion
  349. }
  350. //Load copied plugins
  351. string[] copiedPlugins = Directory.GetFiles(cacheDir, "*.dll");
  352. foreach (string s in copiedPlugins)
  353. {
  354. var result = LoadPluginsFromFile(s);
  355. if (result == null) continue;
  356. _ipaPlugins.AddRange(result.NonNull());
  357. }
  358. Logger.log.Info(exeName);
  359. Logger.log.Info($"Running on Unity {Application.unityVersion}");
  360. Logger.log.Info($"Game version {UnityGame.GameVersion}");
  361. Logger.log.Info("-----------------------------");
  362. Logger.log.Info($"Loading plugins from {Utils.GetRelativePath(pluginDirectory, Environment.CurrentDirectory)} and found {_bsPlugins.Count + _ipaPlugins.Count}");
  363. Logger.log.Info("-----------------------------");
  364. foreach (var plugin in _bsPlugins)
  365. {
  366. Logger.log.Info($"{plugin.Metadata.Name} ({plugin.Metadata.Id}): {plugin.Metadata.Version}");
  367. }
  368. Logger.log.Info("-----------------------------");
  369. foreach (var plugin in _ipaPlugins)
  370. {
  371. Logger.log.Info($"{plugin.Name}: {plugin.Version}");
  372. }
  373. Logger.log.Info("-----------------------------");
  374. }
  375. private static IEnumerable<Old.IPlugin> LoadPluginsFromFile(string file)
  376. {
  377. var ipaPlugins = new List<Old.IPlugin>();
  378. if (!File.Exists(file) || !file.EndsWith(".dll", true, null))
  379. return ipaPlugins;
  380. T OptionalGetPlugin<T>(Type t) where T : class
  381. {
  382. if (t.FindInterfaces((t, o) => t == (o as Type), typeof(T)).Length > 0)
  383. {
  384. try
  385. {
  386. T pluginInstance = Activator.CreateInstance(t) as T;
  387. return pluginInstance;
  388. }
  389. catch (Exception e)
  390. {
  391. Logger.loader.Error($"Could not load plugin {t.FullName} in {Path.GetFileName(file)}! {e}");
  392. }
  393. }
  394. return null;
  395. }
  396. try
  397. {
  398. Assembly assembly = Assembly.LoadFrom(file);
  399. foreach (Type t in assembly.GetTypes())
  400. {
  401. var ipaPlugin = OptionalGetPlugin<Old.IPlugin>(t);
  402. if (ipaPlugin != null)
  403. {
  404. ipaPlugins.Add(ipaPlugin);
  405. }
  406. }
  407. }
  408. catch (ReflectionTypeLoadException e)
  409. {
  410. Logger.loader.Error($"Could not load the following types from {Path.GetFileName(file)}:");
  411. Logger.loader.Error($" {string.Join("\n ", e.LoaderExceptions?.Select(e1 => e1?.Message).StrJP() ?? Array.Empty<string>())}");
  412. }
  413. catch (Exception e)
  414. {
  415. Logger.loader.Error($"Could not load {Path.GetFileName(file)}!");
  416. Logger.loader.Error(e);
  417. }
  418. return ipaPlugins;
  419. }
  420. internal static class AppInfo
  421. {
  422. [DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = false)]
  423. private static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length);
  424. private static HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero);
  425. public static string StartupPath
  426. {
  427. get
  428. {
  429. StringBuilder stringBuilder = new StringBuilder(260);
  430. GetModuleFileName(NullHandleRef, stringBuilder, stringBuilder.Capacity);
  431. return stringBuilder.ToString();
  432. }
  433. }
  434. }
  435. #pragma warning restore CS0618 // Type or member is obsolete (IPlugin)
  436. }
  437. }