Chainloader.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. using BepInEx.Configuration;
  2. using BepInEx.Logging;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Reflection;
  9. using System.Text;
  10. using System.Text.RegularExpressions;
  11. using Mono.Cecil;
  12. using UnityEngine;
  13. using UnityInjector.ConsoleUtil;
  14. using Logger = BepInEx.Logging.Logger;
  15. namespace BepInEx.Bootstrap
  16. {
  17. /// <summary>
  18. /// The manager and loader for all plugins, and the entry point for BepInEx plugin system.
  19. /// </summary>
  20. public static class Chainloader
  21. {
  22. /// <summary>
  23. /// The loaded and initialized list of plugins.
  24. /// </summary>
  25. public static Dictionary<string, PluginInfo> PluginInfos { get; } = new Dictionary<string, PluginInfo>();
  26. private static readonly List<BaseUnityPlugin> _plugins = new List<BaseUnityPlugin>();
  27. [Obsolete("Use PluginInfos instead")]
  28. public static List<BaseUnityPlugin> Plugins
  29. {
  30. get
  31. {
  32. lock (_plugins)
  33. {
  34. _plugins.RemoveAll(x => x == null);
  35. return _plugins.ToList();
  36. }
  37. }
  38. }
  39. public static List<string> DependencyErrors { get; } = new List<string>();
  40. /// <summary>
  41. /// The GameObject that all plugins are attached to as components.
  42. /// </summary>
  43. public static GameObject ManagerObject { get; private set; }
  44. private static bool _loaded = false;
  45. private static bool _initialized = false;
  46. /// <summary>
  47. /// Initializes BepInEx to be able to start the chainloader.
  48. /// </summary>
  49. public static void Initialize(string gameExePath, bool startConsole = true, ICollection<LogEventArgs> preloaderLogEvents = null)
  50. {
  51. if (_initialized)
  52. return;
  53. ThreadingHelper.Initialize();
  54. // Set vitals
  55. if (gameExePath != null)
  56. {
  57. // Checking for null allows a more advanced initialization workflow, where the Paths class has been initialized before calling Chainloader.Initialize
  58. // This is used by Preloader to use environment variables, for example
  59. Paths.SetExecutablePath(gameExePath);
  60. }
  61. // Start logging
  62. if (ConsoleWindow.ConfigConsoleEnabled.Value && startConsole)
  63. {
  64. ConsoleWindow.Attach();
  65. Logger.Listeners.Add(new ConsoleLogListener());
  66. }
  67. // Fix for standard output getting overwritten by UnityLogger
  68. if (ConsoleWindow.StandardOut != null)
  69. {
  70. Console.SetOut(ConsoleWindow.StandardOut);
  71. var encoding = ConsoleWindow.ConfigConsoleShiftJis.Value ? 932 : (uint)Encoding.UTF8.CodePage;
  72. ConsoleEncoding.ConsoleCodePage = encoding;
  73. Console.OutputEncoding = ConsoleEncoding.GetEncoding(encoding);
  74. }
  75. Logger.Listeners.Add(new UnityLogListener());
  76. if (ConfigDiskLogging.Value)
  77. Logger.Listeners.Add(new DiskLogListener("LogOutput.log", ConfigDiskConsoleDisplayedLevel.Value, ConfigDiskAppend.Value, ConfigDiskWriteUnityLog.Value));
  78. if (!TraceLogSource.IsListening)
  79. Logger.Sources.Add(TraceLogSource.CreateSource());
  80. if (ConfigUnityLogging.Value)
  81. Logger.Sources.Add(new UnityLogSource());
  82. // Temporarily disable the console log listener as we replay the preloader logs
  83. var logListener = Logger.Listeners.FirstOrDefault(logger => logger is ConsoleLogListener);
  84. if (logListener != null)
  85. Logger.Listeners.Remove(logListener);
  86. // Write preloader log events if there are any, including the original log source name
  87. if (preloaderLogEvents != null)
  88. {
  89. var preloaderLogSource = Logger.CreateLogSource("Preloader");
  90. foreach (var preloaderLogEvent in preloaderLogEvents)
  91. preloaderLogSource.Log(preloaderLogEvent.Level, $"[{preloaderLogEvent.Source.SourceName,10}] {preloaderLogEvent.Data}");
  92. Logger.Sources.Remove(preloaderLogSource);
  93. }
  94. if (logListener != null)
  95. Logger.Listeners.Add(logListener);
  96. Logger.LogMessage("Chainloader ready");
  97. _initialized = true;
  98. }
  99. private static Regex allowedGuidRegex { get; } = new Regex(@"^[a-zA-Z0-9\._\-]+$");
  100. public static PluginInfo ToPluginInfo(TypeDefinition type)
  101. {
  102. if (type.IsInterface || type.IsAbstract)
  103. return null;
  104. try
  105. {
  106. if (!type.IsSubtypeOf(typeof(BaseUnityPlugin)))
  107. return null;
  108. }
  109. catch (AssemblyResolutionException)
  110. {
  111. // Can happen if this type inherits a type from an assembly that can't be found. Safe to assume it's not a plugin.
  112. return null;
  113. }
  114. var metadata = BepInPlugin.FromCecilType(type);
  115. // Perform checks that will prevent the plugin from being loaded in ALL cases
  116. if (metadata == null)
  117. {
  118. Logger.LogWarning($"Skipping over type [{type.FullName}] as no metadata attribute is specified");
  119. return null;
  120. }
  121. if (string.IsNullOrEmpty(metadata.GUID) || !allowedGuidRegex.IsMatch(metadata.GUID))
  122. {
  123. Logger.LogWarning($"Skipping type [{type.FullName}] because its GUID [{metadata.GUID}] is of an illegal format.");
  124. return null;
  125. }
  126. if (metadata.Version == null)
  127. {
  128. Logger.LogWarning($"Skipping type [{type.FullName}] because its version is invalid.");
  129. return null;
  130. }
  131. if (metadata.Name == null)
  132. {
  133. Logger.LogWarning($"Skipping type [{type.FullName}] because its name is null.");
  134. return null;
  135. }
  136. var filters = BepInProcess.FromCecilType(type);
  137. var dependencies = BepInDependency.FromCecilType(type);
  138. var incompatibilities = BepInIncompatibility.FromCecilType(type);
  139. var bepinVersion = type.Module.AssemblyReferences.FirstOrDefault(reference => reference.Name == "BepInEx")?.Version ?? new Version();
  140. return new PluginInfo
  141. {
  142. Metadata = metadata,
  143. Processes = filters,
  144. Dependencies = dependencies,
  145. Incompatibilities = incompatibilities,
  146. TypeName = type.FullName,
  147. TargettedBepInExVersion = bepinVersion
  148. };
  149. }
  150. private static readonly string CurrentAssemblyName = Assembly.GetExecutingAssembly().GetName().Name;
  151. private static readonly Version CurrentAssemblyVersion = Assembly.GetExecutingAssembly().GetName().Version;
  152. private static bool HasBepinPlugins(AssemblyDefinition ass)
  153. {
  154. if (ass.MainModule.AssemblyReferences.All(r => r.Name != CurrentAssemblyName))
  155. return false;
  156. if (ass.MainModule.GetTypeReferences().All(r => r.FullName != typeof(BaseUnityPlugin).FullName))
  157. return false;
  158. return true;
  159. }
  160. private static bool PluginTargetsWrongBepin(PluginInfo pluginInfo)
  161. {
  162. var pluginTarget = pluginInfo.TargettedBepInExVersion;
  163. // X.X.X.x - compare normally. x.x.x.X - nightly build number, ignore
  164. if (pluginTarget.Major != CurrentAssemblyVersion.Major) return true;
  165. if (pluginTarget.Minor > CurrentAssemblyVersion.Minor) return true;
  166. if (pluginTarget.Minor < CurrentAssemblyVersion.Minor) return false;
  167. return pluginTarget.Build > CurrentAssemblyVersion.Build;
  168. }
  169. /// <summary>
  170. /// The entrypoint for the BepInEx plugin system.
  171. /// </summary>
  172. public static void Start()
  173. {
  174. if (_loaded)
  175. return;
  176. if (!_initialized)
  177. throw new InvalidOperationException("BepInEx has not been initialized. Please call Chainloader.Initialize prior to starting the chainloader instance.");
  178. if (!Directory.Exists(Paths.PluginPath))
  179. Directory.CreateDirectory(Paths.PluginPath);
  180. if (!Directory.Exists(Paths.PatcherPluginPath))
  181. Directory.CreateDirectory(Paths.PatcherPluginPath);
  182. try
  183. {
  184. var productNameProp = typeof(Application).GetProperty("productName", BindingFlags.Public | BindingFlags.Static);
  185. ConsoleWindow.Title = $"{CurrentAssemblyName} {CurrentAssemblyVersion} - {productNameProp?.GetValue(null, null) ?? Process.GetCurrentProcess().ProcessName}";
  186. Logger.LogMessage("Chainloader started");
  187. ManagerObject = new GameObject("BepInEx_Manager");
  188. UnityEngine.Object.DontDestroyOnLoad(ManagerObject);
  189. var pluginsToLoad = TypeLoader.FindPluginTypes(Paths.PluginPath, ToPluginInfo, HasBepinPlugins, "chainloader");
  190. foreach (var keyValuePair in pluginsToLoad)
  191. foreach (var pluginInfo in keyValuePair.Value)
  192. pluginInfo.Location = keyValuePair.Key;
  193. var pluginInfos = pluginsToLoad.SelectMany(p => p.Value).ToList();
  194. var loadedAssemblies = new Dictionary<string, Assembly>();
  195. Logger.LogInfo($"{pluginInfos.Count} plugins to load");
  196. // We use a sorted dictionary to ensure consistent load order
  197. var dependencyDict = new SortedDictionary<string, IEnumerable<string>>(StringComparer.InvariantCultureIgnoreCase);
  198. var pluginsByGUID = new Dictionary<string, PluginInfo>();
  199. foreach (var pluginInfoGroup in pluginInfos.GroupBy(info => info.Metadata.GUID))
  200. {
  201. var alreadyLoaded = false;
  202. foreach (var pluginInfo in pluginInfoGroup.OrderByDescending(x => x.Metadata.Version))
  203. {
  204. if (alreadyLoaded)
  205. {
  206. Logger.LogWarning($"Skipping because a newer version exists [{pluginInfo.Metadata.Name} {pluginInfo.Metadata.Version}]");
  207. continue;
  208. }
  209. alreadyLoaded = true;
  210. // Perform checks that will prevent loading plugins in this run
  211. var filters = pluginInfo.Processes.ToList();
  212. bool invalidProcessName = filters.Count != 0 && filters.All(x => !string.Equals(x.ProcessName.Replace(".exe", ""), Paths.ProcessName, StringComparison.InvariantCultureIgnoreCase));
  213. if (invalidProcessName)
  214. {
  215. Logger.LogWarning($"Skipping because of process filters [{pluginInfo.Metadata.Name} {pluginInfo.Metadata.Version}]");
  216. continue;
  217. }
  218. dependencyDict[pluginInfo.Metadata.GUID] = pluginInfo.Dependencies.Select(d => d.DependencyGUID);
  219. pluginsByGUID[pluginInfo.Metadata.GUID] = pluginInfo;
  220. }
  221. }
  222. foreach (var pluginInfo in pluginsByGUID.Values.ToList())
  223. {
  224. if (pluginInfo.Incompatibilities.Any(incompatibility => pluginsByGUID.ContainsKey(incompatibility.IncompatibilityGUID)))
  225. {
  226. pluginsByGUID.Remove(pluginInfo.Metadata.GUID);
  227. dependencyDict.Remove(pluginInfo.Metadata.GUID);
  228. var incompatiblePlugins = pluginInfo.Incompatibilities.Select(x => x.IncompatibilityGUID).Where(x => pluginsByGUID.ContainsKey(x)).ToArray();
  229. string message = $@"Could not load [{pluginInfo.Metadata.Name}] because it is incompatible with: {string.Join(", ", incompatiblePlugins)}";
  230. DependencyErrors.Add(message);
  231. Logger.LogError(message);
  232. }
  233. else if (PluginTargetsWrongBepin(pluginInfo))
  234. {
  235. string message = $@"Plugin [{pluginInfo.Metadata.Name}] targets a wrong version of BepInEx ({pluginInfo.TargettedBepInExVersion}) and might not work until you update";
  236. DependencyErrors.Add(message);
  237. Logger.LogWarning(message);
  238. }
  239. }
  240. var emptyDependencies = new string[0];
  241. // Sort plugins by their dependencies.
  242. // Give missing dependencies no dependencies of its own, which will cause missing plugins to be first in the resulting list.
  243. var sortedPlugins = Utility.TopologicalSort(dependencyDict.Keys, x => dependencyDict.TryGetValue(x, out var deps) ? deps : emptyDependencies).ToList();
  244. var invalidPlugins = new HashSet<string>();
  245. var processedPlugins = new Dictionary<string, Version>();
  246. foreach (var pluginGUID in sortedPlugins)
  247. {
  248. // If the plugin is missing, don't process it
  249. if (!pluginsByGUID.TryGetValue(pluginGUID, out var pluginInfo))
  250. continue;
  251. var dependsOnInvalidPlugin = false;
  252. var missingDependencies = new List<BepInDependency>();
  253. foreach (var dependency in pluginInfo.Dependencies)
  254. {
  255. // If the depenency wasn't already processed, it's missing altogether
  256. bool depenencyExists = processedPlugins.TryGetValue(dependency.DependencyGUID, out var pluginVersion);
  257. if (!depenencyExists || pluginVersion < dependency.MinimumVersion)
  258. {
  259. // If the dependency is hard, collect it into a list to show
  260. if ((dependency.Flags & BepInDependency.DependencyFlags.HardDependency) != 0)
  261. missingDependencies.Add(dependency);
  262. continue;
  263. }
  264. // If the dependency is invalid (e.g. has missing depedencies), report that to the user
  265. if (invalidPlugins.Contains(dependency.DependencyGUID))
  266. {
  267. dependsOnInvalidPlugin = true;
  268. break;
  269. }
  270. }
  271. processedPlugins.Add(pluginGUID, pluginInfo.Metadata.Version);
  272. if (dependsOnInvalidPlugin)
  273. {
  274. string message = $"Skipping [{pluginInfo.Metadata.Name}] because it has a dependency that was not loaded. See previous errors for details.";
  275. DependencyErrors.Add(message);
  276. Logger.LogWarning(message);
  277. continue;
  278. }
  279. if (missingDependencies.Count != 0)
  280. {
  281. bool IsEmptyVersion(Version v) => v.Major == 0 && v.Minor == 0 && v.Build <= 0 && v.Revision <= 0;
  282. string message = $@"Could not load [{pluginInfo.Metadata.Name}] because it has missing dependencies: {
  283. string.Join(", ", missingDependencies.Select(s => IsEmptyVersion(s.MinimumVersion) ? s.DependencyGUID : $"{s.DependencyGUID} (v{s.MinimumVersion} or newer)").ToArray())
  284. }";
  285. DependencyErrors.Add(message);
  286. Logger.LogError(message);
  287. invalidPlugins.Add(pluginGUID);
  288. continue;
  289. }
  290. try
  291. {
  292. Logger.LogInfo($"Loading [{pluginInfo.Metadata.Name} {pluginInfo.Metadata.Version}]");
  293. if (!loadedAssemblies.TryGetValue(pluginInfo.Location, out var ass))
  294. loadedAssemblies[pluginInfo.Location] = ass = Assembly.LoadFile(pluginInfo.Location);
  295. PluginInfos[pluginGUID] = pluginInfo;
  296. pluginInfo.Instance = (BaseUnityPlugin)ManagerObject.AddComponent(ass.GetType(pluginInfo.TypeName));
  297. _plugins.Add(pluginInfo.Instance);
  298. }
  299. catch (Exception ex)
  300. {
  301. invalidPlugins.Add(pluginGUID);
  302. PluginInfos.Remove(pluginGUID);
  303. Logger.LogError($"Error loading [{pluginInfo.Metadata.Name}] : {ex.Message}");
  304. if (ex is ReflectionTypeLoadException re)
  305. Logger.LogDebug(TypeLoader.TypeLoadExceptionToString(re));
  306. else
  307. Logger.LogDebug(ex);
  308. }
  309. }
  310. }
  311. catch (Exception ex)
  312. {
  313. ConsoleWindow.Attach();
  314. Console.WriteLine("Error occurred starting the game");
  315. Console.WriteLine(ex.ToString());
  316. }
  317. Logger.LogMessage("Chainloader startup complete");
  318. _loaded = true;
  319. }
  320. #region Config
  321. private static readonly ConfigEntry<bool> ConfigUnityLogging = ConfigFile.CoreConfig.Bind(
  322. "Logging", "UnityLogListening",
  323. true,
  324. "Enables showing unity log messages in the BepInEx logging system.");
  325. private static readonly ConfigEntry<bool> ConfigDiskWriteUnityLog = ConfigFile.CoreConfig.Bind(
  326. "Logging.Disk", "WriteUnityLog",
  327. false,
  328. "Include unity log messages in log file output.");
  329. private static readonly ConfigEntry<bool> ConfigDiskAppend = ConfigFile.CoreConfig.Bind(
  330. "Logging.Disk", "AppendLog",
  331. false,
  332. "Appends to the log file instead of overwriting, on game startup.");
  333. private static readonly ConfigEntry<bool> ConfigDiskLogging = ConfigFile.CoreConfig.Bind(
  334. "Logging.Disk", "Enabled",
  335. true,
  336. "Enables writing log messages to disk.");
  337. private static readonly ConfigEntry<LogLevel> ConfigDiskConsoleDisplayedLevel = ConfigFile.CoreConfig.Bind(
  338. "Logging.Disk", "DisplayedLogLevel",
  339. LogLevel.Info,
  340. "Only displays the specified log level and above in the console output.");
  341. #endregion
  342. }
  343. }