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.

190 lines
6.8 KiB

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