Chainloader.cs 12 KB

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