Chainloader.cs 15 KB

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