BaseChainloader.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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} - {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. Logger.LogError("Error occurred starting the game");
  186. Logger.LogDebug(ex);
  187. }
  188. Logger.LogMessage("Chainloader startup complete");
  189. }
  190. public abstract TPlugin LoadPlugin(PluginInfo pluginInfo, Assembly pluginAssembly);
  191. #endregion
  192. private static Regex allowedGuidRegex { get; } = new Regex(@"^[a-zA-Z0-9\._\-]+$");
  193. public static PluginInfo ToPluginInfo(TypeDefinition type, string assemblyLocation)
  194. {
  195. if (type.IsInterface || type.IsAbstract)
  196. return null;
  197. try
  198. {
  199. if (!type.IsSubtypeOf(typeof(TPlugin)))
  200. return null;
  201. }
  202. catch (AssemblyResolutionException)
  203. {
  204. // Can happen if this type inherits a type from an assembly that can't be found. Safe to assume it's not a plugin.
  205. return null;
  206. }
  207. var metadata = BepInPlugin.FromCecilType(type);
  208. // Perform checks that will prevent the plugin from being loaded in ALL cases
  209. if (metadata == null)
  210. {
  211. Logger.LogWarning($"Skipping over type [{type.FullName}] as no metadata attribute is specified");
  212. return null;
  213. }
  214. if (string.IsNullOrEmpty(metadata.GUID) || !allowedGuidRegex.IsMatch(metadata.GUID))
  215. {
  216. Logger.LogWarning($"Skipping type [{type.FullName}] because its GUID [{metadata.GUID}] is of an illegal format.");
  217. return null;
  218. }
  219. if (metadata.Version == null)
  220. {
  221. Logger.LogWarning($"Skipping type [{type.FullName}] because its version is invalid.");
  222. return null;
  223. }
  224. if (metadata.Name == null)
  225. {
  226. Logger.LogWarning($"Skipping type [{type.FullName}] because its name is null.");
  227. return null;
  228. }
  229. var filters = BepInProcess.FromCecilType(type);
  230. var dependencies = BepInDependency.FromCecilType(type);
  231. var incompatibilities = BepInIncompatibility.FromCecilType(type);
  232. var bepinVersion = type.Module.AssemblyReferences.FirstOrDefault(reference => reference.Name == "BepInEx.Core")?.Version ?? new Version();
  233. return new PluginInfo
  234. {
  235. Metadata = metadata,
  236. Processes = filters,
  237. Dependencies = dependencies,
  238. Incompatibilities = incompatibilities,
  239. TypeName = type.FullName,
  240. TargettedBepInExVersion = bepinVersion,
  241. Location = assemblyLocation
  242. };
  243. }
  244. protected static readonly string CurrentAssemblyName = Assembly.GetExecutingAssembly().GetName().Name;
  245. protected static readonly Version CurrentAssemblyVersion = Assembly.GetExecutingAssembly().GetName().Version;
  246. protected static bool HasBepinPlugins(AssemblyDefinition ass)
  247. {
  248. if (ass.MainModule.AssemblyReferences.All(r => r.Name != CurrentAssemblyName))
  249. return false;
  250. if (ass.MainModule.GetTypeReferences().All(r => r.FullName != typeof(TPlugin).FullName))
  251. return false;
  252. return true;
  253. }
  254. protected static bool PluginTargetsWrongBepin(PluginInfo pluginInfo)
  255. {
  256. var pluginTarget = pluginInfo.TargettedBepInExVersion;
  257. // X.X.X.x - compare normally. x.x.x.X - nightly build number, ignore
  258. if (pluginTarget.Major != CurrentAssemblyVersion.Major) return true;
  259. if (pluginTarget.Minor > CurrentAssemblyVersion.Minor) return true;
  260. if (pluginTarget.Minor < CurrentAssemblyVersion.Minor) return false;
  261. return pluginTarget.Build > CurrentAssemblyVersion.Build;
  262. }
  263. #region Config
  264. private static readonly ConfigEntry<bool> ConfigDiskAppend = ConfigFile.CoreConfig.Bind(
  265. "Logging.Disk", "AppendLog",
  266. false,
  267. "Appends to the log file instead of overwriting, on game startup.");
  268. private static readonly ConfigEntry<bool> ConfigDiskLogging = ConfigFile.CoreConfig.Bind(
  269. "Logging.Disk", "Enabled",
  270. true,
  271. "Enables writing log messages to disk.");
  272. private static readonly ConfigEntry<LogLevel> ConfigDiskConsoleDisplayedLevel = ConfigFile.CoreConfig.Bind(
  273. "Logging.Disk", "DisplayedLogLevel",
  274. LogLevel.Info,
  275. "Only displays the specified log level and above in the console output.");
  276. #endregion
  277. }
  278. }