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.

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