Chainloader.cs 9.9 KB

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