Chainloader.cs 16 KB

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