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.

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