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.

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