Chainloader.cs 9.0 KB

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