Chainloader.cs 8.0 KB

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