Chainloader.cs 7.6 KB

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