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.

536 lines
26 KiB

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