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.

334 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. //private static string otherNewtonsoftJson = null;
  36. public static Assembly ExecutingAssembly => typeof(Injector).Assembly;
  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. // 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 MaybeInitializeConsole(string[] arguments)
  89. {
  90. var i = 0;
  91. while (i < arguments.Length)
  92. {
  93. if (arguments[i++] == "--verbose")
  94. {
  95. if (i == arguments.Length)
  96. {
  97. WinConsole.Initialize(WinConsole.AttachParent);
  98. return;
  99. }
  100. WinConsole.Initialize(int.TryParse(arguments[i], out int processId) ? processId : WinConsole.AttachParent);
  101. return;
  102. }
  103. }
  104. }
  105. private static void EnsureDirectories()
  106. {
  107. string path;
  108. if (!Directory.Exists(path = Path.Combine(Environment.CurrentDirectory, "UserData")))
  109. _ = Directory.CreateDirectory(path);
  110. if (!Directory.Exists(path = Path.Combine(Environment.CurrentDirectory, "Plugins")))
  111. _ = Directory.CreateDirectory(path);
  112. }
  113. private static void SetupLibraryLoading()
  114. {
  115. if (loadingDone) return;
  116. loadingDone = true;
  117. Loader.LibLoader.Configure();
  118. }
  119. private static void InstallBootstrapPatch()
  120. {
  121. var sw = Stopwatch.StartNew();
  122. var cAsmName = ExecutingAssembly.GetName();
  123. var managedPath = Path.GetDirectoryName(ExecutingAssembly.Location)!;
  124. var dataDir = new DirectoryInfo(managedPath).Parent!.Name;
  125. var gameName = dataDir.Substring(0, dataDir.Length - 5);
  126. Logging.Logger.Injector.Debug("Finding backup");
  127. var backupPath = Path.Combine(Environment.CurrentDirectory, "IPA", "Backups", gameName);
  128. var bkp = BackupManager.FindLatestBackup(backupPath);
  129. if (bkp == null)
  130. Logging.Logger.Injector.Warn("No backup found! Was BSIPA installed using the installer?");
  131. // TODO: Investigate if this ever worked properly.
  132. // this is a critical section because if you exit in here, assembly can die
  133. using var critSec = CriticalSection.ExecuteSection();
  134. var readerParameters = new ReaderParameters
  135. {
  136. ReadWrite = false,
  137. InMemory = true,
  138. ReadingMode = ReadingMode.Immediate
  139. };
  140. Logging.Logger.Injector.Debug("Ensuring patch on UnityEngine.CoreModule exists");
  141. #region Insert patch into UnityEngine.CoreModule.dll
  142. var unityPath = Path.Combine(managedPath, "UnityEngine.CoreModule.dll");
  143. using var unityAsmDef = AssemblyDefinition.ReadAssembly(unityPath, readerParameters);
  144. var unityModDef = unityAsmDef.MainModule;
  145. bool modified = false;
  146. foreach (var asmref in unityModDef.AssemblyReferences)
  147. {
  148. if (asmref.Name == cAsmName.Name)
  149. {
  150. if (asmref.Version != cAsmName.Version)
  151. {
  152. asmref.Version = cAsmName.Version;
  153. modified = true;
  154. }
  155. }
  156. }
  157. var application = unityModDef.GetType("UnityEngine", "Camera");
  158. if (application == null)
  159. {
  160. Logging.Logger.Injector.Critical("UnityEngine.CoreModule doesn't have a definition for UnityEngine.Camera!"
  161. + "Nothing to patch to get ourselves into the Unity run cycle!");
  162. goto endPatchCoreModule;
  163. }
  164. MethodDefinition? cctor = null;
  165. foreach (var m in application.Methods)
  166. if (m.IsRuntimeSpecialName && m.Name == ".cctor")
  167. cctor = m;
  168. var cbs = unityModDef.ImportReference(((Action)CreateBootstrapper).Method);
  169. if (cctor == null)
  170. {
  171. cctor = new MethodDefinition(".cctor",
  172. MethodAttributes.RTSpecialName | MethodAttributes.Static | MethodAttributes.SpecialName,
  173. unityModDef.TypeSystem.Void);
  174. application.Methods.Add(cctor);
  175. modified = true;
  176. var ilp = cctor.Body.GetILProcessor();
  177. ilp.Emit(OpCodes.Call, cbs);
  178. ilp.Emit(OpCodes.Ret);
  179. }
  180. else
  181. {
  182. var ilp = cctor.Body.GetILProcessor();
  183. for (var i = 0; i < Math.Min(2, cctor.Body.Instructions.Count); i++)
  184. {
  185. var ins = cctor.Body.Instructions[i];
  186. switch (i)
  187. {
  188. case 0 when ins.OpCode != OpCodes.Call:
  189. ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs));
  190. modified = true;
  191. break;
  192. case 0:
  193. {
  194. var methodRef = ins.Operand as MethodReference;
  195. if (methodRef?.FullName != cbs.FullName)
  196. {
  197. ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs));
  198. modified = true;
  199. }
  200. break;
  201. }
  202. case 1 when ins.OpCode != OpCodes.Ret:
  203. ilp.Replace(ins, ilp.Create(OpCodes.Ret));
  204. modified = true;
  205. break;
  206. }
  207. }
  208. }
  209. if (modified)
  210. {
  211. string tempFilePath = Path.GetTempFileName();
  212. bkp?.Add(unityPath);
  213. unityAsmDef.Write(tempFilePath);
  214. File.Delete(unityPath);
  215. File.Move(tempFilePath, unityPath);
  216. }
  217. endPatchCoreModule:
  218. #endregion Insert patch into UnityEngine.CoreModule.dll
  219. #if BeatSaber
  220. Logging.Logger.Injector.Debug("Ensuring anti-yeet patch exists");
  221. var name = SelfConfig.GameAssemblies_.FirstOrDefault() ?? SelfConfig.GetDefaultGameAssemblies().First();
  222. var ascPath = Path.Combine(managedPath, name);
  223. try
  224. {
  225. using var ascAsmDef = AssemblyDefinition.ReadAssembly(ascPath, readerParameters);
  226. var ascModDef = ascAsmDef.MainModule;
  227. var deleter = ascModDef.GetType("IPAPluginsDirDeleter");
  228. if (deleter.Methods.Count > 0)
  229. {
  230. deleter.Methods.Clear(); // delete all methods
  231. string tempFilePath = Path.GetTempFileName();
  232. bkp?.Add(ascPath);
  233. ascAsmDef.Write(tempFilePath);
  234. File.Delete(ascPath);
  235. File.Move(tempFilePath, ascPath);
  236. }
  237. }
  238. catch (Exception e)
  239. {
  240. Logging.Logger.Injector.Warn($"Could not apply anti-yeet patch to {ascPath}");
  241. if (SelfConfig.Debug_.ShowHandledErrorStackTraces_)
  242. Logging.Logger.Injector.Warn(e);
  243. }
  244. #endif
  245. sw.Stop();
  246. Logging.Logger.Injector.Info($"Installing bootstrapper took {sw.Elapsed}");
  247. }
  248. private static bool bootstrapped;
  249. private static void CreateBootstrapper()
  250. {
  251. if (bootstrapped) return;
  252. bootstrapped = true;
  253. Application.logMessageReceivedThreaded += delegate (string condition, string stackTrace, LogType type)
  254. {
  255. var level = UnityLogRedirector.LogTypeToLevel(type);
  256. UnityLogProvider.UnityLogger.Log(level, $"{condition}");
  257. UnityLogProvider.UnityLogger.Log(level, $"{stackTrace}");
  258. };
  259. StdoutInterceptor.EnsureHarmonyLogging();
  260. // need to reinit streams singe Unity seems to redirect stdout
  261. StdoutInterceptor.RedirectConsole();
  262. var bootstrapper = new GameObject("NonDestructiveBootstrapper").AddComponent<Bootstrapper>();
  263. bootstrapper.Destroyed += Bootstrapper_Destroyed;
  264. }
  265. private static bool loadingDone;
  266. private static void Bootstrapper_Destroyed()
  267. {
  268. // wait for plugins to finish loading
  269. pluginAsyncLoadTask?.Wait();
  270. permissionFixTask?.Wait();
  271. Default.Debug("Plugins loaded");
  272. Default.Debug(string.Join(", ", PluginLoader.PluginsMetadata.StrJP()));
  273. _ = PluginComponent.Create();
  274. }
  275. }
  276. }