BaseChainloader.cs 12 KB

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