Chainloader.cs 15 KB

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