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.

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