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.

219 lines
7.7 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 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. EnsureUserData();
  34. //log.Debug("Initializing logger");
  35. SelfConfig.Set();
  36. loader.Debug("Prepping bootstrapper");
  37. InstallBootstrapPatch();
  38. Updates.InstallPendingUpdates();
  39. pluginAsyncLoadTask = PluginLoader.LoadTask();
  40. }
  41. catch (Exception e)
  42. {
  43. Console.WriteLine(e);
  44. }
  45. }
  46. private static void EnsureUserData()
  47. {
  48. string path;
  49. if (!Directory.Exists(path = Path.Combine(Environment.CurrentDirectory, "UserData")))
  50. Directory.CreateDirectory(path);
  51. }
  52. private static void SetupLibraryLoading()
  53. {
  54. if (loadingDone) return;
  55. loadingDone = true;
  56. AppDomain.CurrentDomain.AssemblyResolve += LibLoader.AssemblyLibLoader;
  57. }
  58. private static void InstallBootstrapPatch()
  59. {
  60. var cAsmName = Assembly.GetExecutingAssembly().GetName();
  61. loader.Debug("Finding backup");
  62. var backupPath = Path.Combine(Environment.CurrentDirectory, "IPA", "Backups", "Beat Saber");
  63. var bkp = BackupManager.FindLatestBackup(backupPath);
  64. if (bkp == null)
  65. loader.Warn("No backup found! Was BSIPA installed using the installer?");
  66. loader.Debug("Ensuring patch on UnityEngine.CoreModule exists");
  67. #region Insert patch into UnityEngine.CoreModule.dll
  68. {
  69. var unityPath = Path.Combine(Environment.CurrentDirectory, "Beat Saber_Data", "Managed",
  70. "UnityEngine.CoreModule.dll");
  71. var unityAsmDef = AssemblyDefinition.ReadAssembly(unityPath, new ReaderParameters
  72. {
  73. ReadWrite = false,
  74. InMemory = true,
  75. ReadingMode = ReadingMode.Immediate
  76. });
  77. var unityModDef = unityAsmDef.MainModule;
  78. bool modified = false;
  79. foreach (var asmref in unityModDef.AssemblyReferences)
  80. {
  81. if (asmref.Name == cAsmName.Name)
  82. {
  83. if (asmref.Version != cAsmName.Version)
  84. {
  85. asmref.Version = cAsmName.Version;
  86. modified = true;
  87. }
  88. }
  89. }
  90. var application = unityModDef.GetType("UnityEngine", "Application");
  91. MethodDefinition cctor = null;
  92. foreach (var m in application.Methods)
  93. if (m.IsRuntimeSpecialName && m.Name == ".cctor")
  94. cctor = m;
  95. var cbs = unityModDef.ImportReference(((Action)CreateBootstrapper).Method);
  96. if (cctor == null)
  97. {
  98. cctor = new MethodDefinition(".cctor",
  99. MethodAttributes.RTSpecialName | MethodAttributes.Static | MethodAttributes.SpecialName,
  100. unityModDef.TypeSystem.Void);
  101. application.Methods.Add(cctor);
  102. modified = true;
  103. var ilp = cctor.Body.GetILProcessor();
  104. ilp.Emit(OpCodes.Call, cbs);
  105. ilp.Emit(OpCodes.Ret);
  106. }
  107. else
  108. {
  109. var ilp = cctor.Body.GetILProcessor();
  110. for (var i = 0; i < Math.Min(2, cctor.Body.Instructions.Count); i++)
  111. {
  112. var ins = cctor.Body.Instructions[i];
  113. switch (i)
  114. {
  115. case 0 when ins.OpCode != OpCodes.Call:
  116. ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs));
  117. modified = true;
  118. break;
  119. case 0:
  120. {
  121. var methodRef = ins.Operand as MethodReference;
  122. if (methodRef?.FullName != cbs.FullName)
  123. {
  124. ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs));
  125. modified = true;
  126. }
  127. break;
  128. }
  129. case 1 when ins.OpCode != OpCodes.Ret:
  130. ilp.Replace(ins, ilp.Create(OpCodes.Ret));
  131. modified = true;
  132. break;
  133. }
  134. }
  135. }
  136. if (modified)
  137. {
  138. bkp?.Add(unityPath);
  139. unityAsmDef.Write(unityPath);
  140. }
  141. }
  142. #endregion Insert patch into UnityEngine.CoreModule.dll
  143. loader.Debug("Ensuring Assembly-CSharp is virtualized");
  144. #region Virtualize Assembly-CSharp.dll
  145. {
  146. var ascPath = Path.Combine(Environment.CurrentDirectory, "Beat Saber_Data", "Managed",
  147. "Assembly-CSharp.dll");
  148. var ascModule = VirtualizedModule.Load(ascPath);
  149. ascModule.Virtualize(cAsmName, () => bkp?.Add(ascPath));
  150. }
  151. #endregion Virtualize Assembly-CSharp.dll
  152. }
  153. private static bool bootstrapped;
  154. private static void CreateBootstrapper()
  155. {
  156. if (bootstrapped) return;
  157. bootstrapped = true;
  158. Application.logMessageReceived += delegate (string condition, string stackTrace, LogType type)
  159. {
  160. var level = UnityLogInterceptor.LogTypeToLevel(type);
  161. UnityLogInterceptor.UnityLogger.Log(level, $"{condition.Trim()}");
  162. UnityLogInterceptor.UnityLogger.Log(level, $"{stackTrace.Trim()}");
  163. };
  164. // need to reinit streams singe Unity seems to redirect stdout
  165. WinConsole.InitializeStreams();
  166. var bootstrapper = new GameObject("NonDestructiveBootstrapper").AddComponent<Bootstrapper>();
  167. bootstrapper.Destroyed += Bootstrapper_Destroyed;
  168. }
  169. private static bool loadingDone;
  170. private static void Bootstrapper_Destroyed()
  171. {
  172. // wait for plugins to finish loading
  173. pluginAsyncLoadTask.Wait();
  174. log.Debug("Plugins loaded");
  175. log.Debug(string.Join(", ", PluginLoader.PluginsMetadata));
  176. PluginComponent.Create();
  177. }
  178. }
  179. }