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.

206 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
  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 Logger = IPA.Logging.Logger;
  15. using MethodAttributes = Mono.Cecil.MethodAttributes;
  16. namespace IPA.Injector
  17. {
  18. public static class Injector
  19. {
  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. // This loads System.Runtime.InteropServices, and Microsoft.Win32.SafeHandles.
  29. Windows.WinConsole.Initialize();
  30. // This loads AppDomain, System.IO, System.Collections.Generic, and System.Reflection.
  31. // If kernel32.dll is not already loaded, this will also load it.
  32. // This call also loads IPA.Loader and initializes the logging system. In the process
  33. // it loads Ionic.Zip.
  34. SetupLibraryLoading();
  35. loader.Debug("Prepping bootstrapper");
  36. // // This will load Mono.Cecil
  37. InstallBootstrapPatch();
  38. }
  39. catch (Exception e)
  40. {
  41. Console.WriteLine(e);
  42. }
  43. }
  44. private static void InstallBootstrapPatch()
  45. {
  46. var cAsmName = Assembly.GetExecutingAssembly().GetName();
  47. loader.Debug("Finding backup");
  48. var backupPath = Path.Combine(Environment.CurrentDirectory, "IPA","Backups","Beat Saber");
  49. var bkp = BackupManager.FindLatestBackup(backupPath);
  50. if (bkp == null)
  51. loader.Warn("No backup found! Was BSIPA installed using the installer?");
  52. loader.Debug("Ensuring patch on UnityEngine.CoreModule exists");
  53. #region Insert patch into UnityEngine.CoreModule.dll
  54. var unityPath = Path.Combine(Environment.CurrentDirectory, "Beat Saber_Data", "Managed", "UnityEngine.CoreModule.dll");
  55. var unityAsmDef = AssemblyDefinition.ReadAssembly(unityPath);
  56. var unityModDef = unityAsmDef.MainModule;
  57. bool modified = false;
  58. foreach (var asmref in unityModDef.AssemblyReferences)
  59. {
  60. if (asmref.Name == cAsmName.Name)
  61. {
  62. if (asmref.Version != cAsmName.Version)
  63. {
  64. asmref.Version = cAsmName.Version;
  65. modified = true;
  66. }
  67. }
  68. }
  69. var application = unityModDef.GetType("UnityEngine", "Application");
  70. MethodDefinition cctor = null;
  71. foreach (var m in application.Methods)
  72. if (m.IsRuntimeSpecialName && m.Name == ".cctor")
  73. cctor = m;
  74. var cbs = unityModDef.Import(((Action)CreateBootstrapper).Method);
  75. if (cctor == null)
  76. {
  77. cctor = new MethodDefinition(".cctor", MethodAttributes.RTSpecialName | MethodAttributes.Static | MethodAttributes.SpecialName, unityModDef.TypeSystem.Void);
  78. application.Methods.Add(cctor);
  79. modified = true;
  80. var ilp = cctor.Body.GetILProcessor();
  81. ilp.Emit(OpCodes.Call, cbs);
  82. ilp.Emit(OpCodes.Ret);
  83. }
  84. else
  85. {
  86. var ilp = cctor.Body.GetILProcessor();
  87. for (int i = 0; i < Math.Min(2, cctor.Body.Instructions.Count); i++)
  88. {
  89. var ins = cctor.Body.Instructions[i];
  90. if (i == 0)
  91. {
  92. if (ins.OpCode != OpCodes.Call)
  93. {
  94. ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs));
  95. modified = true;
  96. }
  97. else
  98. {
  99. var mref = ins.Operand as MethodReference;
  100. if (mref.FullName != cbs.FullName)
  101. {
  102. ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs));
  103. modified = true;
  104. }
  105. }
  106. }
  107. if (i == 1 && ins.OpCode != OpCodes.Ret)
  108. {
  109. ilp.Replace(ins, ilp.Create(OpCodes.Ret));
  110. modified = true;
  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 = false;
  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. Windows.WinConsole.InitializeStreams();
  140. var bootstrapper = new GameObject("NonDestructiveBootstrapper").AddComponent<Bootstrapper>();
  141. bootstrapper.Destroyed += Bootstrapper_Destroyed;
  142. }
  143. private static bool injected = false;
  144. public static void Inject()
  145. {
  146. if (!injected)
  147. {
  148. injected = true;
  149. Windows.WinConsole.Initialize();
  150. SetupLibraryLoading();
  151. var bootstrapper = new GameObject("Bootstrapper").AddComponent<Bootstrapper>();
  152. bootstrapper.Destroyed += Bootstrapper_Destroyed;
  153. }
  154. }
  155. private static bool loadingDone = false;
  156. public 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. [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
  173. [return: MarshalAs(UnmanagedType.Bool)]
  174. static extern bool SetDllDirectory(string lpPathName);
  175. private static void Bootstrapper_Destroyed()
  176. {
  177. PluginComponent.Create();
  178. }
  179. }
  180. }