Chainloader.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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 (ConsoleWindow.ConfigConsoleEnabled.Value && startConsole)
  44. {
  45. ConsoleWindow.Attach();
  46. Logger.Listeners.Add(new ConsoleLogListener());
  47. }
  48. //Fix for standard output getting overwritten by UnityLogger
  49. if (ConsoleWindow.StandardOut != null)
  50. {
  51. Console.SetOut(ConsoleWindow.StandardOut);
  52. var encoding = ConsoleWindow.ConfigConsoleShiftJis.Value ? 932 : (uint)Encoding.UTF8.CodePage;
  53. ConsoleEncoding.ConsoleCodePage = encoding;
  54. Console.OutputEncoding = ConsoleEncoding.GetEncoding(encoding);
  55. }
  56. Logger.Listeners.Add(new UnityLogListener());
  57. Logger.Listeners.Add(new DiskLogListener());
  58. if (!TraceLogSource.IsListening)
  59. Logger.Sources.Add(TraceLogSource.CreateSource());
  60. if (ConfigUnityLogging.Value)
  61. Logger.Sources.Add(new UnityLogSource());
  62. Logger.LogMessage("Chainloader ready");
  63. _initialized = true;
  64. }
  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 = $"BepInEx {Assembly.GetExecutingAssembly().GetName().Version} - {productNameProp.GetValue(null, null)}";
  83. Logger.LogMessage("Chainloader started");
  84. ManagerObject = new GameObject("BepInEx_Manager");
  85. UnityEngine.Object.DontDestroyOnLoad(ManagerObject);
  86. var pluginsToLoad = TypeLoader.FindPluginTypes(Paths.PluginPath);
  87. var pluginInfos = pluginsToLoad.SelectMany(p => p.Value).ToList();
  88. var loadedAssemblies = new Dictionary<AssemblyDefinition, Assembly>();
  89. Logger.LogInfo($"{pluginInfos.Count} / {pluginInfos.Count} plugins to load");
  90. var dependencyDict = new Dictionary<string, IEnumerable<string>>();
  91. var pluginsByGUID = new Dictionary<string, PluginInfo>();
  92. foreach (var pluginInfo in pluginInfos)
  93. {
  94. if (pluginInfo.Metadata.GUID == null)
  95. {
  96. Logger.LogWarning($"Skipping [{pluginInfo.Metadata.Name}] because it does not have a valid GUID.");
  97. continue;
  98. }
  99. if (dependencyDict.ContainsKey(pluginInfo.Metadata.GUID))
  100. {
  101. Logger.LogWarning($"Skipping [{pluginInfo.Metadata.Name}] because its GUID ({pluginInfo.Metadata.GUID}) is already used by another plugin.");
  102. continue;
  103. }
  104. dependencyDict[pluginInfo.Metadata.GUID] = pluginInfo.Dependencies.Select(d => d.DependencyGUID);
  105. pluginsByGUID[pluginInfo.Metadata.GUID] = pluginInfo;
  106. }
  107. var emptyDependencies = new string[0];
  108. // Sort plugins by their dependencies.
  109. // Give missing dependencies no dependencies of its own, which will cause missing plugins to be first in the resulting list.
  110. var sortedPlugins = Utility.TopologicalSort(dependencyDict.Keys, x => dependencyDict.TryGetValue(x, out var deps) ? deps : emptyDependencies).ToList();
  111. var invalidPlugins = new HashSet<string>();
  112. var processedPlugins = new HashSet<string>();
  113. foreach (var pluginGUID in sortedPlugins)
  114. {
  115. // If the plugin is missing, don't process it
  116. if (!pluginsByGUID.TryGetValue(pluginGUID, out var pluginInfo))
  117. continue;
  118. var dependsOnInvalidPlugin = false;
  119. var missingDependencies = new List<string>();
  120. foreach (var dependency in pluginInfo.Dependencies)
  121. {
  122. // If the depenency wasn't already processed, it's missing altogether
  123. if (!processedPlugins.Contains(dependency.DependencyGUID))
  124. {
  125. // If the dependency is hard, collect it into a list to show
  126. if ((dependency.Flags & BepInDependency.DependencyFlags.HardDependency) != 0)
  127. missingDependencies.Add(dependency.DependencyGUID);
  128. continue;
  129. }
  130. // If the dependency is invalid (e.g. has missing depedencies), report that to the user
  131. if (invalidPlugins.Contains(dependency.DependencyGUID))
  132. {
  133. dependsOnInvalidPlugin = true;
  134. break;
  135. }
  136. }
  137. processedPlugins.Add(pluginGUID);
  138. if (dependsOnInvalidPlugin)
  139. {
  140. Logger.LogWarning($"Skipping [{pluginInfo.Metadata.Name}] because it has a dependency that was not loaded. See above errors for details.");
  141. continue;
  142. }
  143. if (missingDependencies.Count != 0)
  144. {
  145. Logger.LogError($@"Missing the following dependencies for [{pluginInfo.Metadata.Name}]: {"\r\n"}{
  146. string.Join("\r\n", missingDependencies.Select(s => $"- {s}").ToArray())
  147. }{"\r\n"}Loading will be skipped; expect further errors and unstabilities.");
  148. invalidPlugins.Add(pluginGUID);
  149. continue;
  150. }
  151. try
  152. {
  153. Logger.LogInfo($"Loading [{pluginInfo.Metadata.Name} {pluginInfo.Metadata.Version}]");
  154. if (!loadedAssemblies.TryGetValue(pluginInfo.CecilType.Module.Assembly, out var ass))
  155. loadedAssemblies[pluginInfo.CecilType.Module.Assembly] = ass = Assembly.LoadFile(pluginInfo.Location);
  156. Plugins[pluginGUID] = pluginInfo;
  157. pluginInfo.Instance = (BaseUnityPlugin)ManagerObject.AddComponent(ass.GetType(pluginInfo.CecilType.FullName));
  158. pluginInfo.CecilType = null;
  159. }
  160. catch (Exception ex)
  161. {
  162. invalidPlugins.Add(pluginGUID);
  163. Plugins.Remove(pluginGUID);
  164. Logger.LogError($"Error loading [{pluginInfo.Metadata.Name}] : {ex.Message}");
  165. Logger.LogDebug(ex);
  166. }
  167. }
  168. foreach (var selectedTypesInfo in pluginsToLoad)
  169. {
  170. selectedTypesInfo.Key.Dispose();
  171. }
  172. }
  173. catch (Exception ex)
  174. {
  175. ConsoleWindow.Attach();
  176. Console.WriteLine("Error occurred starting the game");
  177. Console.WriteLine(ex.ToString());
  178. }
  179. Logger.LogMessage("Chainloader startup complete");
  180. _loaded = true;
  181. }
  182. #region Config
  183. private static readonly ConfigWrapper<string> ConfigPluginsDirectory = ConfigFile.CoreConfig.Wrap("Paths", "PluginsDirectory", "The relative directory to the BepInEx folder where plugins are loaded.", "plugins");
  184. private static readonly ConfigWrapper<bool> ConfigUnityLogging = ConfigFile.CoreConfig.Wrap("Logging", "UnityLogListening", "Enables showing unity log messages in the BepInEx logging system.", true);
  185. #endregion
  186. }
  187. }