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.

197 lines
7.0 KiB

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.IO;
  8. using System.Linq;
  9. using System.Reflection;
  10. using UnityEngine;
  11. using static IPA.Logging.Logger;
  12. using MethodAttributes = Mono.Cecil.MethodAttributes;
  13. namespace IPA.Injector
  14. {
  15. // ReSharper disable once UnusedMember.Global
  16. public static class Injector
  17. {
  18. // ReSharper disable once UnusedParameter.Global
  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. if (!Environment.GetCommandLineArgs().Contains("--no-console"))
  28. WinConsole.Initialize();
  29. SetupLibraryLoading();
  30. loader.Debug("Prepping bootstrapper");
  31. InstallBootstrapPatch();
  32. Updates.InstallPendingUpdates();
  33. }
  34. catch (Exception e)
  35. {
  36. Console.WriteLine(e);
  37. }
  38. }
  39. private static void InstallBootstrapPatch()
  40. {
  41. var cAsmName = Assembly.GetExecutingAssembly().GetName();
  42. loader.Debug("Finding backup");
  43. var backupPath = Path.Combine(Environment.CurrentDirectory, "IPA","Backups","Beat Saber");
  44. var bkp = BackupManager.FindLatestBackup(backupPath);
  45. if (bkp == null)
  46. loader.Warn("No backup found! Was BSIPA installed using the installer?");
  47. loader.Debug("Ensuring patch on UnityEngine.CoreModule exists");
  48. #region Insert patch into UnityEngine.CoreModule.dll
  49. var unityPath = Path.Combine(Environment.CurrentDirectory, "Beat Saber_Data", "Managed", "UnityEngine.CoreModule.dll");
  50. var unityAsmDef = AssemblyDefinition.ReadAssembly(unityPath, new ReaderParameters
  51. {
  52. ReadWrite = false,
  53. InMemory = true,
  54. ReadingMode = ReadingMode.Immediate
  55. });
  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.ImportReference(((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 (var i = 0; i < Math.Min(2, cctor.Body.Instructions.Count); i++)
  88. {
  89. var ins = cctor.Body.Instructions[i];
  90. switch (i)
  91. {
  92. case 0 when ins.OpCode != OpCodes.Call:
  93. ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs));
  94. modified = true;
  95. break;
  96. case 0:
  97. {
  98. var methodRef = ins.Operand as MethodReference;
  99. if (methodRef?.FullName != cbs.FullName)
  100. {
  101. ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs));
  102. modified = true;
  103. }
  104. break;
  105. }
  106. case 1 when ins.OpCode != OpCodes.Ret:
  107. ilp.Replace(ins, ilp.Create(OpCodes.Ret));
  108. modified = true;
  109. break;
  110. }
  111. }
  112. }
  113. if (modified)
  114. {
  115. bkp?.Add(unityPath);
  116. unityAsmDef.Write(unityPath);
  117. }
  118. #endregion
  119. loader.Debug("Ensuring Assembly-CSharp is virtualized");
  120. #region Virtualize Assembly-CSharp.dll
  121. var ascPath = Path.Combine(Environment.CurrentDirectory, "Beat Saber_Data", "Managed", "Assembly-CSharp.dll");
  122. var ascModule = VirtualizedModule.Load(ascPath);
  123. ascModule.Virtualize(cAsmName, () => bkp?.Add(ascPath));
  124. #endregion
  125. }
  126. private static bool _bootstrapped;
  127. private static void CreateBootstrapper()
  128. {
  129. if (_bootstrapped) return;
  130. _bootstrapped = true;
  131. Application.logMessageReceived += delegate (string condition, string stackTrace, LogType type)
  132. {
  133. var level = UnityLogInterceptor.LogTypeToLevel(type);
  134. UnityLogInterceptor.UnityLogger.Log(level, $"{condition.Trim()}");
  135. UnityLogInterceptor.UnityLogger.Log(level, $"{stackTrace.Trim()}");
  136. };
  137. // need to reinit streams singe Unity seems to redirect stdout
  138. WinConsole.InitializeStreams();
  139. var bootstrapper = new GameObject("NonDestructiveBootstrapper").AddComponent<Bootstrapper>();
  140. bootstrapper.Destroyed += Bootstrapper_Destroyed;
  141. }
  142. private static bool _loadingDone;
  143. private static void SetupLibraryLoading()
  144. {
  145. if (_loadingDone) return;
  146. _loadingDone = true;
  147. #region Add Library load locations
  148. AppDomain.CurrentDomain.AssemblyResolve += LibLoader.AssemblyLibLoader;
  149. /*try
  150. {
  151. if (!SetDllDirectory(LibLoader.NativeDir))
  152. {
  153. libLoader.Warn("Unable to add native library path to load path");
  154. }
  155. }
  156. catch (Exception) { }*/
  157. #endregion
  158. }
  159. /*
  160. [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
  161. [return: MarshalAs(UnmanagedType.Bool)]
  162. static extern bool SetDllDirectory(string lpPathName);
  163. */
  164. private static void Bootstrapper_Destroyed()
  165. {
  166. PluginComponent.Create();
  167. }
  168. }
  169. }