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.

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