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.

210 lines
7.4 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. using IPA.Config;
  2. using IPA.Injector.Backups;
  3. using IPA.Loader;
  4. using IPA.Logging;
  5. using Mono.Cecil;
  6. using Mono.Cecil.Cil;
  7. using System;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Reflection;
  11. using System.Threading.Tasks;
  12. using UnityEngine;
  13. using static IPA.Logging.Logger;
  14. using MethodAttributes = Mono.Cecil.MethodAttributes;
  15. namespace IPA.Injector
  16. {
  17. // ReSharper disable once UnusedMember.Global
  18. public static class Injector
  19. {
  20. private static Task pluginAsyncLoadTask;
  21. // ReSharper disable once UnusedParameter.Global
  22. public static void Main(string[] args)
  23. { // entry point for doorstop
  24. // At this point, literally nothing but mscorlib is loaded,
  25. // and since this class doesn't have any static fields that
  26. // aren't defined in mscorlib, we can control exactly what
  27. // gets loaded.
  28. try
  29. {
  30. if (!Environment.GetCommandLineArgs().Contains("--no-console"))
  31. WinConsole.Initialize();
  32. SetupLibraryLoading();
  33. log.Debug("Initializing logger");
  34. SelfConfig.Set();
  35. loader.Debug("Prepping bootstrapper");
  36. InstallBootstrapPatch();
  37. Updates.InstallPendingUpdates();
  38. pluginAsyncLoadTask = PluginLoader.LoadTask();
  39. }
  40. catch (Exception e)
  41. {
  42. Console.WriteLine(e);
  43. }
  44. }
  45. private static void SetupLibraryLoading()
  46. {
  47. if (loadingDone) return;
  48. loadingDone = true;
  49. AppDomain.CurrentDomain.AssemblyResolve += LibLoader.AssemblyLibLoader;
  50. }
  51. private static void InstallBootstrapPatch()
  52. {
  53. var cAsmName = Assembly.GetExecutingAssembly().GetName();
  54. loader.Debug("Finding backup");
  55. var backupPath = Path.Combine(Environment.CurrentDirectory, "IPA", "Backups", "Beat Saber");
  56. var bkp = BackupManager.FindLatestBackup(backupPath);
  57. if (bkp == null)
  58. loader.Warn("No backup found! Was BSIPA installed using the installer?");
  59. loader.Debug("Ensuring patch on UnityEngine.CoreModule exists");
  60. #region Insert patch into UnityEngine.CoreModule.dll
  61. {
  62. var unityPath = Path.Combine(Environment.CurrentDirectory, "Beat Saber_Data", "Managed",
  63. "UnityEngine.CoreModule.dll");
  64. var unityAsmDef = AssemblyDefinition.ReadAssembly(unityPath, new ReaderParameters
  65. {
  66. ReadWrite = false,
  67. InMemory = true,
  68. ReadingMode = ReadingMode.Immediate
  69. });
  70. var unityModDef = unityAsmDef.MainModule;
  71. bool modified = false;
  72. foreach (var asmref in unityModDef.AssemblyReferences)
  73. {
  74. if (asmref.Name == cAsmName.Name)
  75. {
  76. if (asmref.Version != cAsmName.Version)
  77. {
  78. asmref.Version = cAsmName.Version;
  79. modified = true;
  80. }
  81. }
  82. }
  83. var application = unityModDef.GetType("UnityEngine", "Application");
  84. MethodDefinition cctor = null;
  85. foreach (var m in application.Methods)
  86. if (m.IsRuntimeSpecialName && m.Name == ".cctor")
  87. cctor = m;
  88. var cbs = unityModDef.ImportReference(((Action)CreateBootstrapper).Method);
  89. if (cctor == null)
  90. {
  91. cctor = new MethodDefinition(".cctor",
  92. MethodAttributes.RTSpecialName | MethodAttributes.Static | MethodAttributes.SpecialName,
  93. unityModDef.TypeSystem.Void);
  94. application.Methods.Add(cctor);
  95. modified = true;
  96. var ilp = cctor.Body.GetILProcessor();
  97. ilp.Emit(OpCodes.Call, cbs);
  98. ilp.Emit(OpCodes.Ret);
  99. }
  100. else
  101. {
  102. var ilp = cctor.Body.GetILProcessor();
  103. for (var i = 0; i < Math.Min(2, cctor.Body.Instructions.Count); i++)
  104. {
  105. var ins = cctor.Body.Instructions[i];
  106. switch (i)
  107. {
  108. case 0 when ins.OpCode != OpCodes.Call:
  109. ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs));
  110. modified = true;
  111. break;
  112. case 0:
  113. {
  114. var methodRef = ins.Operand as MethodReference;
  115. if (methodRef?.FullName != cbs.FullName)
  116. {
  117. ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs));
  118. modified = true;
  119. }
  120. break;
  121. }
  122. case 1 when ins.OpCode != OpCodes.Ret:
  123. ilp.Replace(ins, ilp.Create(OpCodes.Ret));
  124. modified = true;
  125. break;
  126. }
  127. }
  128. }
  129. if (modified)
  130. {
  131. bkp?.Add(unityPath);
  132. unityAsmDef.Write(unityPath);
  133. }
  134. }
  135. #endregion Insert patch into UnityEngine.CoreModule.dll
  136. loader.Debug("Ensuring Assembly-CSharp is virtualized");
  137. #region Virtualize Assembly-CSharp.dll
  138. {
  139. var ascPath = Path.Combine(Environment.CurrentDirectory, "Beat Saber_Data", "Managed",
  140. "Assembly-CSharp.dll");
  141. var ascModule = VirtualizedModule.Load(ascPath);
  142. ascModule.Virtualize(cAsmName, () => bkp?.Add(ascPath));
  143. }
  144. #endregion Virtualize Assembly-CSharp.dll
  145. }
  146. private static bool bootstrapped;
  147. private static void CreateBootstrapper()
  148. {
  149. if (bootstrapped) return;
  150. bootstrapped = true;
  151. Application.logMessageReceived += delegate (string condition, string stackTrace, LogType type)
  152. {
  153. var level = UnityLogInterceptor.LogTypeToLevel(type);
  154. UnityLogInterceptor.UnityLogger.Log(level, $"{condition.Trim()}");
  155. UnityLogInterceptor.UnityLogger.Log(level, $"{stackTrace.Trim()}");
  156. };
  157. // need to reinit streams singe Unity seems to redirect stdout
  158. WinConsole.InitializeStreams();
  159. var bootstrapper = new GameObject("NonDestructiveBootstrapper").AddComponent<Bootstrapper>();
  160. bootstrapper.Destroyed += Bootstrapper_Destroyed;
  161. }
  162. private static bool loadingDone;
  163. private static void Bootstrapper_Destroyed()
  164. {
  165. // wait for plugins to finish loading
  166. pluginAsyncLoadTask.Wait();
  167. log.Debug("Plugins loaded");
  168. log.Debug(string.Join(", ", PluginLoader.PluginsMetadata));
  169. PluginComponent.Create();
  170. }
  171. }
  172. }