BaseChainloader.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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} - {Paths.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. if (!Logger.Sources.Any(x => x is HarmonyLogSource))
  54. Logger.Sources.Add(new HarmonyLogSource());
  55. }
  56. protected virtual IList<PluginInfo> DiscoverPlugins()
  57. {
  58. var pluginsToLoad = TypeLoader.FindPluginTypes(Paths.PluginPath, ToPluginInfo, HasBepinPlugins, "chainloader");
  59. return pluginsToLoad.SelectMany(p => p.Value).ToList();
  60. }
  61. protected virtual IList<PluginInfo> ModifyLoadOrder(IList<PluginInfo> plugins)
  62. {
  63. // We use a sorted dictionary to ensure consistent load order
  64. var dependencyDict = new SortedDictionary<string, IEnumerable<string>>(StringComparer.InvariantCultureIgnoreCase);
  65. var pluginsByGuid = new Dictionary<string, PluginInfo>();
  66. foreach (var pluginInfoGroup in plugins.GroupBy(info => info.Metadata.GUID))
  67. {
  68. PluginInfo loadedVersion = null;
  69. foreach (var pluginInfo in pluginInfoGroup.OrderByDescending(x => x.Metadata.Version))
  70. {
  71. if (loadedVersion != null)
  72. {
  73. Logger.LogWarning($"Skipping [{pluginInfo}] because a newer version exists ({loadedVersion})");
  74. continue;
  75. }
  76. // Perform checks that will prevent loading plugins in this run
  77. var filters = pluginInfo.Processes.ToList();
  78. bool invalidProcessName = filters.Count != 0 && filters.All(x => !string.Equals(x.ProcessName.Replace(".exe", ""), Paths.ProcessName, StringComparison.InvariantCultureIgnoreCase));
  79. if (invalidProcessName)
  80. {
  81. Logger.LogWarning($"Skipping [{pluginInfo}] because of process filters ({string.Join(", ", pluginInfo.Processes.Select(p => p.ProcessName).ToArray())})");
  82. continue;
  83. }
  84. loadedVersion = pluginInfo;
  85. dependencyDict[pluginInfo.Metadata.GUID] = pluginInfo.Dependencies.Select(d => d.DependencyGUID);
  86. pluginsByGuid[pluginInfo.Metadata.GUID] = pluginInfo;
  87. }
  88. }
  89. foreach (var pluginInfo in pluginsByGuid.Values.ToList())
  90. {
  91. if (pluginInfo.Incompatibilities.Any(incompatibility => pluginsByGuid.ContainsKey(incompatibility.IncompatibilityGUID)))
  92. {
  93. pluginsByGuid.Remove(pluginInfo.Metadata.GUID);
  94. dependencyDict.Remove(pluginInfo.Metadata.GUID);
  95. var incompatiblePlugins = pluginInfo.Incompatibilities.Select(x => x.IncompatibilityGUID).Where(x => pluginsByGuid.ContainsKey(x)).ToArray();
  96. string message = $@"Could not load [{pluginInfo}] because it is incompatible with: {string.Join(", ", incompatiblePlugins)}";
  97. DependencyErrors.Add(message);
  98. Logger.LogError(message);
  99. }
  100. else if (PluginTargetsWrongBepin(pluginInfo))
  101. {
  102. string message = $@"Plugin [{pluginInfo}] targets a wrong version of BepInEx ({pluginInfo.TargettedBepInExVersion}) and might not work until you update";
  103. DependencyErrors.Add(message);
  104. Logger.LogWarning(message);
  105. }
  106. }
  107. var emptyDependencies = new string[0];
  108. // Sort plugins by their dependencies.
  109. // Give missing dependencies no dependencies of its own, which will cause missing plugins to be first in the resulting list.
  110. var sortedPlugins = Utility.TopologicalSort(dependencyDict.Keys, x => dependencyDict.TryGetValue(x, out var deps) ? deps : emptyDependencies).ToList();
  111. return sortedPlugins.Select(x => pluginsByGuid[x]).ToList();
  112. }
  113. public virtual void Execute()
  114. {
  115. try
  116. {
  117. var plugins = DiscoverPlugins();
  118. Logger.LogInfo($"{plugins.Count} plugins to load");
  119. ModifyLoadOrder(plugins);
  120. var invalidPlugins = new HashSet<string>();
  121. var processedPlugins = new Dictionary<string, Version>();
  122. var loadedAssemblies = new Dictionary<string, Assembly>();
  123. foreach (var plugin in plugins)
  124. {
  125. var dependsOnInvalidPlugin = false;
  126. var missingDependencies = new List<BepInDependency>();
  127. foreach (var dependency in plugin.Dependencies)
  128. {
  129. bool IsHardDependency(BepInDependency dep)
  130. => (dep.Flags & BepInDependency.DependencyFlags.HardDependency) != 0;
  131. // If the dependency wasn't already processed, it's missing altogether
  132. bool dependencyExists = processedPlugins.TryGetValue(dependency.DependencyGUID, out var pluginVersion);
  133. if (!dependencyExists || pluginVersion < dependency.MinimumVersion)
  134. {
  135. // If the dependency is hard, collect it into a list to show
  136. if (IsHardDependency(dependency))
  137. missingDependencies.Add(dependency);
  138. continue;
  139. }
  140. // If the dependency is a hard and is invalid (e.g. has missing dependencies), report that to the user
  141. if (invalidPlugins.Contains(dependency.DependencyGUID) && IsHardDependency(dependency))
  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}] 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}] 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}]");
  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}] : {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. try
  190. {
  191. ConsoleManager.CreateConsole();
  192. }
  193. catch { }
  194. Logger.LogError("Error occurred starting the game");
  195. Logger.LogDebug(ex);
  196. }
  197. Logger.LogMessage("Chainloader startup complete");
  198. }
  199. public abstract TPlugin LoadPlugin(PluginInfo pluginInfo, Assembly pluginAssembly);
  200. #endregion
  201. private static Regex allowedGuidRegex { get; } = new Regex(@"^[a-zA-Z0-9\._\-]+$");
  202. public static PluginInfo ToPluginInfo(TypeDefinition type, string assemblyLocation)
  203. {
  204. if (type.IsInterface || type.IsAbstract)
  205. return null;
  206. try
  207. {
  208. if (!type.IsSubtypeOf(typeof(TPlugin)))
  209. return null;
  210. }
  211. catch (AssemblyResolutionException)
  212. {
  213. // Can happen if this type inherits a type from an assembly that can't be found. Safe to assume it's not a plugin.
  214. return null;
  215. }
  216. var metadata = BepInPlugin.FromCecilType(type);
  217. // Perform checks that will prevent the plugin from being loaded in ALL cases
  218. if (metadata == null)
  219. {
  220. Logger.LogWarning($"Skipping over type [{type.FullName}] as no metadata attribute is specified");
  221. return null;
  222. }
  223. if (string.IsNullOrEmpty(metadata.GUID) || !allowedGuidRegex.IsMatch(metadata.GUID))
  224. {
  225. Logger.LogWarning($"Skipping type [{type.FullName}] because its GUID [{metadata.GUID}] is of an illegal format.");
  226. return null;
  227. }
  228. if (metadata.Version == null)
  229. {
  230. Logger.LogWarning($"Skipping type [{type.FullName}] because its version is invalid.");
  231. return null;
  232. }
  233. if (metadata.Name == null)
  234. {
  235. Logger.LogWarning($"Skipping type [{type.FullName}] because its name is null.");
  236. return null;
  237. }
  238. var filters = BepInProcess.FromCecilType(type);
  239. var dependencies = BepInDependency.FromCecilType(type);
  240. var incompatibilities = BepInIncompatibility.FromCecilType(type);
  241. var bepinVersion = type.Module.AssemblyReferences.FirstOrDefault(reference => reference.Name == "BepInEx.Core")?.Version ?? new Version();
  242. return new PluginInfo
  243. {
  244. Metadata = metadata,
  245. Processes = filters,
  246. Dependencies = dependencies,
  247. Incompatibilities = incompatibilities,
  248. TypeName = type.FullName,
  249. TargettedBepInExVersion = bepinVersion,
  250. Location = assemblyLocation
  251. };
  252. }
  253. protected static readonly string CurrentAssemblyName = Assembly.GetExecutingAssembly().GetName().Name;
  254. protected static readonly Version CurrentAssemblyVersion = Assembly.GetExecutingAssembly().GetName().Version;
  255. protected static bool HasBepinPlugins(AssemblyDefinition ass)
  256. {
  257. if (ass.MainModule.AssemblyReferences.All(r => r.Name != CurrentAssemblyName))
  258. return false;
  259. if (ass.MainModule.GetTypeReferences().All(r => r.FullName != typeof(TPlugin).FullName))
  260. return false;
  261. return true;
  262. }
  263. protected static bool PluginTargetsWrongBepin(PluginInfo pluginInfo)
  264. {
  265. var pluginTarget = pluginInfo.TargettedBepInExVersion;
  266. // X.X.X.x - compare normally. x.x.x.X - nightly build number, ignore
  267. if (pluginTarget.Major != CurrentAssemblyVersion.Major) return true;
  268. if (pluginTarget.Minor > CurrentAssemblyVersion.Minor) return true;
  269. if (pluginTarget.Minor < CurrentAssemblyVersion.Minor) return false;
  270. return pluginTarget.Build > CurrentAssemblyVersion.Build;
  271. }
  272. #region Config
  273. private static readonly ConfigEntry<bool> ConfigDiskAppend = ConfigFile.CoreConfig.Bind(
  274. "Logging.Disk", "AppendLog",
  275. false,
  276. "Appends to the log file instead of overwriting, on game startup.");
  277. private static readonly ConfigEntry<bool> ConfigDiskLogging = ConfigFile.CoreConfig.Bind(
  278. "Logging.Disk", "Enabled",
  279. true,
  280. "Enables writing log messages to disk.");
  281. private static readonly ConfigEntry<LogLevel> ConfigDiskConsoleDisplayedLevel = ConfigFile.CoreConfig.Bind(
  282. "Logging.Disk", "LogLevels",
  283. LogLevel.Fatal | LogLevel.Error | LogLevel.Warning | LogLevel.Message | LogLevel.Info,
  284. "Only displays the specified log levels in the disk log output.");
  285. #endregion
  286. }
  287. }