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.

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