Chainloader.cs 8.1 KB

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