Chainloader.cs 8.8 KB

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