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.

355 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.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 cmd = Environment.GetCommandLineArgs();
  47. if (cmd.Contains("--verbose"))
  48. {
  49. var arg = string.Empty;
  50. for (var i = 0; i < cmd.Length; i++)
  51. {
  52. if (cmd[i] == "-pid" && cmd.Length > i + 1)
  53. {
  54. arg = cmd[i + 1];
  55. break;
  56. }
  57. }
  58. WinConsole.Initialize(uint.TryParse(arg, out uint pid) ? pid : WinConsole.AttachParent);
  59. }
  60. SetupLibraryLoading();
  61. EnsureDirectories();
  62. // this is weird, but it prevents Mono from having issues loading the type.
  63. // IMPORTANT: NO CALLS TO ANY LOGGER CAN HAPPEN BEFORE THIS
  64. var unused = StandardLogger.PrintFilter;
  65. #region // Above hack explaination
  66. /*
  67. * Due to an unknown bug in the version of Mono that Unity uses, if the first access to StandardLogger
  68. * is a call to a constructor, then Mono fails to load the type correctly. However, if the first access is to
  69. * the above static property (or maybe any, but I don't really know) it behaves as expected and works fine.
  70. */
  71. #endregion
  72. Default.Debug("Initializing logger");
  73. SelfConfig.ReadCommandLine(Environment.GetCommandLineArgs());
  74. SelfConfig.Load();
  75. DisabledConfig.Load();
  76. if (AntiPiracy.IsInvalid(Environment.CurrentDirectory))
  77. {
  78. Default.Error("Invalid installation; please buy the game to run BSIPA.");
  79. return;
  80. }
  81. CriticalSection.Configure();
  82. Logging.Logger.Injector.Debug("Prepping bootstrapper");
  83. // make sure to load the game version and check boundaries before installing the bootstrap, because that uses the game assemblies property
  84. GameVersionEarly.Load();
  85. SelfConfig.Instance.CheckVersionBoundary();
  86. // updates backup
  87. InstallBootstrapPatch();
  88. AntiMalwareEngine.Initialize();
  89. Updates.InstallPendingUpdates();
  90. Loader.LibLoader.SetupAssemblyFilenames(true);
  91. pluginAsyncLoadTask = PluginLoader.LoadTask();
  92. permissionFixTask = PermissionFix.FixPermissions(new DirectoryInfo(Environment.CurrentDirectory));
  93. }
  94. catch (Exception e)
  95. {
  96. Console.WriteLine(e);
  97. }
  98. }
  99. private static void EnsureDirectories()
  100. {
  101. string path;
  102. if (!Directory.Exists(path = Path.Combine(Environment.CurrentDirectory, "UserData")))
  103. _ = Directory.CreateDirectory(path);
  104. if (!Directory.Exists(path = Path.Combine(Environment.CurrentDirectory, "Plugins")))
  105. _ = Directory.CreateDirectory(path);
  106. }
  107. private static void SetupLibraryLoading()
  108. {
  109. if (loadingDone) return;
  110. loadingDone = true;
  111. Loader.LibLoader.Configure();
  112. }
  113. private static void InstallHarmonyProtections()
  114. { // proxy function to delay resolution
  115. HarmonyProtectorProxy.ProtectNull();
  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. Logging.Logger.Injector.Debug("Ensuring patch on UnityEngine.CoreModule exists");
  130. #region Insert patch into UnityEngine.CoreModule.dll
  131. {
  132. var unityPath = Path.Combine(managedPath,
  133. "UnityEngine.CoreModule.dll");
  134. // this is a critical section because if you exit in here, CoreModule can die
  135. using var critSec = CriticalSection.ExecuteSection();
  136. using var unityAsmDef = AssemblyDefinition.ReadAssembly(unityPath, new ReaderParameters
  137. {
  138. ReadWrite = false,
  139. InMemory = true,
  140. ReadingMode = ReadingMode.Immediate
  141. });
  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. bkp?.Add(unityPath);
  210. unityAsmDef.Write(unityPath);
  211. }
  212. }
  213. endPatchCoreModule:
  214. #endregion Insert patch into UnityEngine.CoreModule.dll
  215. Logging.Logger.Injector.Debug("Ensuring game assemblies are virtualized");
  216. #region Virtualize game assemblies
  217. bool isFirst = true;
  218. foreach (var name in SelfConfig.GameAssemblies_)
  219. {
  220. var ascPath = Path.Combine(managedPath, name);
  221. using var execSec = CriticalSection.ExecuteSection();
  222. try
  223. {
  224. Logging.Logger.Injector.Debug($"Virtualizing {name}");
  225. using var ascModule = VirtualizedModule.Load(ascPath);
  226. ascModule.Virtualize(cAsmName, () => bkp?.Add(ascPath));
  227. }
  228. catch (Exception e)
  229. {
  230. Logging.Logger.Injector.Error($"Could not virtualize {ascPath}");
  231. if (SelfConfig.Debug_.ShowHandledErrorStackTraces_)
  232. Logging.Logger.Injector.Error(e);
  233. }
  234. #if BeatSaber
  235. if (isFirst)
  236. {
  237. try
  238. {
  239. Logging.Logger.Injector.Debug("Applying anti-yeet patch");
  240. using var ascAsmDef = AssemblyDefinition.ReadAssembly(ascPath, new ReaderParameters
  241. {
  242. ReadWrite = false,
  243. InMemory = true,
  244. ReadingMode = ReadingMode.Immediate
  245. });
  246. var ascModDef = ascAsmDef.MainModule;
  247. var deleter = ascModDef.GetType("IPAPluginsDirDeleter");
  248. deleter.Methods.Clear(); // delete all methods
  249. ascAsmDef.Write(ascPath);
  250. isFirst = false;
  251. }
  252. catch (Exception e)
  253. {
  254. Logging.Logger.Injector.Warn($"Could not apply anti-yeet patch to {ascPath}");
  255. if (SelfConfig.Debug_.ShowHandledErrorStackTraces_)
  256. Logging.Logger.Injector.Warn(e);
  257. }
  258. }
  259. #endif
  260. }
  261. #endregion
  262. sw.Stop();
  263. Logging.Logger.Injector.Info($"Installing bootstrapper took {sw.Elapsed}");
  264. }
  265. private static bool bootstrapped;
  266. private static void CreateBootstrapper()
  267. {
  268. if (bootstrapped) return;
  269. bootstrapped = true;
  270. Application.logMessageReceived += delegate (string condition, string stackTrace, LogType type)
  271. {
  272. var level = UnityLogRedirector.LogTypeToLevel(type);
  273. UnityLogProvider.UnityLogger.Log(level, $"{condition}");
  274. UnityLogProvider.UnityLogger.Log(level, $"{stackTrace}");
  275. };
  276. StdoutInterceptor.EnsureHarmonyLogging();
  277. // need to reinit streams singe Unity seems to redirect stdout
  278. StdoutInterceptor.RedirectConsole();
  279. InstallHarmonyProtections();
  280. var bootstrapper = new GameObject("NonDestructiveBootstrapper").AddComponent<Bootstrapper>();
  281. bootstrapper.Destroyed += Bootstrapper_Destroyed;
  282. }
  283. private static bool loadingDone;
  284. private static void Bootstrapper_Destroyed()
  285. {
  286. // wait for plugins to finish loading
  287. pluginAsyncLoadTask?.Wait();
  288. permissionFixTask?.Wait();
  289. Default.Debug("Plugins loaded");
  290. Default.Debug(string.Join(", ", PluginLoader.PluginsMetadata.StrJP()));
  291. _ = PluginComponent.Create();
  292. }
  293. }
  294. }