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.

362 lines
14 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 Mono.Cecil;
  9. using Mono.Cecil.Cil;
  10. using System;
  11. using System.Collections.Generic;
  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. if (Environment.GetCommandLineArgs().Contains("--verbose"))
  48. WinConsole.Initialize();
  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 explaination
  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(Environment.GetCommandLineArgs());
  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. // updates backup
  76. InstallBootstrapPatch();
  77. AntiMalwareEngine.Initialize();
  78. Updates.InstallPendingUpdates();
  79. Loader.LibLoader.SetupAssemblyFilenames(true);
  80. pluginAsyncLoadTask = PluginLoader.LoadTask();
  81. permissionFixTask = PermissionFix.FixPermissions(new DirectoryInfo(Environment.CurrentDirectory));
  82. }
  83. catch (Exception e)
  84. {
  85. Console.WriteLine(e);
  86. }
  87. }
  88. private static void EnsureDirectories()
  89. {
  90. string path;
  91. if (!Directory.Exists(path = Path.Combine(Environment.CurrentDirectory, "UserData")))
  92. _ = Directory.CreateDirectory(path);
  93. if (!Directory.Exists(path = Path.Combine(Environment.CurrentDirectory, "Plugins")))
  94. _ = Directory.CreateDirectory(path);
  95. }
  96. private static void SetupLibraryLoading()
  97. {
  98. if (loadingDone) return;
  99. loadingDone = true;
  100. Loader.LibLoader.Configure();
  101. }
  102. private static void InstallHarmonyProtections()
  103. { // proxy function to delay resolution
  104. HarmonyProtectorProxy.ProtectNull();
  105. }
  106. private static void InstallBootstrapPatch()
  107. {
  108. var sw = Stopwatch.StartNew();
  109. var cAsmName = Assembly.GetExecutingAssembly().GetName();
  110. var managedPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
  111. var dataDir = new DirectoryInfo(managedPath).Parent.Name;
  112. var gameName = dataDir.Substring(0, dataDir.Length - 5);
  113. Logging.Logger.Injector.Debug("Finding backup");
  114. var backupPath = Path.Combine(Environment.CurrentDirectory, "IPA", "Backups", gameName);
  115. var bkp = BackupManager.FindLatestBackup(backupPath);
  116. if (bkp == null)
  117. Logging.Logger.Injector.Warn("No backup found! Was BSIPA installed using the installer?");
  118. Logging.Logger.Injector.Debug("Ensuring patch on UnityEngine.CoreModule exists");
  119. #region Insert patch into UnityEngine.CoreModule.dll
  120. {
  121. var unityPath = Path.Combine(managedPath,
  122. "UnityEngine.CoreModule.dll");
  123. // this is a critical section because if you exit in here, CoreModule can die
  124. using var critSec = CriticalSection.ExecuteSection();
  125. using var unityAsmDef = AssemblyDefinition.ReadAssembly(unityPath, new ReaderParameters
  126. {
  127. ReadWrite = false,
  128. InMemory = true,
  129. ReadingMode = ReadingMode.Immediate
  130. });
  131. var unityModDef = unityAsmDef.MainModule;
  132. bool modified = false;
  133. foreach (var asmref in unityModDef.AssemblyReferences)
  134. {
  135. if (asmref.Name == cAsmName.Name)
  136. {
  137. if (asmref.Version != cAsmName.Version)
  138. {
  139. asmref.Version = cAsmName.Version;
  140. modified = true;
  141. }
  142. }
  143. }
  144. var application = unityModDef.GetType("UnityEngine", "Camera");
  145. if (application == null)
  146. {
  147. Logging.Logger.Injector.Critical("UnityEngine.CoreModule doesn't have a definition for UnityEngine.Camera!"
  148. + "Nothing to patch to get ourselves into the Unity run cycle!");
  149. goto endPatchCoreModule;
  150. }
  151. MethodDefinition? cctor = null;
  152. foreach (var m in application.Methods)
  153. if (m.IsRuntimeSpecialName && m.Name == ".cctor")
  154. cctor = m;
  155. var cbs = unityModDef.ImportReference(((Action)CreateBootstrapper).Method);
  156. if (cctor == null)
  157. {
  158. cctor = new MethodDefinition(".cctor",
  159. MethodAttributes.RTSpecialName | MethodAttributes.Static | MethodAttributes.SpecialName,
  160. unityModDef.TypeSystem.Void);
  161. application.Methods.Add(cctor);
  162. modified = true;
  163. var ilp = cctor.Body.GetILProcessor();
  164. ilp.Emit(OpCodes.Call, cbs);
  165. ilp.Emit(OpCodes.Ret);
  166. }
  167. else
  168. {
  169. var ilp = cctor.Body.GetILProcessor();
  170. for (var i = 0; i < Math.Min(2, cctor.Body.Instructions.Count); i++)
  171. {
  172. var ins = cctor.Body.Instructions[i];
  173. switch (i)
  174. {
  175. case 0 when ins.OpCode != OpCodes.Call:
  176. ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs));
  177. modified = true;
  178. break;
  179. case 0:
  180. {
  181. var methodRef = ins.Operand as MethodReference;
  182. if (methodRef?.FullName != cbs.FullName)
  183. {
  184. ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs));
  185. modified = true;
  186. }
  187. break;
  188. }
  189. case 1 when ins.OpCode != OpCodes.Ret:
  190. ilp.Replace(ins, ilp.Create(OpCodes.Ret));
  191. modified = true;
  192. break;
  193. }
  194. }
  195. }
  196. if (modified)
  197. {
  198. bkp?.Add(unityPath);
  199. unityAsmDef.Write(unityPath);
  200. }
  201. }
  202. endPatchCoreModule:
  203. #endregion Insert patch into UnityEngine.CoreModule.dll
  204. Logging.Logger.Injector.Debug("Ensuring game assemblies are virtualized");
  205. #region Virtualize game assemblies
  206. bool isFirst = true;
  207. var modifiedMethods = new Dictionary<string, MethodReference>();
  208. List<VirtualizedModule> modules = SelfConfig.GameAssemblies_.Select(ga => VirtualizedModule.Load(Path.Combine(managedPath, ga))).ToList();
  209. foreach (var ascModule in modules)
  210. {
  211. using var execSec = CriticalSection.ExecuteSection();
  212. var ascPath = Path.Combine(managedPath, ascModule.FileName);
  213. try
  214. {
  215. Logging.Logger.Injector.Debug($"Virtualizing {ascModule.FileName}");
  216. ascModule.Virtualize(cAsmName, modifiedMethods);
  217. }
  218. catch (Exception e)
  219. {
  220. Logging.Logger.Injector.Error($"Could not virtualize {ascPath}");
  221. if (SelfConfig.Debug_.ShowHandledErrorStackTraces_)
  222. Logging.Logger.Injector.Error(e);
  223. }
  224. #if BeatSaber
  225. if (isFirst)
  226. {
  227. try
  228. {
  229. Logging.Logger.Injector.Debug("Applying anti-yeet patch");
  230. var deleter = ascModule.GetType("IPAPluginsDirDeleter");
  231. deleter.Methods.Clear(); // delete all methods
  232. isFirst = false;
  233. }
  234. catch (Exception e)
  235. {
  236. Logging.Logger.Injector.Warn($"Could not apply anti-yeet patch to {ascPath}");
  237. if (SelfConfig.Debug_.ShowHandledErrorStackTraces_)
  238. Logging.Logger.Injector.Warn(e);
  239. }
  240. }
  241. #endif
  242. }
  243. // if a virtualized method has a modreq added to it and it is referenced by
  244. // another assembly, we need to update the method reference in the other assembly
  245. foreach (var ascModule in modules)
  246. {
  247. using var execSec = CriticalSection.ExecuteSection();
  248. var ascPath = Path.Combine(managedPath, ascModule.FileName);
  249. try
  250. {
  251. Logging.Logger.Injector.Debug($"Fixing references in {ascModule.FileName}");
  252. ascModule.FixReferences(modifiedMethods);
  253. if (ascModule.Changed)
  254. {
  255. bkp?.Add(ascPath);
  256. ascModule.Write(ascPath);
  257. }
  258. }
  259. catch (Exception e)
  260. {
  261. Logging.Logger.Injector.Error($"Could not fix references in {ascPath}");
  262. if (SelfConfig.Debug_.ShowHandledErrorStackTraces_)
  263. Logging.Logger.Injector.Error(e);
  264. }
  265. finally
  266. {
  267. ascModule.Dispose();
  268. }
  269. }
  270. #endregion
  271. sw.Stop();
  272. Logging.Logger.Injector.Info($"Installing bootstrapper took {sw.Elapsed}");
  273. }
  274. private static bool bootstrapped;
  275. private static void CreateBootstrapper()
  276. {
  277. if (bootstrapped) return;
  278. bootstrapped = true;
  279. Application.logMessageReceived += delegate (string condition, string stackTrace, LogType type)
  280. {
  281. var level = UnityLogRedirector.LogTypeToLevel(type);
  282. UnityLogProvider.UnityLogger.Log(level, $"{condition}");
  283. UnityLogProvider.UnityLogger.Log(level, $"{stackTrace}");
  284. };
  285. StdoutInterceptor.EnsureHarmonyLogging();
  286. // need to reinit streams singe Unity seems to redirect stdout
  287. StdoutInterceptor.RedirectConsole();
  288. InstallHarmonyProtections();
  289. var bootstrapper = new GameObject("NonDestructiveBootstrapper").AddComponent<Bootstrapper>();
  290. bootstrapper.Destroyed += Bootstrapper_Destroyed;
  291. }
  292. private static bool loadingDone;
  293. private static void Bootstrapper_Destroyed()
  294. {
  295. // wait for plugins to finish loading
  296. pluginAsyncLoadTask?.Wait();
  297. permissionFixTask?.Wait();
  298. Default.Debug("Plugins loaded");
  299. Default.Debug(string.Join(", ", PluginLoader.PluginsMetadata.StrJP()));
  300. _ = PluginComponent.Create();
  301. }
  302. }
  303. }