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.

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