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.

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