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