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.

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