Chainloader.cs 11 KB

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