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.

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