BaseChainloader.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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. PluginInfo loadedVersion = null;
  67. foreach (var pluginInfo in pluginInfoGroup.OrderByDescending(x => x.Metadata.Version))
  68. {
  69. if (loadedVersion != null)
  70. {
  71. Logger.LogWarning($"Skipping [{pluginInfo}] because a newer version exists [{loadedVersion}]");
  72. continue;
  73. }
  74. loadedVersion = pluginInfo;
  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 [{pluginInfo}] because of process filters");
  81. Logger.LogDebug($"[{pluginInfo}] has the following process filters: {string.Join(", ", pluginInfo.Processes.Select(p => p.ProcessName).ToArray())}");
  82. continue;
  83. }
  84. dependencyDict[pluginInfo.Metadata.GUID] = pluginInfo.Dependencies.Select(d => d.DependencyGUID);
  85. pluginsByGuid[pluginInfo.Metadata.GUID] = pluginInfo;
  86. }
  87. }
  88. foreach (var pluginInfo in pluginsByGuid.Values.ToList())
  89. {
  90. if (pluginInfo.Incompatibilities.Any(incompatibility => pluginsByGuid.ContainsKey(incompatibility.IncompatibilityGUID)))
  91. {
  92. pluginsByGuid.Remove(pluginInfo.Metadata.GUID);
  93. dependencyDict.Remove(pluginInfo.Metadata.GUID);
  94. var incompatiblePlugins = pluginInfo.Incompatibilities.Select(x => x.IncompatibilityGUID).Where(x => pluginsByGuid.ContainsKey(x)).ToArray();
  95. string message = $@"Could not load [{pluginInfo}] because it is incompatible with: {string.Join(", ", incompatiblePlugins)}";
  96. DependencyErrors.Add(message);
  97. Logger.LogError(message);
  98. }
  99. else if (PluginTargetsWrongBepin(pluginInfo))
  100. {
  101. string message = $@"Plugin [{pluginInfo}] targets a wrong version of BepInEx ({pluginInfo.TargettedBepInExVersion}) and might not work until you update";
  102. DependencyErrors.Add(message);
  103. Logger.LogWarning(message);
  104. }
  105. }
  106. var emptyDependencies = new string[0];
  107. // Sort plugins by their dependencies.
  108. // Give missing dependencies no dependencies of its own, which will cause missing plugins to be first in the resulting list.
  109. var sortedPlugins = Utility.TopologicalSort(dependencyDict.Keys, x => dependencyDict.TryGetValue(x, out var deps) ? deps : emptyDependencies).ToList();
  110. return sortedPlugins.Select(x => pluginsByGuid[x]).ToList();
  111. }
  112. public virtual void Execute()
  113. {
  114. try
  115. {
  116. var plugins = DiscoverPlugins();
  117. Logger.LogInfo($"{plugins.Count} plugins to load");
  118. ModifyLoadOrder(plugins);
  119. var invalidPlugins = new HashSet<string>();
  120. var processedPlugins = new Dictionary<string, Version>();
  121. var loadedAssemblies = new Dictionary<string, Assembly>();
  122. foreach (var plugin in plugins)
  123. {
  124. var dependsOnInvalidPlugin = false;
  125. var missingDependencies = new List<BepInDependency>();
  126. foreach (var dependency in plugin.Dependencies)
  127. {
  128. // If the depenency wasn't already processed, it's missing altogether
  129. bool depenencyExists = processedPlugins.TryGetValue(dependency.DependencyGUID, out var pluginVersion);
  130. if (!depenencyExists || pluginVersion < dependency.MinimumVersion)
  131. {
  132. // If the dependency is hard, collect it into a list to show
  133. if ((dependency.Flags & BepInDependency.DependencyFlags.HardDependency) != 0)
  134. missingDependencies.Add(dependency);
  135. continue;
  136. }
  137. // If the dependency is invalid (e.g. has missing depedencies), report that to the user
  138. if (invalidPlugins.Contains(dependency.DependencyGUID))
  139. {
  140. dependsOnInvalidPlugin = true;
  141. break;
  142. }
  143. }
  144. processedPlugins.Add(plugin.Metadata.GUID, plugin.Metadata.Version);
  145. if (dependsOnInvalidPlugin)
  146. {
  147. string message = $"Skipping [{plugin}] because it has a dependency that was not loaded. See previous errors for details.";
  148. DependencyErrors.Add(message);
  149. Logger.LogWarning(message);
  150. continue;
  151. }
  152. if (missingDependencies.Count != 0)
  153. {
  154. bool IsEmptyVersion(Version v) => v.Major == 0 && v.Minor == 0 && v.Build <= 0 && v.Revision <= 0;
  155. string message = $@"Could not load [{plugin}] because it has missing dependencies: {
  156. string.Join(", ", missingDependencies.Select(s => IsEmptyVersion(s.MinimumVersion) ? s.DependencyGUID : $"{s.DependencyGUID} (v{s.MinimumVersion} or newer)").ToArray())
  157. }";
  158. DependencyErrors.Add(message);
  159. Logger.LogError(message);
  160. invalidPlugins.Add(plugin.Metadata.GUID);
  161. continue;
  162. }
  163. try
  164. {
  165. Logger.LogInfo($"Loading [{plugin}]");
  166. if (!loadedAssemblies.TryGetValue(plugin.Location, out var ass))
  167. loadedAssemblies[plugin.Location] = ass = Assembly.LoadFile(plugin.Location);
  168. Plugins[plugin.Metadata.GUID] = plugin;
  169. plugin.Instance = LoadPlugin(plugin, ass);
  170. //_plugins.Add((TPlugin)plugin.Instance);
  171. }
  172. catch (Exception ex)
  173. {
  174. invalidPlugins.Add(plugin.Metadata.GUID);
  175. Plugins.Remove(plugin.Metadata.GUID);
  176. Logger.LogError($"Error loading [{plugin}] : {ex.Message}");
  177. if (ex is ReflectionTypeLoadException re)
  178. Logger.LogDebug(TypeLoader.TypeLoadExceptionToString(re));
  179. else
  180. Logger.LogDebug(ex);
  181. }
  182. }
  183. }
  184. catch (Exception ex)
  185. {
  186. try
  187. {
  188. ConsoleManager.CreateConsole();
  189. }
  190. catch { }
  191. Logger.LogError("Error occurred starting the game");
  192. Logger.LogDebug(ex);
  193. }
  194. Logger.LogMessage("Chainloader startup complete");
  195. }
  196. public abstract TPlugin LoadPlugin(PluginInfo pluginInfo, Assembly pluginAssembly);
  197. #endregion
  198. private static Regex allowedGuidRegex { get; } = new Regex(@"^[a-zA-Z0-9\._\-]+$");
  199. public static PluginInfo ToPluginInfo(TypeDefinition type, string assemblyLocation)
  200. {
  201. if (type.IsInterface || type.IsAbstract)
  202. return null;
  203. try
  204. {
  205. if (!type.IsSubtypeOf(typeof(TPlugin)))
  206. return null;
  207. }
  208. catch (AssemblyResolutionException)
  209. {
  210. // Can happen if this type inherits a type from an assembly that can't be found. Safe to assume it's not a plugin.
  211. return null;
  212. }
  213. var metadata = BepInPlugin.FromCecilType(type);
  214. // Perform checks that will prevent the plugin from being loaded in ALL cases
  215. if (metadata == null)
  216. {
  217. Logger.LogWarning($"Skipping over type [{type.FullName}] as no metadata attribute is specified");
  218. return null;
  219. }
  220. if (string.IsNullOrEmpty(metadata.GUID) || !allowedGuidRegex.IsMatch(metadata.GUID))
  221. {
  222. Logger.LogWarning($"Skipping type [{type.FullName}] because its GUID [{metadata.GUID}] is of an illegal format.");
  223. return null;
  224. }
  225. if (metadata.Version == null)
  226. {
  227. Logger.LogWarning($"Skipping type [{type.FullName}] because its version is invalid.");
  228. return null;
  229. }
  230. if (metadata.Name == null)
  231. {
  232. Logger.LogWarning($"Skipping type [{type.FullName}] because its name is null.");
  233. return null;
  234. }
  235. var filters = BepInProcess.FromCecilType(type);
  236. var dependencies = BepInDependency.FromCecilType(type);
  237. var incompatibilities = BepInIncompatibility.FromCecilType(type);
  238. var bepinVersion = type.Module.AssemblyReferences.FirstOrDefault(reference => reference.Name == "BepInEx.Core")?.Version ?? new Version();
  239. return new PluginInfo
  240. {
  241. Metadata = metadata,
  242. Processes = filters,
  243. Dependencies = dependencies,
  244. Incompatibilities = incompatibilities,
  245. TypeName = type.FullName,
  246. TargettedBepInExVersion = bepinVersion,
  247. Location = assemblyLocation
  248. };
  249. }
  250. protected static readonly string CurrentAssemblyName = Assembly.GetExecutingAssembly().GetName().Name;
  251. protected static readonly Version CurrentAssemblyVersion = Assembly.GetExecutingAssembly().GetName().Version;
  252. protected static bool HasBepinPlugins(AssemblyDefinition ass)
  253. {
  254. if (ass.MainModule.AssemblyReferences.All(r => r.Name != CurrentAssemblyName))
  255. return false;
  256. if (ass.MainModule.GetTypeReferences().All(r => r.FullName != typeof(TPlugin).FullName))
  257. return false;
  258. return true;
  259. }
  260. protected static bool PluginTargetsWrongBepin(PluginInfo pluginInfo)
  261. {
  262. var pluginTarget = pluginInfo.TargettedBepInExVersion;
  263. // X.X.X.x - compare normally. x.x.x.X - nightly build number, ignore
  264. if (pluginTarget.Major != CurrentAssemblyVersion.Major) return true;
  265. if (pluginTarget.Minor > CurrentAssemblyVersion.Minor) return true;
  266. if (pluginTarget.Minor < CurrentAssemblyVersion.Minor) return false;
  267. return pluginTarget.Build > CurrentAssemblyVersion.Build;
  268. }
  269. #region Config
  270. private static readonly ConfigEntry<bool> ConfigDiskAppend = ConfigFile.CoreConfig.Bind(
  271. "Logging.Disk", "AppendLog",
  272. false,
  273. "Appends to the log file instead of overwriting, on game startup.");
  274. private static readonly ConfigEntry<bool> ConfigDiskLogging = ConfigFile.CoreConfig.Bind(
  275. "Logging.Disk", "Enabled",
  276. true,
  277. "Enables writing log messages to disk.");
  278. private static readonly ConfigEntry<LogLevel> ConfigDiskConsoleDisplayedLevel = ConfigFile.CoreConfig.Bind(
  279. "Logging.Disk", "DisplayedLogLevel",
  280. LogLevel.Fatal | LogLevel.Error | LogLevel.Message | LogLevel.Info,
  281. "Only displays the specified log levels in the disk log output.");
  282. #endregion
  283. }
  284. }