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.

358 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 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 var processId) ? processId : WinConsole.AttachParent);
  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 InstallHarmonyProtections()
  118. { // proxy function to delay resolution
  119. HarmonyProtectorProxy.ProtectNull();
  120. }
  121. private static void InstallBootstrapPatch()
  122. {
  123. var sw = Stopwatch.StartNew();
  124. var cAsmName = Assembly.GetExecutingAssembly().GetName();
  125. var managedPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
  126. var dataDir = new DirectoryInfo(managedPath).Parent.Name;
  127. var gameName = dataDir.Substring(0, dataDir.Length - 5);
  128. Logging.Logger.Injector.Debug("Finding backup");
  129. var backupPath = Path.Combine(Environment.CurrentDirectory, "IPA", "Backups", gameName);
  130. var bkp = BackupManager.FindLatestBackup(backupPath);
  131. if (bkp == null)
  132. Logging.Logger.Injector.Warn("No backup found! Was BSIPA installed using the installer?");
  133. Logging.Logger.Injector.Debug("Ensuring patch on UnityEngine.CoreModule exists");
  134. #region Insert patch into UnityEngine.CoreModule.dll
  135. {
  136. var unityPath = Path.Combine(managedPath,
  137. "UnityEngine.CoreModule.dll");
  138. // this is a critical section because if you exit in here, CoreModule can die
  139. using var critSec = CriticalSection.ExecuteSection();
  140. using var unityAsmDef = AssemblyDefinition.ReadAssembly(unityPath, new ReaderParameters
  141. {
  142. ReadWrite = false,
  143. InMemory = true,
  144. ReadingMode = ReadingMode.Immediate
  145. });
  146. var unityModDef = unityAsmDef.MainModule;
  147. bool modified = false;
  148. foreach (var asmref in unityModDef.AssemblyReferences)
  149. {
  150. if (asmref.Name == cAsmName.Name)
  151. {
  152. if (asmref.Version != cAsmName.Version)
  153. {
  154. asmref.Version = cAsmName.Version;
  155. modified = true;
  156. }
  157. }
  158. }
  159. var application = unityModDef.GetType("UnityEngine", "Camera");
  160. if (application == null)
  161. {
  162. Logging.Logger.Injector.Critical("UnityEngine.CoreModule doesn't have a definition for UnityEngine.Camera!"
  163. + "Nothing to patch to get ourselves into the Unity run cycle!");
  164. goto endPatchCoreModule;
  165. }
  166. MethodDefinition? cctor = null;
  167. foreach (var m in application.Methods)
  168. if (m.IsRuntimeSpecialName && m.Name == ".cctor")
  169. cctor = m;
  170. var cbs = unityModDef.ImportReference(((Action)CreateBootstrapper).Method);
  171. if (cctor == null)
  172. {
  173. cctor = new MethodDefinition(".cctor",
  174. MethodAttributes.RTSpecialName | MethodAttributes.Static | MethodAttributes.SpecialName,
  175. unityModDef.TypeSystem.Void);
  176. application.Methods.Add(cctor);
  177. modified = true;
  178. var ilp = cctor.Body.GetILProcessor();
  179. ilp.Emit(OpCodes.Call, cbs);
  180. ilp.Emit(OpCodes.Ret);
  181. }
  182. else
  183. {
  184. var ilp = cctor.Body.GetILProcessor();
  185. for (var i = 0; i < Math.Min(2, cctor.Body.Instructions.Count); i++)
  186. {
  187. var ins = cctor.Body.Instructions[i];
  188. switch (i)
  189. {
  190. case 0 when ins.OpCode != OpCodes.Call:
  191. ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs));
  192. modified = true;
  193. break;
  194. case 0:
  195. {
  196. var methodRef = ins.Operand as MethodReference;
  197. if (methodRef?.FullName != cbs.FullName)
  198. {
  199. ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs));
  200. modified = true;
  201. }
  202. break;
  203. }
  204. case 1 when ins.OpCode != OpCodes.Ret:
  205. ilp.Replace(ins, ilp.Create(OpCodes.Ret));
  206. modified = true;
  207. break;
  208. }
  209. }
  210. }
  211. if (modified)
  212. {
  213. bkp?.Add(unityPath);
  214. unityAsmDef.Write(unityPath);
  215. }
  216. }
  217. endPatchCoreModule:
  218. #endregion Insert patch into UnityEngine.CoreModule.dll
  219. Logging.Logger.Injector.Debug("Ensuring game assemblies are virtualized");
  220. #region Virtualize game assemblies
  221. bool isFirst = true;
  222. foreach (var name in SelfConfig.GameAssemblies_)
  223. {
  224. var ascPath = Path.Combine(managedPath, name);
  225. using var execSec = CriticalSection.ExecuteSection();
  226. try
  227. {
  228. Logging.Logger.Injector.Debug($"Virtualizing {name}");
  229. using var ascModule = VirtualizedModule.Load(ascPath);
  230. ascModule.Virtualize(cAsmName, () => bkp?.Add(ascPath));
  231. }
  232. catch (Exception e)
  233. {
  234. Logging.Logger.Injector.Error($"Could not virtualize {ascPath}");
  235. if (SelfConfig.Debug_.ShowHandledErrorStackTraces_)
  236. Logging.Logger.Injector.Error(e);
  237. }
  238. #if BeatSaber
  239. if (isFirst)
  240. {
  241. try
  242. {
  243. Logging.Logger.Injector.Debug("Applying anti-yeet patch");
  244. using var ascAsmDef = AssemblyDefinition.ReadAssembly(ascPath, new ReaderParameters
  245. {
  246. ReadWrite = false,
  247. InMemory = true,
  248. ReadingMode = ReadingMode.Immediate
  249. });
  250. var ascModDef = ascAsmDef.MainModule;
  251. var deleter = ascModDef.GetType("IPAPluginsDirDeleter");
  252. deleter.Methods.Clear(); // delete all methods
  253. ascAsmDef.Write(ascPath);
  254. isFirst = false;
  255. }
  256. catch (Exception e)
  257. {
  258. Logging.Logger.Injector.Warn($"Could not apply anti-yeet patch to {ascPath}");
  259. if (SelfConfig.Debug_.ShowHandledErrorStackTraces_)
  260. Logging.Logger.Injector.Warn(e);
  261. }
  262. }
  263. #endif
  264. }
  265. #endregion
  266. sw.Stop();
  267. Logging.Logger.Injector.Info($"Installing bootstrapper took {sw.Elapsed}");
  268. }
  269. private static bool bootstrapped;
  270. private static void CreateBootstrapper()
  271. {
  272. if (bootstrapped) return;
  273. bootstrapped = true;
  274. Application.logMessageReceived += delegate (string condition, string stackTrace, LogType type)
  275. {
  276. var level = UnityLogRedirector.LogTypeToLevel(type);
  277. UnityLogProvider.UnityLogger.Log(level, $"{condition}");
  278. UnityLogProvider.UnityLogger.Log(level, $"{stackTrace}");
  279. };
  280. StdoutInterceptor.EnsureHarmonyLogging();
  281. // need to reinit streams singe Unity seems to redirect stdout
  282. StdoutInterceptor.RedirectConsole();
  283. InstallHarmonyProtections();
  284. var bootstrapper = new GameObject("NonDestructiveBootstrapper").AddComponent<Bootstrapper>();
  285. bootstrapper.Destroyed += Bootstrapper_Destroyed;
  286. }
  287. private static bool loadingDone;
  288. private static void Bootstrapper_Destroyed()
  289. {
  290. // wait for plugins to finish loading
  291. pluginAsyncLoadTask?.Wait();
  292. permissionFixTask?.Wait();
  293. Default.Debug("Plugins loaded");
  294. Default.Debug(string.Join(", ", PluginLoader.PluginsMetadata.StrJP()));
  295. _ = PluginComponent.Create();
  296. }
  297. }
  298. }