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.

458 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 => TaskEx.WhenAll(t, exec.Executor.Disable()), UnityMainThreadTaskScheduler.Default).Unwrap();
  167. // The WhenAll above allows us to wait for the executor to disable, but still propagate errors
  168. // By scheduling on a UnityMainThreadScheduler, we ensure that Disable() is always called on the Unity main thread
  169. alreadyDisabled.Add(exec.Executor, res);
  170. return res;
  171. }
  172. }
  173. var disabled = new Dictionary<PluginExecutor, Task>();
  174. result = TaskEx.WhenAll(disableStructure.Select(d => Disable(d, disabled)));
  175. }
  176. //DisabledConfig.Instance.Changed();
  177. // changed is handled by transaction
  178. return result;
  179. }
  180. }
  181. private struct DisableExecutor
  182. {
  183. public PluginExecutor Executor;
  184. public IEnumerable<DisableExecutor> Dependents;
  185. }
  186. /// <summary>
  187. /// Checks if a given plugin is disabled.
  188. /// </summary>
  189. /// <param name="meta">the plugin to check</param>
  190. /// <returns><see langword="true"/> if the plugin is disabled, <see langword="false"/> otherwise.</returns>
  191. public static bool IsDisabled(PluginMetadata meta) => DisabledPlugins.Contains(meta);
  192. /// <summary>
  193. /// Checks if a given plugin is enabled.
  194. /// </summary>
  195. /// <param name="meta">the plugin to check</param>
  196. /// <returns><see langword="true"/> if the plugin is enabled, <see langword="false"/> otherwise.</returns>
  197. public static bool IsEnabled(PluginMetadata meta) => BSMetas.Any(p => p.Metadata == meta);
  198. /// <summary>
  199. /// An invoker for the <see cref="PluginEnabled"/> event.
  200. /// </summary>
  201. /// <param name="plugin">the plugin that was enabled</param>
  202. /// <param name="needsRestart">whether it needs a restart to take effect</param>
  203. public delegate void PluginEnableDelegate(PluginMetadata plugin, bool needsRestart);
  204. /// <summary>
  205. /// An invoker for the <see cref="PluginDisabled"/> event.
  206. /// </summary>
  207. /// <param name="plugin">the plugin that was disabled</param>
  208. /// <param name="needsRestart">whether it needs a restart to take effect</param>
  209. public delegate void PluginDisableDelegate(PluginMetadata plugin, bool needsRestart);
  210. /// <summary>
  211. /// Called whenever a plugin is enabled.
  212. /// </summary>
  213. public static event PluginEnableDelegate PluginEnabled;
  214. /// <summary>
  215. /// Called whenever a plugin is disabled.
  216. /// </summary>
  217. public static event PluginDisableDelegate PluginDisabled;
  218. /// <summary>
  219. /// Gets a list of all enabled BSIPA plugins. Use <see cref="EnabledPlugins"/> instead of this.
  220. /// </summary>
  221. /// <value>a collection of all enabled plugins as <see cref="PluginMetadata"/>s</value>
  222. [Obsolete("This is an old name that no longer accurately represents its value. Use EnabledPlugins instead.")]
  223. public static IEnumerable<PluginMetadata> AllPlugins => EnabledPlugins;
  224. /// <summary>
  225. /// Gets a collection of all enabled plugins, as represented by <see cref="PluginMetadata"/>.
  226. /// </summary>
  227. /// <value>a collection of all enabled plugins</value>
  228. public static IEnumerable<PluginMetadata> EnabledPlugins => BSMetas.Select(p => p.Metadata);
  229. /// <summary>
  230. /// Gets a list of disabled BSIPA plugins.
  231. /// </summary>
  232. /// <value>a collection of all disabled plugins as <see cref="PluginMetadata"/></value>
  233. public static IEnumerable<PluginMetadata> DisabledPlugins => PluginLoader.DisabledPlugins;
  234. private static readonly HashSet<PluginExecutor> runtimeDisabledPlugins = new HashSet<PluginExecutor>();
  235. /// <summary>
  236. /// An <see cref="IEnumerable{T}"/> of old IPA plugins.
  237. /// </summary>
  238. /// <value>all legacy plugin instances</value>
  239. [Obsolete("This exists only to provide support for legacy IPA plugins based on the IPlugin interface.")]
  240. public static IEnumerable<Old.IPlugin> Plugins => _ipaPlugins;
  241. private static List<Old.IPlugin> _ipaPlugins;
  242. internal static IConfigProvider SelfConfigProvider { get; set; }
  243. internal static void Load()
  244. {
  245. string pluginDirectory = UnityGame.PluginsPath;
  246. // Process.GetCurrentProcess().MainModule crashes the game and Assembly.GetEntryAssembly() is NULL,
  247. // so we need to resort to P/Invoke
  248. string exeName = Path.GetFileNameWithoutExtension(AppInfo.StartupPath);
  249. _bsPlugins = new List<PluginExecutor>();
  250. _ipaPlugins = new List<Old.IPlugin>();
  251. if (!Directory.Exists(pluginDirectory)) return;
  252. string cacheDir = Path.Combine(pluginDirectory, ".cache");
  253. if (!Directory.Exists(cacheDir))
  254. {
  255. Directory.CreateDirectory(cacheDir);
  256. }
  257. else
  258. {
  259. foreach (string plugin in Directory.GetFiles(cacheDir, "*"))
  260. File.Delete(plugin);
  261. }
  262. // initialize BSIPA plugins first
  263. _bsPlugins.AddRange(PluginLoader.LoadPlugins());
  264. var metadataPaths = PluginLoader.PluginsMetadata.Select(m => m.File.FullName).ToList();
  265. var ignoredPaths = PluginLoader.ignoredPlugins.Select(m => m.Key.File.FullName)
  266. .Concat(PluginLoader.ignoredPlugins.SelectMany(m => m.Key.AssociatedFiles.Select(f => f.FullName))).ToList();
  267. var disabledPaths = DisabledPlugins.Select(m => m.File.FullName).ToList();
  268. //Copy plugins to .cache
  269. string[] originalPlugins = Directory.GetFiles(pluginDirectory, "*.dll");
  270. foreach (string s in originalPlugins)
  271. {
  272. if (metadataPaths.Contains(s)) continue;
  273. if (ignoredPaths.Contains(s)) continue;
  274. if (disabledPaths.Contains(s)) continue;
  275. string pluginCopy = Path.Combine(cacheDir, Path.GetFileName(s));
  276. #region Fix assemblies for refactor
  277. var module = ModuleDefinition.ReadModule(Path.Combine(pluginDirectory, s));
  278. foreach (var @ref in module.AssemblyReferences)
  279. { // fix assembly references
  280. if (@ref.Name == "IllusionPlugin" || @ref.Name == "IllusionInjector")
  281. {
  282. @ref.Name = "IPA.Loader";
  283. }
  284. }
  285. foreach (var @ref in module.GetTypeReferences())
  286. { // fix type references
  287. if (@ref.FullName == "IllusionPlugin.IPlugin") @ref.Namespace = "IPA.Old"; //@ref.Name = "";
  288. if (@ref.FullName == "IllusionPlugin.IEnhancedPlugin") @ref.Namespace = "IPA.Old"; //@ref.Name = "";
  289. if (@ref.FullName == "IllusionPlugin.IniFile") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  290. if (@ref.FullName == "IllusionPlugin.IModPrefs") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  291. if (@ref.FullName == "IllusionPlugin.ModPrefs") @ref.Namespace = "IPA.Config"; //@ref.Name = "";
  292. if (@ref.FullName == "IllusionPlugin.Utils.ReflectionUtil") @ref.Namespace = "IPA.Utilities"; //@ref.Name = "";
  293. if (@ref.FullName == "IllusionPlugin.Logging.Logger") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  294. if (@ref.FullName == "IllusionPlugin.Logging.LogPrinter") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  295. if (@ref.FullName == "IllusionInjector.PluginManager") @ref.Namespace = "IPA.Loader"; //@ref.Name = "";
  296. if (@ref.FullName == "IllusionInjector.PluginComponent") @ref.Namespace = "IPA.Loader"; //@ref.Name = "";
  297. if (@ref.FullName == "IllusionInjector.CompositeBSPlugin") @ref.Namespace = "IPA.Loader.Composite"; //@ref.Name = "";
  298. if (@ref.FullName == "IllusionInjector.CompositeIPAPlugin") @ref.Namespace = "IPA.Loader.Composite"; //@ref.Name = "";
  299. if (@ref.FullName == "IllusionInjector.Logging.UnityLogInterceptor") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  300. if (@ref.FullName == "IllusionInjector.Logging.StandardLogger") @ref.Namespace = "IPA.Logging"; //@ref.Name = "";
  301. if (@ref.FullName == "IllusionInjector.Updating.SelfPlugin") @ref.Namespace = "IPA.Updating"; //@ref.Name = "";
  302. if (@ref.FullName == "IllusionInjector.Updating.Backup.BackupUnit") @ref.Namespace = "IPA.Updating.Backup"; //@ref.Name = "";
  303. if (@ref.Namespace == "IllusionInjector.Utilities") @ref.Namespace = "IPA.Utilities"; //@ref.Name = "";
  304. if (@ref.Namespace == "IllusionInjector.Logging.Printers") @ref.Namespace = "IPA.Logging.Printers"; //@ref.Name = "";
  305. }
  306. module.Write(pluginCopy);
  307. #endregion
  308. }
  309. //Load copied plugins
  310. string[] copiedPlugins = Directory.GetFiles(cacheDir, "*.dll");
  311. foreach (string s in copiedPlugins)
  312. {
  313. var result = LoadPluginsFromFile(s);
  314. if (result == null) continue;
  315. _ipaPlugins.AddRange(result.NonNull());
  316. }
  317. Logger.log.Info(exeName);
  318. Logger.log.Info($"Running on Unity {Application.unityVersion}");
  319. Logger.log.Info($"Game version {UnityGame.GameVersion}");
  320. Logger.log.Info("-----------------------------");
  321. Logger.log.Info($"Loading plugins from {Utils.GetRelativePath(pluginDirectory, Environment.CurrentDirectory)} and found {_bsPlugins.Count + _ipaPlugins.Count}");
  322. Logger.log.Info("-----------------------------");
  323. foreach (var plugin in _bsPlugins)
  324. {
  325. Logger.log.Info($"{plugin.Metadata.Name} ({plugin.Metadata.Id}): {plugin.Metadata.Version}");
  326. }
  327. Logger.log.Info("-----------------------------");
  328. foreach (var plugin in _ipaPlugins)
  329. {
  330. Logger.log.Info($"{plugin.Name}: {plugin.Version}");
  331. }
  332. Logger.log.Info("-----------------------------");
  333. }
  334. private static IEnumerable<Old.IPlugin> LoadPluginsFromFile(string file)
  335. {
  336. var ipaPlugins = new List<Old.IPlugin>();
  337. if (!File.Exists(file) || !file.EndsWith(".dll", true, null))
  338. return ipaPlugins;
  339. T OptionalGetPlugin<T>(Type t) where T : class
  340. {
  341. if (t.FindInterfaces((t, o) => t == (o as Type), typeof(T)).Length > 0)
  342. {
  343. try
  344. {
  345. T pluginInstance = Activator.CreateInstance(t) as T;
  346. return pluginInstance;
  347. }
  348. catch (Exception e)
  349. {
  350. Logger.loader.Error($"Could not load plugin {t.FullName} in {Path.GetFileName(file)}! {e}");
  351. }
  352. }
  353. return null;
  354. }
  355. try
  356. {
  357. Assembly assembly = Assembly.LoadFrom(file);
  358. foreach (Type t in assembly.GetTypes())
  359. {
  360. var ipaPlugin = OptionalGetPlugin<Old.IPlugin>(t);
  361. if (ipaPlugin != null)
  362. {
  363. ipaPlugins.Add(ipaPlugin);
  364. }
  365. }
  366. }
  367. catch (ReflectionTypeLoadException e)
  368. {
  369. Logger.loader.Error($"Could not load the following types from {Path.GetFileName(file)}:");
  370. Logger.loader.Error($" {string.Join("\n ", e.LoaderExceptions?.Select(e1 => e1?.Message).StrJP() ?? Array.Empty<string>())}");
  371. }
  372. catch (Exception e)
  373. {
  374. Logger.loader.Error($"Could not load {Path.GetFileName(file)}!");
  375. Logger.loader.Error(e);
  376. }
  377. return ipaPlugins;
  378. }
  379. internal static class AppInfo
  380. {
  381. [DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = false)]
  382. private static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length);
  383. private static HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero);
  384. public static string StartupPath
  385. {
  386. get
  387. {
  388. StringBuilder stringBuilder = new StringBuilder(260);
  389. GetModuleFileName(NullHandleRef, stringBuilder, stringBuilder.Capacity);
  390. return stringBuilder.ToString();
  391. }
  392. }
  393. }
  394. #pragma warning restore CS0618 // Type or member is obsolete (IPlugin)
  395. }
  396. }