Chainloader.cs 15 KB

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