Chainloader.cs 8.8 KB

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