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.

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