Chainloader.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. using BepInEx.Configuration;
  2. using BepInEx.Logging;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Reflection;
  9. using System.Text;
  10. using System.Text.RegularExpressions;
  11. using UnityEngine;
  12. using UnityInjector.ConsoleUtil;
  13. using Logger = BepInEx.Logging.Logger;
  14. namespace BepInEx.Bootstrap
  15. {
  16. /// <summary>
  17. /// The manager and loader for all plugins, and the entry point for BepInEx plugin system.
  18. /// </summary>
  19. public static class Chainloader
  20. {
  21. /// <summary>
  22. /// The loaded and initialized list of plugins.
  23. /// </summary>
  24. public static List<BaseUnityPlugin> Plugins { get; private set; } = new List<BaseUnityPlugin>();
  25. /// <summary>
  26. /// The GameObject that all plugins are attached to as components.
  27. /// </summary>
  28. public static GameObject ManagerObject { get; private set; }
  29. private static bool _loaded = false;
  30. private static bool _initialized = false;
  31. /// <summary>
  32. /// Initializes BepInEx to be able to start the chainloader.
  33. /// </summary>
  34. public static void Initialize(string gameExePath, bool startConsole = true)
  35. {
  36. if (_initialized)
  37. return;
  38. // Set vitals
  39. if (gameExePath != null)
  40. {
  41. // Checking for null allows a more advanced initialization workflow, where the Paths class has been initialized before calling Chainloader.Initialize
  42. // This is used by Preloader to use environment variables, for example
  43. Paths.SetExecutablePath(gameExePath);
  44. }
  45. Paths.SetPluginPath(ConfigPluginsDirectory.Value);
  46. // Start logging
  47. if (ConsoleWindow.ConfigConsoleEnabled.Value && startConsole)
  48. {
  49. ConsoleWindow.Attach();
  50. Logger.Listeners.Add(new ConsoleLogListener());
  51. }
  52. // Fix for standard output getting overwritten by UnityLogger
  53. if (ConsoleWindow.StandardOut != null)
  54. {
  55. Console.SetOut(ConsoleWindow.StandardOut);
  56. var encoding = ConsoleWindow.ConfigConsoleShiftJis.Value ? 932 : (uint)Encoding.UTF8.CodePage;
  57. ConsoleEncoding.ConsoleCodePage = encoding;
  58. Console.OutputEncoding = ConsoleEncoding.GetEncoding(encoding);
  59. }
  60. Logger.Listeners.Add(new UnityLogListener());
  61. Logger.Listeners.Add(new DiskLogListener());
  62. if (!TraceLogSource.IsListening)
  63. Logger.Sources.Add(TraceLogSource.CreateSource());
  64. if (ConfigUnityLogging.Value)
  65. Logger.Sources.Add(new UnityLogSource());
  66. Logger.LogMessage("Chainloader ready");
  67. _initialized = true;
  68. }
  69. private static Regex allowedGuidRegex { get; } = new Regex(@"^[a-zA-Z0-9\._]+$");
  70. /// <summary>
  71. /// The entrypoint for the BepInEx plugin system.
  72. /// </summary>
  73. public static void Start()
  74. {
  75. if (_loaded)
  76. return;
  77. if (!_initialized)
  78. throw new InvalidOperationException("BepInEx has not been initialized. Please call Chainloader.Initialize prior to starting the chainloader instance.");
  79. if (!Directory.Exists(Paths.PluginPath))
  80. Directory.CreateDirectory(Paths.PluginPath);
  81. if (!Directory.Exists(Paths.PatcherPluginPath))
  82. Directory.CreateDirectory(Paths.PatcherPluginPath);
  83. try
  84. {
  85. var productNameProp = typeof(Application).GetProperty("productName", BindingFlags.Public | BindingFlags.Static);
  86. if (productNameProp != null)
  87. ConsoleWindow.Title =
  88. $"BepInEx {Assembly.GetExecutingAssembly().GetName().Version} - {productNameProp.GetValue(null, null)}";
  89. Logger.LogMessage("Chainloader started");
  90. ManagerObject = new GameObject("BepInEx_Manager");
  91. UnityEngine.Object.DontDestroyOnLoad(ManagerObject);
  92. string currentProcess = Process.GetCurrentProcess().ProcessName.ToLower();
  93. var globalPluginTypes = TypeLoader.LoadTypes<BaseUnityPlugin>(Paths.PluginPath).ToList();
  94. Dictionary<Type, BepInPlugin> selectedPluginTypes = new Dictionary<Type, BepInPlugin>(globalPluginTypes.Count);
  95. foreach (var pluginType in globalPluginTypes)
  96. {
  97. //Ensure metadata exists
  98. var metadata = MetadataHelper.GetMetadata(pluginType);
  99. if (metadata == null)
  100. {
  101. Logger.LogWarning($"Skipping type [{pluginType.FullName}] as no metadata attribute is specified");
  102. continue;
  103. }
  104. if (string.IsNullOrEmpty(metadata.GUID) || !allowedGuidRegex.IsMatch(metadata.GUID))
  105. {
  106. Logger.LogWarning($"Skipping type [{pluginType.FullName}] because its GUID [{metadata.GUID}] is of an illegal format.");
  107. continue;
  108. }
  109. if (selectedPluginTypes.Any(x => x.Value.GUID.Equals(metadata.GUID, StringComparison.OrdinalIgnoreCase)))
  110. {
  111. Logger.LogWarning($"Skipping type [{pluginType.FullName}] because its GUID [{metadata.GUID}] is already used by another plugin.");
  112. continue;
  113. }
  114. if (metadata.Version == null)
  115. {
  116. Logger.LogWarning($"Skipping type [{pluginType.FullName}] because its version is invalid.");
  117. continue;
  118. }
  119. if (metadata.Name == null)
  120. {
  121. Logger.LogWarning($"Skipping type [{pluginType.FullName}] because its name is null.");
  122. continue;
  123. }
  124. //Perform a filter for currently running process
  125. var filters = MetadataHelper.GetAttributes<BepInProcess>(pluginType);
  126. if (filters.Length != 0)
  127. {
  128. var result = filters.Any(x => x.ProcessName.ToLower().Replace(".exe", "") == currentProcess);
  129. if (!result)
  130. {
  131. Logger.LogInfo($"Skipping over plugin [{metadata.GUID}] due to process filter");
  132. continue;
  133. }
  134. }
  135. selectedPluginTypes.Add(pluginType, metadata);
  136. }
  137. Logger.LogInfo($"{selectedPluginTypes.Count} / {globalPluginTypes.Count} plugins to load");
  138. var dependencyDict = new Dictionary<string, IEnumerable<string>>();
  139. var pluginsByGUID = new Dictionary<string, Type>();
  140. foreach (var kv in selectedPluginTypes)
  141. {
  142. var dependencies = MetadataHelper.GetDependencies(kv.Key, selectedPluginTypes.Keys);
  143. dependencyDict[kv.Value.GUID] = dependencies.Select(d => d.DependencyGUID);
  144. pluginsByGUID[kv.Value.GUID] = kv.Key;
  145. }
  146. var emptyDependencies = new string[0];
  147. // Sort plugins by their dependencies.
  148. // Give missing dependencies no dependencies of its own, which will cause missing plugins to be first in the resulting list.
  149. var sortedPlugins = Utility.TopologicalSort(dependencyDict.Keys, x => dependencyDict.TryGetValue(x, out var deps) ? deps : emptyDependencies).ToList();
  150. var invalidPlugins = new HashSet<string>();
  151. var processedPlugins = new HashSet<string>();
  152. foreach (var pluginGUID in sortedPlugins)
  153. {
  154. // If the plugin is missing, don't process it
  155. if (!pluginsByGUID.TryGetValue(pluginGUID, out var pluginType))
  156. continue;
  157. var metadata = MetadataHelper.GetMetadata(pluginType);
  158. var dependencies = MetadataHelper.GetDependencies(pluginType, selectedPluginTypes.Keys);
  159. var dependsOnInvalidPlugin = false;
  160. var missingDependencies = new List<string>();
  161. foreach (var dependency in dependencies)
  162. {
  163. // If the depenency wasn't already processed, it's missing altogether
  164. if (!processedPlugins.Contains(dependency.DependencyGUID))
  165. {
  166. // If the dependency is hard, collect it into a list to show
  167. if ((dependency.Flags & BepInDependency.DependencyFlags.HardDependency) != 0)
  168. missingDependencies.Add(dependency.DependencyGUID);
  169. continue;
  170. }
  171. // If the dependency is invalid (e.g. has missing depedencies), report that to the user
  172. if (invalidPlugins.Contains(dependency.DependencyGUID))
  173. {
  174. dependsOnInvalidPlugin = true;
  175. break;
  176. }
  177. }
  178. processedPlugins.Add(pluginGUID);
  179. if (dependsOnInvalidPlugin)
  180. {
  181. Logger.LogWarning($"Skipping [{metadata.Name}] because it has a dependency that was not loaded. See above errors for details.");
  182. continue;
  183. }
  184. if (missingDependencies.Count != 0)
  185. {
  186. Logger.LogError($@"Missing the following dependencies for [{metadata.Name}]: {"\r\n"}{
  187. string.Join("\r\n", missingDependencies.Select(s => $"- {s}").ToArray())
  188. }{"\r\n"}Loading will be skipped; expect further errors and unstabilities.");
  189. invalidPlugins.Add(pluginGUID);
  190. continue;
  191. }
  192. try
  193. {
  194. Logger.LogInfo($"Loading [{metadata.Name} {metadata.Version}]");
  195. Plugins.Add((BaseUnityPlugin)ManagerObject.AddComponent(pluginType));
  196. }
  197. catch (Exception ex)
  198. {
  199. invalidPlugins.Add(pluginGUID);
  200. Logger.LogError($"Error loading [{metadata.Name}] : {ex.Message}");
  201. Logger.LogDebug(ex);
  202. }
  203. }
  204. }
  205. catch (Exception ex)
  206. {
  207. ConsoleWindow.Attach();
  208. Console.WriteLine("Error occurred starting the game");
  209. Console.WriteLine(ex.ToString());
  210. }
  211. Logger.LogMessage("Chainloader startup complete");
  212. _loaded = true;
  213. }
  214. #region Config
  215. private static readonly ConfigWrapper<string> ConfigPluginsDirectory = ConfigFile.CoreConfig.Wrap(
  216. "Paths",
  217. "PluginsDirectory",
  218. "The relative directory to the BepInEx folder where plugins are loaded.",
  219. "plugins");
  220. private static readonly ConfigWrapper<bool> ConfigUnityLogging = ConfigFile.CoreConfig.Wrap(
  221. "Logging",
  222. "UnityLogListening",
  223. "Enables showing unity log messages in the BepInEx logging system.",
  224. true);
  225. #endregion
  226. }
  227. }