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.

211 lines
7.5 KiB

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