Chainloader.cs 13 KB

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