BaseChainloader.cs 12 KB

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