Chainloader.cs 15 KB

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