BaseChainloader.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Text;
  7. using System.Text.RegularExpressions;
  8. using BepInEx.Configuration;
  9. using BepInEx.Core;
  10. using BepInEx.Logging;
  11. using Mono.Cecil;
  12. namespace BepInEx.Bootstrap
  13. {
  14. public abstract class BaseChainloader<TPlugin>
  15. {
  16. #region Contract
  17. protected virtual string ConsoleTitle => $"BepInEx {Paths.BepInExVersion} - {Paths.ProcessName}";
  18. private bool _initialized = false;
  19. /// <summary>
  20. /// List of all <see cref="PluginInfo"/> instances loaded via the chainloader.
  21. /// </summary>
  22. public Dictionary<string, PluginInfo> Plugins { get; } = new Dictionary<string, PluginInfo>();
  23. /// <summary>
  24. /// Collection of error chainloader messages that occured during plugin loading.
  25. /// Contains information about what certain plugins were not loaded.
  26. /// </summary>
  27. public List<string> DependencyErrors { get; } = new List<string>();
  28. public virtual void Initialize(string gameExePath = null)
  29. {
  30. if (_initialized)
  31. throw new InvalidOperationException("Chainloader cannot be initialized multiple times");
  32. // Set vitals
  33. if (gameExePath != null)
  34. {
  35. // Checking for null allows a more advanced initialization workflow, where the Paths class has been initialized before calling Chainloader.Initialize
  36. // This is used by Preloader to use environment variables, for example
  37. Paths.SetExecutablePath(gameExePath);
  38. }
  39. InitializeLoggers();
  40. if (!Directory.Exists(Paths.PluginPath))
  41. Directory.CreateDirectory(Paths.PluginPath);
  42. if (!Directory.Exists(Paths.PatcherPluginPath))
  43. Directory.CreateDirectory(Paths.PatcherPluginPath);
  44. _initialized = true;
  45. Logger.LogMessage("Chainloader initialized");
  46. }
  47. protected virtual void InitializeLoggers()
  48. {
  49. if (ConsoleManager.ConfigConsoleEnabled.Value && !ConsoleManager.ConsoleActive)
  50. ConsoleManager.CreateConsole();
  51. if (ConsoleManager.ConsoleActive)
  52. {
  53. if (!Logger.Listeners.Any(x => x is ConsoleLogListener))
  54. Logger.Listeners.Add(new ConsoleLogListener());
  55. ConsoleManager.SetConsoleTitle(ConsoleTitle);
  56. }
  57. if (ConfigDiskLogging.Value)
  58. Logger.Listeners.Add(new DiskLogListener("LogOutput.log", ConfigDiskLoggingDisplayedLevel.Value, ConfigDiskAppend.Value, ConfigDiskLoggingInstantFlushing.Value));
  59. if (!TraceLogSource.IsListening)
  60. Logger.Sources.Add(TraceLogSource.CreateSource());
  61. if (!Logger.Sources.Any(x => x is HarmonyLogSource))
  62. Logger.Sources.Add(new HarmonyLogSource());
  63. }
  64. protected virtual IList<PluginInfo> DiscoverPlugins()
  65. {
  66. var pluginsToLoad = TypeLoader.FindPluginTypes(Paths.PluginPath, ToPluginInfo, HasBepinPlugins, "chainloader");
  67. return pluginsToLoad.SelectMany(p => p.Value).ToList();
  68. }
  69. protected virtual IList<PluginInfo> ModifyLoadOrder(IList<PluginInfo> plugins)
  70. {
  71. // We use a sorted dictionary to ensure consistent load order
  72. var dependencyDict = new SortedDictionary<string, IEnumerable<string>>(StringComparer.InvariantCultureIgnoreCase);
  73. var pluginsByGuid = new Dictionary<string, PluginInfo>();
  74. foreach (var pluginInfoGroup in plugins.GroupBy(info => info.Metadata.GUID))
  75. {
  76. PluginInfo loadedVersion = null;
  77. foreach (var pluginInfo in pluginInfoGroup.OrderByDescending(x => x.Metadata.Version))
  78. {
  79. if (loadedVersion != null)
  80. {
  81. Logger.LogWarning($"Skipping [{pluginInfo}] because a newer version exists ({loadedVersion})");
  82. continue;
  83. }
  84. // Perform checks that will prevent loading plugins in this run
  85. var filters = pluginInfo.Processes.ToList();
  86. bool invalidProcessName = filters.Count != 0 && filters.All(x => !string.Equals(x.ProcessName.Replace(".exe", ""), Paths.ProcessName, StringComparison.InvariantCultureIgnoreCase));
  87. if (invalidProcessName)
  88. {
  89. Logger.LogWarning($"Skipping [{pluginInfo}] because of process filters ({string.Join(", ", pluginInfo.Processes.Select(p => p.ProcessName).ToArray())})");
  90. continue;
  91. }
  92. loadedVersion = pluginInfo;
  93. dependencyDict[pluginInfo.Metadata.GUID] = pluginInfo.Dependencies.Select(d => d.DependencyGUID);
  94. pluginsByGuid[pluginInfo.Metadata.GUID] = pluginInfo;
  95. }
  96. }
  97. foreach (var pluginInfo in pluginsByGuid.Values.ToList())
  98. {
  99. if (pluginInfo.Incompatibilities.Any(incompatibility => pluginsByGuid.ContainsKey(incompatibility.IncompatibilityGUID)))
  100. {
  101. pluginsByGuid.Remove(pluginInfo.Metadata.GUID);
  102. dependencyDict.Remove(pluginInfo.Metadata.GUID);
  103. var incompatiblePlugins = pluginInfo.Incompatibilities.Select(x => x.IncompatibilityGUID).Where(x => pluginsByGuid.ContainsKey(x)).ToArray();
  104. string message = $@"Could not load [{pluginInfo}] because it is incompatible with: {string.Join(", ", incompatiblePlugins)}";
  105. DependencyErrors.Add(message);
  106. Logger.LogError(message);
  107. }
  108. else if (PluginTargetsWrongBepin(pluginInfo))
  109. {
  110. string message = $@"Plugin [{pluginInfo}] targets a wrong version of BepInEx ({pluginInfo.TargettedBepInExVersion}) and might not work until you update";
  111. DependencyErrors.Add(message);
  112. Logger.LogWarning(message);
  113. }
  114. }
  115. var emptyDependencies = new string[0];
  116. // Sort plugins by their dependencies.
  117. // Give missing dependencies no dependencies of its own, which will cause missing plugins to be first in the resulting list.
  118. var sortedPlugins = Utility.TopologicalSort(dependencyDict.Keys, x => dependencyDict.TryGetValue(x, out var deps) ? deps : emptyDependencies).ToList();
  119. return sortedPlugins.Where(pluginsByGuid.ContainsKey).Select(x => pluginsByGuid[x]).ToList();
  120. }
  121. public virtual void Execute()
  122. {
  123. try
  124. {
  125. var plugins = DiscoverPlugins();
  126. Logger.LogInfo($"{plugins.Count} plugin{(plugins.Count == 1 ? "" : "s")} to load");
  127. var sortedPlugins = ModifyLoadOrder(plugins);
  128. var invalidPlugins = new HashSet<string>();
  129. var processedPlugins = new Dictionary<string, SemVer.Version>();
  130. var loadedAssemblies = new Dictionary<string, Assembly>();
  131. foreach (var plugin in sortedPlugins)
  132. {
  133. var dependsOnInvalidPlugin = false;
  134. var missingDependencies = new List<BepInDependency>();
  135. foreach (var dependency in plugin.Dependencies)
  136. {
  137. bool IsHardDependency(BepInDependency dep)
  138. => (dep.Flags & BepInDependency.DependencyFlags.HardDependency) != 0;
  139. // If the dependency wasn't already processed, it's missing altogether
  140. bool dependencyExists = processedPlugins.TryGetValue(dependency.DependencyGUID, out var pluginVersion);
  141. if (!dependencyExists || (dependency.VersionRange != null && !dependency.VersionRange.IsSatisfied(pluginVersion)))
  142. {
  143. // If the dependency is hard, collect it into a list to show
  144. if (IsHardDependency(dependency))
  145. missingDependencies.Add(dependency);
  146. continue;
  147. }
  148. // If the dependency is a hard and is invalid (e.g. has missing dependencies), report that to the user
  149. if (invalidPlugins.Contains(dependency.DependencyGUID) && IsHardDependency(dependency))
  150. {
  151. dependsOnInvalidPlugin = true;
  152. break;
  153. }
  154. }
  155. processedPlugins.Add(plugin.Metadata.GUID, plugin.Metadata.Version);
  156. if (dependsOnInvalidPlugin)
  157. {
  158. string message = $"Skipping [{plugin}] because it has a dependency that was not loaded. See previous errors for details.";
  159. DependencyErrors.Add(message);
  160. Logger.LogWarning(message);
  161. continue;
  162. }
  163. if (missingDependencies.Count != 0)
  164. {
  165. string message = $@"Could not load [{plugin}] because it has missing dependencies: {
  166. string.Join(", ", missingDependencies.Select(s => s.VersionRange == null ? s.DependencyGUID : $"{s.DependencyGUID} ({s.VersionRange})").ToArray())
  167. }";
  168. DependencyErrors.Add(message);
  169. Logger.LogError(message);
  170. invalidPlugins.Add(plugin.Metadata.GUID);
  171. continue;
  172. }
  173. try
  174. {
  175. Logger.LogInfo($"Loading [{plugin}]");
  176. if (!loadedAssemblies.TryGetValue(plugin.Location, out var ass))
  177. loadedAssemblies[plugin.Location] = ass = Assembly.LoadFile(plugin.Location);
  178. Plugins[plugin.Metadata.GUID] = plugin;
  179. plugin.Instance = LoadPlugin(plugin, ass);
  180. //_plugins.Add((TPlugin)plugin.Instance);
  181. }
  182. catch (Exception ex)
  183. {
  184. invalidPlugins.Add(plugin.Metadata.GUID);
  185. Plugins.Remove(plugin.Metadata.GUID);
  186. Logger.LogError($"Error loading [{plugin}] : {ex.Message}");
  187. if (ex is ReflectionTypeLoadException re)
  188. Logger.LogDebug(TypeLoader.TypeLoadExceptionToString(re));
  189. else
  190. Logger.LogDebug(ex);
  191. }
  192. }
  193. }
  194. catch (Exception ex)
  195. {
  196. try
  197. {
  198. ConsoleManager.CreateConsole();
  199. }
  200. catch { }
  201. Logger.LogError("Error occurred starting the game");
  202. Logger.LogDebug(ex);
  203. }
  204. Logger.LogMessage("Chainloader startup complete");
  205. }
  206. public abstract TPlugin LoadPlugin(PluginInfo pluginInfo, Assembly pluginAssembly);
  207. #endregion
  208. private static Regex allowedGuidRegex { get; } = new Regex(@"^[a-zA-Z0-9\._\-]+$");
  209. /// <summary>
  210. /// Analyzes the given type definition and attempts to convert it to a valid <see cref="PluginInfo"/>
  211. /// </summary>
  212. /// <param name="type">Type definition to analyze.</param>
  213. /// <param name="assemblyLocation">The filepath of the assembly, to keep as metadata.</param>
  214. /// <returns>If the type represent a valid plugin, returns a <see cref="PluginInfo"/> instance. Otherwise, return null.</returns>
  215. public static PluginInfo ToPluginInfo(TypeDefinition type, string assemblyLocation)
  216. {
  217. if (type.IsInterface || type.IsAbstract)
  218. return null;
  219. try
  220. {
  221. if (!type.IsSubtypeOf(typeof(TPlugin)))
  222. return null;
  223. }
  224. catch (AssemblyResolutionException)
  225. {
  226. // Can happen if this type inherits a type from an assembly that can't be found. Safe to assume it's not a plugin.
  227. return null;
  228. }
  229. var metadata = BepInPlugin.FromCecilType(type);
  230. // Perform checks that will prevent the plugin from being loaded in ALL cases
  231. if (metadata == null)
  232. {
  233. Logger.LogWarning($"Skipping over type [{type.FullName}] as no metadata attribute is specified");
  234. return null;
  235. }
  236. if (string.IsNullOrEmpty(metadata.GUID) || !allowedGuidRegex.IsMatch(metadata.GUID))
  237. {
  238. Logger.LogWarning($"Skipping type [{type.FullName}] because its GUID [{metadata.GUID}] is of an illegal format.");
  239. return null;
  240. }
  241. if (metadata.Version == null)
  242. {
  243. Logger.LogWarning($"Skipping type [{type.FullName}] because its version is invalid.");
  244. return null;
  245. }
  246. if (metadata.Name == null)
  247. {
  248. Logger.LogWarning($"Skipping type [{type.FullName}] because its name is null.");
  249. return null;
  250. }
  251. var filters = BepInProcess.FromCecilType(type);
  252. var dependencies = BepInDependency.FromCecilType(type);
  253. var incompatibilities = BepInIncompatibility.FromCecilType(type);
  254. var bepinVersion = type.Module.AssemblyReferences.FirstOrDefault(reference => reference.Name == "BepInEx.Core")?.Version ?? new Version();
  255. return new PluginInfo
  256. {
  257. Metadata = metadata,
  258. Processes = filters,
  259. Dependencies = dependencies,
  260. Incompatibilities = incompatibilities,
  261. TypeName = type.FullName,
  262. TargettedBepInExVersion = bepinVersion,
  263. Location = assemblyLocation
  264. };
  265. }
  266. protected static readonly string CurrentAssemblyName = Assembly.GetExecutingAssembly().GetName().Name;
  267. protected static readonly Version CurrentAssemblyVersion = Assembly.GetExecutingAssembly().GetName().Version;
  268. protected static bool HasBepinPlugins(AssemblyDefinition ass)
  269. {
  270. if (ass.MainModule.AssemblyReferences.All(r => r.Name != CurrentAssemblyName))
  271. return false;
  272. if (ass.MainModule.GetTypeReferences().All(r => r.FullName != typeof(TPlugin).FullName))
  273. return false;
  274. return true;
  275. }
  276. protected static bool PluginTargetsWrongBepin(PluginInfo pluginInfo)
  277. {
  278. var pluginTarget = pluginInfo.TargettedBepInExVersion;
  279. // X.X.X.x - compare normally. x.x.x.X - nightly build number, ignore
  280. if (pluginTarget.Major != CurrentAssemblyVersion.Major) return true;
  281. if (pluginTarget.Minor > CurrentAssemblyVersion.Minor) return true;
  282. if (pluginTarget.Minor < CurrentAssemblyVersion.Minor) return false;
  283. return pluginTarget.Build > CurrentAssemblyVersion.Build;
  284. }
  285. #region Config
  286. private static readonly ConfigEntry<bool> ConfigDiskAppend = ConfigFile.CoreConfig.Bind(
  287. "Logging.Disk", "AppendLog",
  288. false,
  289. "Appends to the log file instead of overwriting, on game startup.");
  290. private static readonly ConfigEntry<bool> ConfigDiskLogging = ConfigFile.CoreConfig.Bind(
  291. "Logging.Disk", "Enabled",
  292. true,
  293. "Enables writing log messages to disk.");
  294. private static readonly ConfigEntry<LogLevel> ConfigDiskLoggingDisplayedLevel = ConfigFile.CoreConfig.Bind(
  295. "Logging.Disk", "LogLevels",
  296. LogLevel.Fatal | LogLevel.Error | LogLevel.Warning | LogLevel.Message | LogLevel.Info,
  297. "Only displays the specified log levels in the disk log output.");
  298. private static readonly ConfigEntry<bool> ConfigDiskLoggingInstantFlushing = ConfigFile.CoreConfig.Bind(
  299. "Logging.Disk", "InstantFlushing",
  300. false,
  301. new StringBuilder()
  302. .AppendLine("If true, instantly writes any received log entries to disk.")
  303. .AppendLine("This incurs a major performance hit if a lot of log messages are being written, however it is really useful for debugging crashes.")
  304. .ToString());
  305. #endregion
  306. }
  307. }