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.

338 lines
13 KiB

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