Chainloader.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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. var preloaderLogSource = Logger.CreateLogSource("Preloader");
  87. foreach (var preloaderLogEvent in preloaderLogEvents)
  88. {
  89. preloaderLogSource.Log(preloaderLogEvent.Level, preloaderLogEvent.Data);
  90. }
  91. Logger.Sources.Remove(preloaderLogSource);
  92. if (logListener != null)
  93. Logger.Listeners.Add(logListener);
  94. Logger.LogMessage("Chainloader ready");
  95. _initialized = true;
  96. }
  97. private static Regex allowedGuidRegex { get; } = new Regex(@"^[a-zA-Z0-9\._\-]+$");
  98. public static PluginInfo ToPluginInfo(TypeDefinition type)
  99. {
  100. if (type.IsInterface || type.IsAbstract)
  101. return null;
  102. try
  103. {
  104. if (!type.IsSubtypeOf(typeof(BaseUnityPlugin)))
  105. return null;
  106. }
  107. catch (AssemblyResolutionException)
  108. {
  109. // Can happen if this type inherits a type from an assembly that can't be found. Safe to assume it's not a plugin.
  110. return null;
  111. }
  112. var metadata = BepInPlugin.FromCecilType(type);
  113. // Perform checks that will prevent the plugin from being loaded in ALL cases
  114. if (metadata == null)
  115. {
  116. Logger.LogWarning($"Skipping over type [{type.FullName}] as no metadata attribute is specified");
  117. return null;
  118. }
  119. if (string.IsNullOrEmpty(metadata.GUID) || !allowedGuidRegex.IsMatch(metadata.GUID))
  120. {
  121. Logger.LogWarning($"Skipping type [{type.FullName}] because its GUID [{metadata.GUID}] is of an illegal format.");
  122. return null;
  123. }
  124. if (metadata.Version == null)
  125. {
  126. Logger.LogWarning($"Skipping type [{type.FullName}] because its version is invalid.");
  127. return null;
  128. }
  129. if (metadata.Name == null)
  130. {
  131. Logger.LogWarning($"Skipping type [{type.FullName}] because its name is null.");
  132. return null;
  133. }
  134. var filters = BepInProcess.FromCecilType(type);
  135. var dependencies = BepInDependency.FromCecilType(type);
  136. var incompatibilities = BepInIncompatibility.FromCecilType(type);
  137. return new PluginInfo
  138. {
  139. Metadata = metadata,
  140. Processes = filters,
  141. Dependencies = dependencies,
  142. Incompatibilities = incompatibilities,
  143. TypeName = type.FullName
  144. };
  145. }
  146. private static readonly string CurrentAssemblyName = Assembly.GetExecutingAssembly().GetName().Name;
  147. private static readonly Version CurrentAssemblyVersion = Assembly.GetExecutingAssembly().GetName().Version;
  148. private static bool HasBepinPlugins(AssemblyDefinition ass)
  149. {
  150. if (ass.MainModule.AssemblyReferences.All(r => r.Name != CurrentAssemblyName))
  151. return false;
  152. if (ass.MainModule.GetTypeReferences().All(r => r.FullName != typeof(BaseUnityPlugin).FullName))
  153. return false;
  154. return true;
  155. }
  156. /// <summary>
  157. /// The entrypoint for the BepInEx plugin system.
  158. /// </summary>
  159. public static void Start()
  160. {
  161. if (_loaded)
  162. return;
  163. if (!_initialized)
  164. throw new InvalidOperationException("BepInEx has not been initialized. Please call Chainloader.Initialize prior to starting the chainloader instance.");
  165. if (!Directory.Exists(Paths.PluginPath))
  166. Directory.CreateDirectory(Paths.PluginPath);
  167. if (!Directory.Exists(Paths.PatcherPluginPath))
  168. Directory.CreateDirectory(Paths.PatcherPluginPath);
  169. try
  170. {
  171. var productNameProp = typeof(Application).GetProperty("productName", BindingFlags.Public | BindingFlags.Static);
  172. ConsoleWindow.Title = $"{CurrentAssemblyName} {CurrentAssemblyVersion} - {productNameProp?.GetValue(null, null) ?? Process.GetCurrentProcess().ProcessName}";
  173. Logger.LogMessage("Chainloader started");
  174. ManagerObject = new GameObject("BepInEx_Manager");
  175. UnityEngine.Object.DontDestroyOnLoad(ManagerObject);
  176. var pluginsToLoad = TypeLoader.FindPluginTypes(Paths.PluginPath, ToPluginInfo, HasBepinPlugins, "chainloader");
  177. foreach (var keyValuePair in pluginsToLoad)
  178. foreach (var pluginInfo in keyValuePair.Value)
  179. pluginInfo.Location = keyValuePair.Key;
  180. var pluginInfos = pluginsToLoad.SelectMany(p => p.Value).ToList();
  181. var loadedAssemblies = new Dictionary<string, Assembly>();
  182. Logger.LogInfo($"{pluginInfos.Count} plugins to load");
  183. // We use a sorted dictionary to ensure consistent load order
  184. var dependencyDict = new SortedDictionary<string, IEnumerable<string>>(StringComparer.InvariantCultureIgnoreCase);
  185. var pluginsByGUID = new Dictionary<string, PluginInfo>();
  186. foreach (var pluginInfoGroup in pluginInfos.GroupBy(info => info.Metadata.GUID))
  187. {
  188. var alreadyLoaded = false;
  189. foreach (var pluginInfo in pluginInfoGroup.OrderByDescending(x => x.Metadata.Version))
  190. {
  191. if (alreadyLoaded)
  192. {
  193. Logger.LogWarning($"Skipping because a newer version exists [{pluginInfo.Metadata.Name} {pluginInfo.Metadata.Version}]");
  194. continue;
  195. }
  196. alreadyLoaded = true;
  197. // Perform checks that will prevent loading plugins in this run
  198. var filters = pluginInfo.Processes.ToList();
  199. bool invalidProcessName = filters.Count != 0 && filters.All(x => !string.Equals(x.ProcessName.Replace(".exe", ""), Paths.ProcessName, StringComparison.InvariantCultureIgnoreCase));
  200. if (invalidProcessName)
  201. {
  202. Logger.LogWarning($"Skipping because of process filters [{pluginInfo.Metadata.Name} {pluginInfo.Metadata.Version}]");
  203. continue;
  204. }
  205. dependencyDict[pluginInfo.Metadata.GUID] = pluginInfo.Dependencies.Select(d => d.DependencyGUID);
  206. pluginsByGUID[pluginInfo.Metadata.GUID] = pluginInfo;
  207. }
  208. }
  209. foreach (var pluginInfo in pluginsByGUID.Values.ToList())
  210. {
  211. if (pluginInfo.Incompatibilities.Any(incompatibility => pluginsByGUID.ContainsKey(incompatibility.IncompatibilityGUID)))
  212. {
  213. pluginsByGUID.Remove(pluginInfo.Metadata.GUID);
  214. dependencyDict.Remove(pluginInfo.Metadata.GUID);
  215. var incompatiblePlugins = pluginInfo.Incompatibilities.Select(x => x.IncompatibilityGUID).Where(x => pluginsByGUID.ContainsKey(x)).ToArray();
  216. string message = $@"Could not load [{pluginInfo.Metadata.Name}] because it is incompatible with: {string.Join(", ", incompatiblePlugins)}";
  217. DependencyErrors.Add(message);
  218. Logger.LogError(message);
  219. }
  220. }
  221. var emptyDependencies = new string[0];
  222. // Sort plugins by their dependencies.
  223. // Give missing dependencies no dependencies of its own, which will cause missing plugins to be first in the resulting list.
  224. var sortedPlugins = Utility.TopologicalSort(dependencyDict.Keys, x => dependencyDict.TryGetValue(x, out var deps) ? deps : emptyDependencies).ToList();
  225. var invalidPlugins = new HashSet<string>();
  226. var processedPlugins = new Dictionary<string, Version>();
  227. foreach (var pluginGUID in sortedPlugins)
  228. {
  229. // If the plugin is missing, don't process it
  230. if (!pluginsByGUID.TryGetValue(pluginGUID, out var pluginInfo))
  231. continue;
  232. var dependsOnInvalidPlugin = false;
  233. var missingDependencies = new List<BepInDependency>();
  234. foreach (var dependency in pluginInfo.Dependencies)
  235. {
  236. // If the depenency wasn't already processed, it's missing altogether
  237. bool depenencyExists = processedPlugins.TryGetValue(dependency.DependencyGUID, out var pluginVersion);
  238. if (!depenencyExists || pluginVersion < dependency.MinimumVersion)
  239. {
  240. // If the dependency is hard, collect it into a list to show
  241. if ((dependency.Flags & BepInDependency.DependencyFlags.HardDependency) != 0)
  242. missingDependencies.Add(dependency);
  243. continue;
  244. }
  245. // If the dependency is invalid (e.g. has missing depedencies), report that to the user
  246. if (invalidPlugins.Contains(dependency.DependencyGUID))
  247. {
  248. dependsOnInvalidPlugin = true;
  249. break;
  250. }
  251. }
  252. processedPlugins.Add(pluginGUID, pluginInfo.Metadata.Version);
  253. if (dependsOnInvalidPlugin)
  254. {
  255. string message = $"Skipping [{pluginInfo.Metadata.Name}] because it has a dependency that was not loaded. See previous errors for details.";
  256. DependencyErrors.Add(message);
  257. Logger.LogWarning(message);
  258. continue;
  259. }
  260. if (missingDependencies.Count != 0)
  261. {
  262. bool IsEmptyVersion(Version v) => v.Major == 0 && v.Minor == 0 && v.Build <= 0 && v.Revision <= 0;
  263. string message = $@"Could not load [{pluginInfo.Metadata.Name}] because it has missing dependencies: {
  264. string.Join(", ", missingDependencies.Select(s => IsEmptyVersion(s.MinimumVersion) ? s.DependencyGUID : $"{s.DependencyGUID} (v{s.MinimumVersion} or newer)").ToArray())
  265. }";
  266. DependencyErrors.Add(message);
  267. Logger.LogError(message);
  268. invalidPlugins.Add(pluginGUID);
  269. continue;
  270. }
  271. try
  272. {
  273. Logger.LogInfo($"Loading [{pluginInfo.Metadata.Name} {pluginInfo.Metadata.Version}]");
  274. if (!loadedAssemblies.TryGetValue(pluginInfo.Location, out var ass))
  275. loadedAssemblies[pluginInfo.Location] = ass = Assembly.LoadFile(pluginInfo.Location);
  276. PluginInfos[pluginGUID] = pluginInfo;
  277. pluginInfo.Instance = (BaseUnityPlugin)ManagerObject.AddComponent(ass.GetType(pluginInfo.TypeName));
  278. _plugins.Add(pluginInfo.Instance);
  279. }
  280. catch (Exception ex)
  281. {
  282. invalidPlugins.Add(pluginGUID);
  283. PluginInfos.Remove(pluginGUID);
  284. Logger.LogError($"Error loading [{pluginInfo.Metadata.Name}] : {ex.Message}");
  285. if (ex is ReflectionTypeLoadException re)
  286. Logger.LogDebug(TypeLoader.TypeLoadExceptionToString(re));
  287. else
  288. Logger.LogDebug(ex);
  289. }
  290. }
  291. }
  292. catch (Exception ex)
  293. {
  294. ConsoleWindow.Attach();
  295. Console.WriteLine("Error occurred starting the game");
  296. Console.WriteLine(ex.ToString());
  297. }
  298. Logger.LogMessage("Chainloader startup complete");
  299. _loaded = true;
  300. }
  301. #region Config
  302. private static readonly ConfigEntry<bool> ConfigUnityLogging = ConfigFile.CoreConfig.Bind(
  303. "Logging", "UnityLogListening",
  304. true,
  305. "Enables showing unity log messages in the BepInEx logging system.");
  306. private static readonly ConfigEntry<bool> ConfigDiskWriteUnityLog = ConfigFile.CoreConfig.Bind(
  307. "Logging.Disk", "WriteUnityLog",
  308. false,
  309. "Include unity log messages in log file output.");
  310. private static readonly ConfigEntry<bool> ConfigDiskAppend = ConfigFile.CoreConfig.Bind(
  311. "Logging.Disk", "AppendLog",
  312. false,
  313. "Appends to the log file instead of overwriting, on game startup.");
  314. private static readonly ConfigEntry<bool> ConfigDiskLogging = ConfigFile.CoreConfig.Bind(
  315. "Logging.Disk", "Enabled",
  316. true,
  317. "Enables writing log messages to disk.");
  318. private static readonly ConfigEntry<LogLevel> ConfigDiskConsoleDisplayedLevel = ConfigFile.CoreConfig.Bind(
  319. "Logging.Disk", "DisplayedLogLevel",
  320. LogLevel.Info,
  321. "Only displays the specified log level and above in the console output.");
  322. #endregion
  323. }
  324. }