Chainloader.cs 16 KB

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