Chainloader.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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.RegularExpressions;
  10. using Mono.Cecil;
  11. using UnityEngine;
  12. using Logger = BepInEx.Logging.Logger;
  13. namespace BepInEx.Bootstrap
  14. {
  15. /// <summary>
  16. /// The manager and loader for all plugins, and the entry point for BepInEx plugin system.
  17. /// </summary>
  18. public static class Chainloader
  19. {
  20. /// <summary>
  21. /// The loaded and initialized list of plugins.
  22. /// </summary>
  23. public static Dictionary<string, PluginInfo> PluginInfos { get; } = new Dictionary<string, PluginInfo>();
  24. private static readonly List<BaseUnityPlugin> _plugins = new List<BaseUnityPlugin>();
  25. [Obsolete("Use PluginInfos instead")]
  26. public static List<BaseUnityPlugin> Plugins
  27. {
  28. get
  29. {
  30. lock (_plugins)
  31. {
  32. _plugins.RemoveAll(x => x == null);
  33. return _plugins.ToList();
  34. }
  35. }
  36. }
  37. public static List<string> DependencyErrors { get; } = new List<string>();
  38. /// <summary>
  39. /// The GameObject that all plugins are attached to as components.
  40. /// </summary>
  41. public static GameObject ManagerObject { get; private set; }
  42. private static bool _loaded = false;
  43. private static bool _initialized = false;
  44. /// <summary>
  45. /// Initializes BepInEx to be able to start the chainloader.
  46. /// </summary>
  47. public static void Initialize(string gameExePath, bool startConsole = true, ICollection<LogEventArgs> preloaderLogEvents = null)
  48. {
  49. if (_initialized)
  50. return;
  51. ThreadingHelper.Initialize();
  52. // Set vitals
  53. if (gameExePath != null)
  54. {
  55. // Checking for null allows a more advanced initialization workflow, where the Paths class has been initialized before calling Chainloader.Initialize
  56. // This is used by Preloader to use environment variables, for example
  57. Paths.SetExecutablePath(gameExePath);
  58. }
  59. // Start logging
  60. if (ConsoleManager.ConfigConsoleEnabled.Value && startConsole)
  61. {
  62. ConsoleManager.CreateConsole();
  63. Logger.Listeners.Add(new ConsoleLogListener());
  64. }
  65. // Fix for standard output getting overwritten by UnityLogger
  66. if (ConsoleManager.ConsoleActive)
  67. {
  68. ConsoleManager.SetConsoleStreams();
  69. ConsoleManager.SetConsoleEncoding();
  70. }
  71. Logger.Listeners.Add(new UnityLogListener());
  72. if (ConfigDiskLogging.Value)
  73. Logger.Listeners.Add(new DiskLogListener("LogOutput.log", ConfigDiskConsoleDisplayedLevel.Value, ConfigDiskAppend.Value, ConfigDiskWriteUnityLog.Value));
  74. if (!TraceLogSource.IsListening)
  75. Logger.Sources.Add(TraceLogSource.CreateSource());
  76. if (ConfigUnityLogging.Value)
  77. Logger.Sources.Add(new UnityLogSource());
  78. // Temporarily disable the console log listener as we replay the preloader logs
  79. var logListener = Logger.Listeners.FirstOrDefault(logger => logger is ConsoleLogListener);
  80. if (logListener != null)
  81. Logger.Listeners.Remove(logListener);
  82. // Write preloader log events if there are any, including the original log source name
  83. if (preloaderLogEvents != null)
  84. {
  85. var preloaderLogSource = Logger.CreateLogSource("Preloader");
  86. foreach (var preloaderLogEvent in preloaderLogEvents)
  87. preloaderLogSource.Log(preloaderLogEvent.Level, $"[{preloaderLogEvent.Source.SourceName,10}] {preloaderLogEvent.Data}");
  88. Logger.Sources.Remove(preloaderLogSource);
  89. }
  90. if (logListener != null)
  91. Logger.Listeners.Add(logListener);
  92. Logger.LogMessage("Chainloader ready");
  93. _initialized = true;
  94. }
  95. private static Regex allowedGuidRegex { get; } = new Regex(@"^[a-zA-Z0-9\._\-]+$");
  96. public static PluginInfo ToPluginInfo(TypeDefinition type)
  97. {
  98. if (type.IsInterface || type.IsAbstract)
  99. return null;
  100. try
  101. {
  102. if (!type.IsSubtypeOf(typeof(BaseUnityPlugin)))
  103. return null;
  104. }
  105. catch (AssemblyResolutionException)
  106. {
  107. // Can happen if this type inherits a type from an assembly that can't be found. Safe to assume it's not a plugin.
  108. return null;
  109. }
  110. var metadata = BepInPlugin.FromCecilType(type);
  111. // Perform checks that will prevent the plugin from being loaded in ALL cases
  112. if (metadata == null)
  113. {
  114. Logger.LogWarning($"Skipping over type [{type.FullName}] as no metadata attribute is specified");
  115. return null;
  116. }
  117. if (string.IsNullOrEmpty(metadata.GUID) || !allowedGuidRegex.IsMatch(metadata.GUID))
  118. {
  119. Logger.LogWarning($"Skipping type [{type.FullName}] because its GUID [{metadata.GUID}] is of an illegal format.");
  120. return null;
  121. }
  122. if (metadata.Version == null)
  123. {
  124. Logger.LogWarning($"Skipping type [{type.FullName}] because its version is invalid.");
  125. return null;
  126. }
  127. if (metadata.Name == null)
  128. {
  129. Logger.LogWarning($"Skipping type [{type.FullName}] because its name is null.");
  130. return null;
  131. }
  132. var filters = BepInProcess.FromCecilType(type);
  133. var dependencies = BepInDependency.FromCecilType(type);
  134. var incompatibilities = BepInIncompatibility.FromCecilType(type);
  135. var bepinVersion = type.Module.AssemblyReferences.FirstOrDefault(reference => reference.Name == "BepInEx")?.Version ?? new Version();
  136. return new PluginInfo
  137. {
  138. Metadata = metadata,
  139. Processes = filters,
  140. Dependencies = dependencies,
  141. Incompatibilities = incompatibilities,
  142. TypeName = type.FullName,
  143. TargettedBepInExVersion = bepinVersion
  144. };
  145. }
  146. private static readonly string CurrentAssemblyName = Assembly.GetExecutingAssembly().GetName().Name;
  147. private static readonly Version CurrentAssemblyVersion = Assembly.GetExecutingAssembly().GetName().Version;
  148. private static bool HasBepinPlugins(AssemblyDefinition ass)
  149. {
  150. if (ass.MainModule.AssemblyReferences.All(r => r.Name != CurrentAssemblyName))
  151. return false;
  152. if (ass.MainModule.GetTypeReferences().All(r => r.FullName != typeof(BaseUnityPlugin).FullName))
  153. return false;
  154. return true;
  155. }
  156. private static bool PluginTargetsWrongBepin(PluginInfo pluginInfo)
  157. {
  158. var pluginTarget = pluginInfo.TargettedBepInExVersion;
  159. // X.X.X.x - compare normally. x.x.x.X - nightly build number, ignore
  160. if (pluginTarget.Major != CurrentAssemblyVersion.Major) return true;
  161. if (pluginTarget.Minor > CurrentAssemblyVersion.Minor) return true;
  162. if (pluginTarget.Minor < CurrentAssemblyVersion.Minor) return false;
  163. return pluginTarget.Build > CurrentAssemblyVersion.Build;
  164. }
  165. /// <summary>
  166. /// The entrypoint for the BepInEx plugin system.
  167. /// </summary>
  168. public static void Start()
  169. {
  170. if (_loaded)
  171. return;
  172. if (!_initialized)
  173. throw new InvalidOperationException("BepInEx has not been initialized. Please call Chainloader.Initialize prior to starting the chainloader instance.");
  174. if (!Directory.Exists(Paths.PluginPath))
  175. Directory.CreateDirectory(Paths.PluginPath);
  176. if (!Directory.Exists(Paths.PatcherPluginPath))
  177. Directory.CreateDirectory(Paths.PatcherPluginPath);
  178. try
  179. {
  180. var productNameProp = typeof(Application).GetProperty("productName", BindingFlags.Public | BindingFlags.Static);
  181. if (ConsoleManager.ConsoleActive)
  182. ConsoleManager.SetConsoleTitle($"{CurrentAssemblyName} {CurrentAssemblyVersion} - {productNameProp?.GetValue(null, null) ?? Process.GetCurrentProcess().ProcessName}");
  183. Logger.LogMessage("Chainloader started");
  184. ManagerObject = new GameObject("BepInEx_Manager");
  185. UnityEngine.Object.DontDestroyOnLoad(ManagerObject);
  186. var pluginsToLoad = TypeLoader.FindPluginTypes(Paths.PluginPath, ToPluginInfo, HasBepinPlugins, "chainloader");
  187. foreach (var keyValuePair in pluginsToLoad)
  188. foreach (var pluginInfo in keyValuePair.Value)
  189. pluginInfo.Location = keyValuePair.Key;
  190. var pluginInfos = pluginsToLoad.SelectMany(p => p.Value).ToList();
  191. var loadedAssemblies = new Dictionary<string, Assembly>();
  192. Logger.LogInfo($"{pluginInfos.Count} plugins to load");
  193. // We use a sorted dictionary to ensure consistent load order
  194. var dependencyDict = new SortedDictionary<string, IEnumerable<string>>(StringComparer.InvariantCultureIgnoreCase);
  195. var pluginsByGUID = new Dictionary<string, PluginInfo>();
  196. foreach (var pluginInfoGroup in pluginInfos.GroupBy(info => info.Metadata.GUID))
  197. {
  198. var alreadyLoaded = false;
  199. foreach (var pluginInfo in pluginInfoGroup.OrderByDescending(x => x.Metadata.Version))
  200. {
  201. if (alreadyLoaded)
  202. {
  203. Logger.LogWarning($"Skipping because a newer version exists [{pluginInfo.Metadata.Name} {pluginInfo.Metadata.Version}]");
  204. continue;
  205. }
  206. alreadyLoaded = true;
  207. // Perform checks that will prevent loading plugins in this run
  208. var filters = pluginInfo.Processes.ToList();
  209. bool invalidProcessName = filters.Count != 0 && filters.All(x => !string.Equals(x.ProcessName.Replace(".exe", ""), Paths.ProcessName, StringComparison.InvariantCultureIgnoreCase));
  210. if (invalidProcessName)
  211. {
  212. Logger.LogWarning($"Skipping because of process filters [{pluginInfo.Metadata.Name} {pluginInfo.Metadata.Version}]");
  213. continue;
  214. }
  215. dependencyDict[pluginInfo.Metadata.GUID] = pluginInfo.Dependencies.Select(d => d.DependencyGUID);
  216. pluginsByGUID[pluginInfo.Metadata.GUID] = pluginInfo;
  217. }
  218. }
  219. foreach (var pluginInfo in pluginsByGUID.Values.ToList())
  220. {
  221. if (pluginInfo.Incompatibilities.Any(incompatibility => pluginsByGUID.ContainsKey(incompatibility.IncompatibilityGUID)))
  222. {
  223. pluginsByGUID.Remove(pluginInfo.Metadata.GUID);
  224. dependencyDict.Remove(pluginInfo.Metadata.GUID);
  225. var incompatiblePlugins = pluginInfo.Incompatibilities.Select(x => x.IncompatibilityGUID).Where(x => pluginsByGUID.ContainsKey(x)).ToArray();
  226. string message = $@"Could not load [{pluginInfo.Metadata.Name}] because it is incompatible with: {string.Join(", ", incompatiblePlugins)}";
  227. DependencyErrors.Add(message);
  228. Logger.LogError(message);
  229. }
  230. else if (PluginTargetsWrongBepin(pluginInfo))
  231. {
  232. string message = $@"Plugin [{pluginInfo.Metadata.Name}] targets a wrong version of BepInEx ({pluginInfo.TargettedBepInExVersion}) and might not work until you update";
  233. DependencyErrors.Add(message);
  234. Logger.LogWarning(message);
  235. }
  236. }
  237. var emptyDependencies = new string[0];
  238. // Sort plugins by their dependencies.
  239. // Give missing dependencies no dependencies of its own, which will cause missing plugins to be first in the resulting list.
  240. var sortedPlugins = Utility.TopologicalSort(dependencyDict.Keys, x => dependencyDict.TryGetValue(x, out var deps) ? deps : emptyDependencies).ToList();
  241. var invalidPlugins = new HashSet<string>();
  242. var processedPlugins = new Dictionary<string, Version>();
  243. foreach (var pluginGUID in sortedPlugins)
  244. {
  245. // If the plugin is missing, don't process it
  246. if (!pluginsByGUID.TryGetValue(pluginGUID, out var pluginInfo))
  247. continue;
  248. var dependsOnInvalidPlugin = false;
  249. var missingDependencies = new List<BepInDependency>();
  250. foreach (var dependency in pluginInfo.Dependencies)
  251. {
  252. // If the depenency wasn't already processed, it's missing altogether
  253. bool depenencyExists = processedPlugins.TryGetValue(dependency.DependencyGUID, out var pluginVersion);
  254. if (!depenencyExists || pluginVersion < dependency.MinimumVersion)
  255. {
  256. // If the dependency is hard, collect it into a list to show
  257. if ((dependency.Flags & BepInDependency.DependencyFlags.HardDependency) != 0)
  258. missingDependencies.Add(dependency);
  259. continue;
  260. }
  261. // If the dependency is invalid (e.g. has missing depedencies), report that to the user
  262. if (invalidPlugins.Contains(dependency.DependencyGUID))
  263. {
  264. dependsOnInvalidPlugin = true;
  265. break;
  266. }
  267. }
  268. processedPlugins.Add(pluginGUID, pluginInfo.Metadata.Version);
  269. if (dependsOnInvalidPlugin)
  270. {
  271. string message = $"Skipping [{pluginInfo.Metadata.Name}] because it has a dependency that was not loaded. See previous errors for details.";
  272. DependencyErrors.Add(message);
  273. Logger.LogWarning(message);
  274. continue;
  275. }
  276. if (missingDependencies.Count != 0)
  277. {
  278. bool IsEmptyVersion(Version v) => v.Major == 0 && v.Minor == 0 && v.Build <= 0 && v.Revision <= 0;
  279. string message = $@"Could not load [{pluginInfo.Metadata.Name}] because it has missing dependencies: {
  280. string.Join(", ", missingDependencies.Select(s => IsEmptyVersion(s.MinimumVersion) ? s.DependencyGUID : $"{s.DependencyGUID} (v{s.MinimumVersion} or newer)").ToArray())
  281. }";
  282. DependencyErrors.Add(message);
  283. Logger.LogError(message);
  284. invalidPlugins.Add(pluginGUID);
  285. continue;
  286. }
  287. try
  288. {
  289. Logger.LogInfo($"Loading [{pluginInfo.Metadata.Name} {pluginInfo.Metadata.Version}]");
  290. if (!loadedAssemblies.TryGetValue(pluginInfo.Location, out var ass))
  291. loadedAssemblies[pluginInfo.Location] = ass = Assembly.LoadFile(pluginInfo.Location);
  292. PluginInfos[pluginGUID] = pluginInfo;
  293. pluginInfo.Instance = (BaseUnityPlugin)ManagerObject.AddComponent(ass.GetType(pluginInfo.TypeName));
  294. _plugins.Add(pluginInfo.Instance);
  295. }
  296. catch (Exception ex)
  297. {
  298. invalidPlugins.Add(pluginGUID);
  299. PluginInfos.Remove(pluginGUID);
  300. Logger.LogError($"Error loading [{pluginInfo.Metadata.Name}] : {ex.Message}");
  301. if (ex is ReflectionTypeLoadException re)
  302. Logger.LogDebug(TypeLoader.TypeLoadExceptionToString(re));
  303. else
  304. Logger.LogDebug(ex);
  305. }
  306. }
  307. }
  308. catch (Exception ex)
  309. {
  310. try
  311. {
  312. ConsoleManager.CreateConsole();
  313. }
  314. catch { }
  315. Logger.LogFatal("Error occurred starting the game");
  316. Logger.LogFatal(ex.ToString());
  317. }
  318. Logger.LogMessage("Chainloader startup complete");
  319. _loaded = true;
  320. }
  321. #region Config
  322. private static readonly ConfigEntry<bool> ConfigUnityLogging = ConfigFile.CoreConfig.Bind(
  323. "Logging", "UnityLogListening",
  324. true,
  325. "Enables showing unity log messages in the BepInEx logging system.");
  326. private static readonly ConfigEntry<bool> ConfigDiskWriteUnityLog = ConfigFile.CoreConfig.Bind(
  327. "Logging.Disk", "WriteUnityLog",
  328. false,
  329. "Include unity log messages in log file output.");
  330. private static readonly ConfigEntry<bool> ConfigDiskAppend = ConfigFile.CoreConfig.Bind(
  331. "Logging.Disk", "AppendLog",
  332. false,
  333. "Appends to the log file instead of overwriting, on game startup.");
  334. private static readonly ConfigEntry<bool> ConfigDiskLogging = ConfigFile.CoreConfig.Bind(
  335. "Logging.Disk", "Enabled",
  336. true,
  337. "Enables writing log messages to disk.");
  338. private static readonly ConfigEntry<LogLevel> ConfigDiskConsoleDisplayedLevel = ConfigFile.CoreConfig.Bind(
  339. "Logging.Disk", "DisplayedLogLevel",
  340. LogLevel.Fatal | LogLevel.Error | LogLevel.Message | LogLevel.Info,
  341. "Only displays the specified log levels in the disk log output.");
  342. #endregion
  343. }
  344. }