Chainloader.cs 15 KB

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