Chainloader.cs 10 KB

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