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.

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