You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

358 lines
13 KiB

  1. #nullable enable
  2. using IPA.AntiMalware;
  3. using IPA.Config;
  4. using IPA.Injector.Backups;
  5. using IPA.Loader;
  6. using IPA.Logging;
  7. using IPA.Utilities;
  8. using Microsoft.Win32;
  9. using Mono.Cecil;
  10. using Mono.Cecil.Cil;
  11. using System;
  12. using System.Diagnostics;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Reflection;
  16. using System.Threading.Tasks;
  17. using UnityEngine;
  18. using static IPA.Logging.Logger;
  19. using MethodAttributes = Mono.Cecil.MethodAttributes;
  20. #if NET3
  21. using Net3_Proxy;
  22. using Path = Net3_Proxy.Path;
  23. using File = Net3_Proxy.File;
  24. using Directory = Net3_Proxy.Directory;
  25. #endif
  26. namespace IPA.Injector
  27. {
  28. /// <summary>
  29. /// The entry point type for BSIPA's Doorstop injector.
  30. /// </summary>
  31. // ReSharper disable once UnusedMember.Global
  32. internal static class Injector
  33. {
  34. private static Task? pluginAsyncLoadTask;
  35. private static Task? permissionFixTask;
  36. //private static string otherNewtonsoftJson = null;
  37. // ReSharper disable once UnusedParameter.Global
  38. internal static void Main(string[] args)
  39. { // entry point for doorstop
  40. // At this point, literally nothing but mscorlib is loaded,
  41. // and since this class doesn't have any static fields that
  42. // aren't defined in mscorlib, we can control exactly what
  43. // gets loaded.
  44. _ = args;
  45. try
  46. {
  47. var arguments = Environment.GetCommandLineArgs();
  48. MaybeInitializeConsole(arguments);
  49. SetupLibraryLoading();
  50. EnsureDirectories();
  51. // this is weird, but it prevents Mono from having issues loading the type.
  52. // IMPORTANT: NO CALLS TO ANY LOGGER CAN HAPPEN BEFORE THIS
  53. var unused = StandardLogger.PrintFilter;
  54. #region // Above hack explanation
  55. /*
  56. * Due to an unknown bug in the version of Mono that Unity uses, if the first access to StandardLogger
  57. * is a call to a constructor, then Mono fails to load the type correctly. However, if the first access is to
  58. * the above static property (or maybe any, but I don't really know) it behaves as expected and works fine.
  59. */
  60. #endregion
  61. Default.Debug("Initializing logger");
  62. SelfConfig.ReadCommandLine(arguments);
  63. SelfConfig.Load();
  64. DisabledConfig.Load();
  65. if (AntiPiracy.IsInvalid(Environment.CurrentDirectory))
  66. {
  67. Default.Error("Invalid installation; please buy the game to run BSIPA.");
  68. return;
  69. }
  70. CriticalSection.Configure();
  71. Logging.Logger.Injector.Debug("Prepping bootstrapper");
  72. // make sure to load the game version and check boundaries before installing the bootstrap, because that uses the game assemblies property
  73. GameVersionEarly.Load();
  74. SelfConfig.Instance.CheckVersionBoundary();
  75. SetOpenXRRuntime(arguments);
  76. // updates backup
  77. InstallBootstrapPatch();
  78. AntiMalwareEngine.Initialize();
  79. Updates.InstallPendingUpdates();
  80. Loader.LibLoader.SetupAssemblyFilenames(true);
  81. pluginAsyncLoadTask = PluginLoader.LoadTask();
  82. permissionFixTask = PermissionFix.FixPermissions(new DirectoryInfo(Environment.CurrentDirectory));
  83. }
  84. catch (Exception e)
  85. {
  86. Console.WriteLine(e);
  87. }
  88. }
  89. public static void SetOpenXRRuntime(string[] arguments)
  90. {
  91. if (arguments == null)
  92. return;
  93. string targetRuntime = string.Empty;
  94. for (int i = 0; i < arguments.Length; i++)
  95. {
  96. if (arguments[i] == "-vrmode" && i + 1 < arguments.Length)
  97. {
  98. targetRuntime = arguments[i + 1];
  99. break;
  100. }
  101. }
  102. if (string.IsNullOrEmpty(targetRuntime))
  103. return;
  104. targetRuntime = targetRuntime.ToLower(System.Globalization.CultureInfo.CurrentCulture);
  105. //This forces the OpenXRLoader to error as there is no OpenXR Runtime found, which is intentional as a mod can then select it
  106. switch (targetRuntime)
  107. {
  108. case "none":
  109. case "fpfc":
  110. case "controllable":
  111. Environment.SetEnvironmentVariable("XR_RUNTIME_JSON", targetRuntime); //By checking the env variable you can see what caused the override while still causing the fail
  112. return;
  113. }
  114. string registryPath = @"SOFTWARE\Khronos\OpenXR\1\AvailableRuntimes";
  115. RegistryKey baseKey = Registry.LocalMachine.OpenSubKey(registryPath);
  116. string foundRuntime = string.Empty;
  117. if (baseKey != null)
  118. {
  119. foreach (string valueName in baseKey.GetValueNames())
  120. {
  121. if (Path.GetFileNameWithoutExtension(valueName).ToLower().Contains(targetRuntime))
  122. {
  123. foundRuntime = valueName;
  124. break;
  125. }
  126. }
  127. baseKey.Close();
  128. }
  129. if(!string.IsNullOrEmpty(foundRuntime))
  130. Environment.SetEnvironmentVariable("XR_RUNTIME_JSON", foundRuntime);
  131. //This is not stored within CommandLineValues.Debug as you can check the environment variable
  132. }
  133. private static void MaybeInitializeConsole(string[] arguments)
  134. {
  135. var i = 0;
  136. while (i < arguments.Length)
  137. {
  138. if (arguments[i++] == "--verbose")
  139. {
  140. if (i == arguments.Length)
  141. {
  142. WinConsole.Initialize(WinConsole.AttachParent);
  143. return;
  144. }
  145. WinConsole.Initialize(int.TryParse(arguments[i], out int processId) ? processId : WinConsole.AttachParent);
  146. return;
  147. }
  148. }
  149. }
  150. private static void EnsureDirectories()
  151. {
  152. string path;
  153. if (!Directory.Exists(path = Path.Combine(Environment.CurrentDirectory, "UserData")))
  154. _ = Directory.CreateDirectory(path);
  155. if (!Directory.Exists(path = Path.Combine(Environment.CurrentDirectory, "Plugins")))
  156. _ = Directory.CreateDirectory(path);
  157. }
  158. private static void SetupLibraryLoading()
  159. {
  160. if (loadingDone) return;
  161. loadingDone = true;
  162. Loader.LibLoader.Configure();
  163. }
  164. private static void InstallBootstrapPatch()
  165. {
  166. var sw = Stopwatch.StartNew();
  167. var cAsmName = Assembly.GetExecutingAssembly().GetName();
  168. var managedPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!;
  169. var dataDir = new DirectoryInfo(managedPath).Parent!.Name;
  170. var gameName = dataDir.Substring(0, dataDir.Length - 5);
  171. Logging.Logger.Injector.Debug("Finding backup");
  172. var backupPath = Path.Combine(Environment.CurrentDirectory, "IPA", "Backups", gameName);
  173. var bkp = BackupManager.FindLatestBackup(backupPath);
  174. if (bkp == null)
  175. Logging.Logger.Injector.Warn("No backup found! Was BSIPA installed using the installer?");
  176. // TODO: Investigate if this ever worked properly.
  177. // this is a critical section because if you exit in here, assembly can die
  178. using var critSec = CriticalSection.ExecuteSection();
  179. var readerParameters = new ReaderParameters
  180. {
  181. ReadWrite = false,
  182. InMemory = true,
  183. ReadingMode = ReadingMode.Immediate
  184. };
  185. Logging.Logger.Injector.Debug("Ensuring patch on UnityEngine.CoreModule exists");
  186. #region Insert patch into UnityEngine.CoreModule.dll
  187. var unityPath = Path.Combine(managedPath, "UnityEngine.CoreModule.dll");
  188. using var unityAsmDef = AssemblyDefinition.ReadAssembly(unityPath, readerParameters);
  189. var unityModDef = unityAsmDef.MainModule;
  190. bool modified = false;
  191. foreach (var asmref in unityModDef.AssemblyReferences)
  192. {
  193. if (asmref.Name == cAsmName.Name)
  194. {
  195. if (asmref.Version != cAsmName.Version)
  196. {
  197. asmref.Version = cAsmName.Version;
  198. modified = true;
  199. }
  200. }
  201. }
  202. var application = unityModDef.GetType("UnityEngine", "Camera");
  203. if (application == null)
  204. {
  205. Logging.Logger.Injector.Critical("UnityEngine.CoreModule doesn't have a definition for UnityEngine.Camera!"
  206. + "Nothing to patch to get ourselves into the Unity run cycle!");
  207. goto endPatchCoreModule;
  208. }
  209. MethodDefinition? cctor = null;
  210. foreach (var m in application.Methods)
  211. if (m.IsRuntimeSpecialName && m.Name == ".cctor")
  212. cctor = m;
  213. var cbs = unityModDef.ImportReference(((Action)CreateBootstrapper).Method);
  214. if (cctor == null)
  215. {
  216. cctor = new MethodDefinition(".cctor",
  217. MethodAttributes.RTSpecialName | MethodAttributes.Static | MethodAttributes.SpecialName,
  218. unityModDef.TypeSystem.Void);
  219. application.Methods.Add(cctor);
  220. modified = true;
  221. var ilp = cctor.Body.GetILProcessor();
  222. ilp.Emit(OpCodes.Call, cbs);
  223. ilp.Emit(OpCodes.Ret);
  224. }
  225. else
  226. {
  227. var ilp = cctor.Body.GetILProcessor();
  228. for (var i = 0; i < Math.Min(2, cctor.Body.Instructions.Count); i++)
  229. {
  230. var ins = cctor.Body.Instructions[i];
  231. switch (i)
  232. {
  233. case 0 when ins.OpCode != OpCodes.Call:
  234. ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs));
  235. modified = true;
  236. break;
  237. case 0:
  238. {
  239. var methodRef = ins.Operand as MethodReference;
  240. if (methodRef?.FullName != cbs.FullName)
  241. {
  242. ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs));
  243. modified = true;
  244. }
  245. break;
  246. }
  247. case 1 when ins.OpCode != OpCodes.Ret:
  248. ilp.Replace(ins, ilp.Create(OpCodes.Ret));
  249. modified = true;
  250. break;
  251. }
  252. }
  253. }
  254. if (modified)
  255. {
  256. string tempFilePath = Path.GetTempFileName();
  257. bkp?.Add(unityPath);
  258. unityAsmDef.Write(tempFilePath);
  259. File.Delete(unityPath);
  260. File.Move(tempFilePath, unityPath);
  261. }
  262. endPatchCoreModule:
  263. #endregion Insert patch into UnityEngine.CoreModule.dll
  264. sw.Stop();
  265. Logging.Logger.Injector.Info($"Installing bootstrapper took {sw.Elapsed}");
  266. }
  267. private static bool bootstrapped;
  268. private static void CreateBootstrapper()
  269. {
  270. if (bootstrapped) return;
  271. bootstrapped = true;
  272. Application.logMessageReceivedThreaded += delegate (string condition, string stackTrace, LogType type)
  273. {
  274. var level = UnityLogRedirector.LogTypeToLevel(type);
  275. UnityLogProvider.UnityLogger.Log(level, $"{condition}");
  276. UnityLogProvider.UnityLogger.Log(level, $"{stackTrace}");
  277. };
  278. StdoutInterceptor.EnsureHarmonyLogging();
  279. // need to reinit streams singe Unity seems to redirect stdout
  280. StdoutInterceptor.RedirectConsole();
  281. AntiYeetPatch.Apply();
  282. var bootstrapper = new GameObject("NonDestructiveBootstrapper").AddComponent<Bootstrapper>();
  283. bootstrapper.Destroyed += Bootstrapper_Destroyed;
  284. }
  285. private static bool loadingDone;
  286. private static void Bootstrapper_Destroyed()
  287. {
  288. // wait for plugins to finish loading
  289. pluginAsyncLoadTask?.Wait();
  290. permissionFixTask?.Wait();
  291. Default.Debug("Plugins loaded");
  292. Default.Debug(string.Join(", ", PluginLoader.PluginsMetadata.StrJP()));
  293. _ = PluginComponent.Create();
  294. }
  295. }
  296. }