Chainloader.cs 12 KB

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