Chainloader.cs 8.6 KB

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