Chainloader.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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> PluginInfos { get; } = new Dictionary<string, PluginInfo>();
  26. public static List<BaseUnityPlugin> Plugins { get; } = new List<BaseUnityPlugin>();
  27. /// <summary>
  28. /// The GameObject that all plugins are attached to as components.
  29. /// </summary>
  30. public static GameObject ManagerObject { get; private set; }
  31. private static bool _loaded = false;
  32. private static bool _initialized = false;
  33. /// <summary>
  34. /// Initializes BepInEx to be able to start the chainloader.
  35. /// </summary>
  36. public static void Initialize(string containerExePath, bool startConsole = true)
  37. {
  38. if (_initialized)
  39. return;
  40. //Set vitals
  41. Paths.SetExecutablePath(containerExePath);
  42. Paths.SetPluginPath(ConfigPluginsDirectory.Value);
  43. //Start logging
  44. if (ConsoleWindow.ConfigConsoleEnabled.Value && startConsole)
  45. {
  46. ConsoleWindow.Attach();
  47. Logger.Listeners.Add(new ConsoleLogListener());
  48. }
  49. //Fix for standard output getting overwritten by UnityLogger
  50. if (ConsoleWindow.StandardOut != null)
  51. {
  52. Console.SetOut(ConsoleWindow.StandardOut);
  53. var encoding = ConsoleWindow.ConfigConsoleShiftJis.Value ? 932 : (uint)Encoding.UTF8.CodePage;
  54. ConsoleEncoding.ConsoleCodePage = encoding;
  55. Console.OutputEncoding = ConsoleEncoding.GetEncoding(encoding);
  56. }
  57. Logger.Listeners.Add(new UnityLogListener());
  58. Logger.Listeners.Add(new DiskLogListener());
  59. if (!TraceLogSource.IsListening)
  60. Logger.Sources.Add(TraceLogSource.CreateSource());
  61. if (ConfigUnityLogging.Value)
  62. Logger.Sources.Add(new UnityLogSource());
  63. Logger.LogMessage("Chainloader ready");
  64. _initialized = true;
  65. }
  66. private static PluginInfo ToPluginInfo(TypeDefinition type)
  67. {
  68. if (type.IsInterface || type.IsAbstract || !type.IsSubtypeOf(typeof(BaseUnityPlugin)))
  69. return null;
  70. var metadata = BepInPlugin.FromCecilType(type);
  71. if (metadata == null)
  72. {
  73. Logger.LogWarning($"Skipping over type [{type.Name}] as no metadata attribute is specified");
  74. return null;
  75. }
  76. //Perform a filter for currently running process
  77. var filters = BepInProcess.FromCecilType(type);
  78. bool invalidProcessName = filters.Any(x => !string.Equals(x.ProcessName.Replace(".exe", ""), Paths.ProcessName, StringComparison.InvariantCultureIgnoreCase));
  79. if (invalidProcessName)
  80. {
  81. Logger.LogWarning($"Skipping over plugin [{metadata.GUID}] due to process filter");
  82. return null;
  83. }
  84. var dependencies = BepInDependency.FromCecilType(type);
  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. PluginInfos[pluginGUID] = pluginInfo;
  186. pluginInfo.Instance = (BaseUnityPlugin)ManagerObject.AddComponent(ass.GetType(pluginInfo.CecilType.FullName));
  187. pluginInfo.CecilType = null;
  188. Plugins.Add(pluginInfo.Instance);
  189. }
  190. catch (Exception ex)
  191. {
  192. invalidPlugins.Add(pluginGUID);
  193. PluginInfos.Remove(pluginGUID);
  194. Logger.LogError($"Error loading [{pluginInfo.Metadata.Name}] : {ex.Message}");
  195. if (ex is ReflectionTypeLoadException re)
  196. Logger.LogDebug(TypeLoader.TypeLoadExceptionToString(re));
  197. else
  198. Logger.LogDebug(ex);
  199. }
  200. }
  201. foreach (var selectedTypesInfo in pluginsToLoad)
  202. {
  203. selectedTypesInfo.Key.Dispose();
  204. }
  205. }
  206. catch (Exception ex)
  207. {
  208. ConsoleWindow.Attach();
  209. Console.WriteLine("Error occurred starting the game");
  210. Console.WriteLine(ex.ToString());
  211. }
  212. Logger.LogMessage("Chainloader startup complete");
  213. _loaded = true;
  214. }
  215. #region Config
  216. private static readonly ConfigWrapper<string> ConfigPluginsDirectory = ConfigFile.CoreConfig.Wrap("Paths", "PluginsDirectory", "The relative directory to the BepInEx folder where plugins are loaded.", "plugins");
  217. private static readonly ConfigWrapper<bool> ConfigUnityLogging = ConfigFile.CoreConfig.Wrap("Logging", "UnityLogListening", "Enables showing unity log messages in the BepInEx logging system.", true);
  218. #endregion
  219. }
  220. }