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.

256 lines
9.3 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. using IPA.Config;
  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.IO;
  9. using System.Linq;
  10. using System.Reflection;
  11. using System.Threading.Tasks;
  12. using UnityEngine;
  13. using static IPA.Logging.Logger;
  14. using MethodAttributes = Mono.Cecil.MethodAttributes;
  15. namespace IPA.Injector
  16. {
  17. // ReSharper disable once UnusedMember.Global
  18. public static class Injector
  19. {
  20. private static Task pluginAsyncLoadTask;
  21. // ReSharper disable once UnusedParameter.Global
  22. public static void Main(string[] args)
  23. { // entry point for doorstop
  24. // At this point, literally nothing but mscorlib is loaded,
  25. // and since this class doesn't have any static fields that
  26. // aren't defined in mscorlib, we can control exactly what
  27. // gets loaded.
  28. try
  29. {
  30. if (!Environment.GetCommandLineArgs().Contains("--no-console"))
  31. WinConsole.Initialize();
  32. SetupLibraryLoading();
  33. EnsureUserData();
  34. // this is weird, but it prevents Mono from having issues loading the type.
  35. // IMPORTANT: NO CALLS TO ANY LOGGER CAN HAPPEN BEFORE THIS
  36. var unused = StandardLogger.PrintFilter;
  37. #region // Above hack explaination
  38. /*
  39. * Due to an unknown bug in the version of Mono that Unity 2018.1.8 uses, if the first access to StandardLogger
  40. * is a call to a constructor, then Mono fails to load the type correctly. However, if the first access is to
  41. * the above static property (or maybe any, but I don't really know) it behaves as expected and works fine.
  42. */
  43. #endregion
  44. log.Debug("Initializing logger");
  45. SelfConfig.Set();
  46. loader.Debug("Prepping bootstrapper");
  47. InstallBootstrapPatch();
  48. Updates.InstallPendingUpdates();
  49. pluginAsyncLoadTask = PluginLoader.LoadTask();
  50. }
  51. catch (Exception e)
  52. {
  53. Console.WriteLine(e);
  54. }
  55. }
  56. private static void EnsureUserData()
  57. {
  58. string path;
  59. if (!Directory.Exists(path = Path.Combine(Environment.CurrentDirectory, "UserData")))
  60. Directory.CreateDirectory(path);
  61. }
  62. private static void SetupLibraryLoading()
  63. {
  64. if (loadingDone) return;
  65. loadingDone = true;
  66. AppDomain.CurrentDomain.AssemblyResolve += LibLoader.AssemblyLibLoader;
  67. }
  68. private static void InstallBootstrapPatch()
  69. {
  70. var cAsmName = Assembly.GetExecutingAssembly().GetName();
  71. loader.Debug("Finding backup");
  72. var backupPath = Path.Combine(Environment.CurrentDirectory, "IPA", "Backups", "Beat Saber");
  73. var bkp = BackupManager.FindLatestBackup(backupPath);
  74. if (bkp == null)
  75. loader.Warn("No backup found! Was BSIPA installed using the installer?");
  76. loader.Debug("Ensuring patch on UnityEngine.CoreModule exists");
  77. #region Insert patch into UnityEngine.CoreModule.dll
  78. {
  79. var unityPath = Path.Combine(Environment.CurrentDirectory, "Beat Saber_Data", "Managed",
  80. "UnityEngine.CoreModule.dll");
  81. var unityAsmDef = AssemblyDefinition.ReadAssembly(unityPath, new ReaderParameters
  82. {
  83. ReadWrite = false,
  84. InMemory = true,
  85. ReadingMode = ReadingMode.Immediate
  86. });
  87. var unityModDef = unityAsmDef.MainModule;
  88. bool modified = false;
  89. foreach (var asmref in unityModDef.AssemblyReferences)
  90. {
  91. if (asmref.Name == cAsmName.Name)
  92. {
  93. if (asmref.Version != cAsmName.Version)
  94. {
  95. asmref.Version = cAsmName.Version;
  96. modified = true;
  97. }
  98. }
  99. }
  100. var application = unityModDef.GetType("UnityEngine", "Application");
  101. MethodDefinition cctor = null;
  102. foreach (var m in application.Methods)
  103. if (m.IsRuntimeSpecialName && m.Name == ".cctor")
  104. cctor = m;
  105. var cbs = unityModDef.ImportReference(((Action)CreateBootstrapper).Method);
  106. if (cctor == null)
  107. {
  108. cctor = new MethodDefinition(".cctor",
  109. MethodAttributes.RTSpecialName | MethodAttributes.Static | MethodAttributes.SpecialName,
  110. unityModDef.TypeSystem.Void);
  111. application.Methods.Add(cctor);
  112. modified = true;
  113. var ilp = cctor.Body.GetILProcessor();
  114. ilp.Emit(OpCodes.Call, cbs);
  115. ilp.Emit(OpCodes.Ret);
  116. }
  117. else
  118. {
  119. var ilp = cctor.Body.GetILProcessor();
  120. for (var i = 0; i < Math.Min(2, cctor.Body.Instructions.Count); i++)
  121. {
  122. var ins = cctor.Body.Instructions[i];
  123. switch (i)
  124. {
  125. case 0 when ins.OpCode != OpCodes.Call:
  126. ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs));
  127. modified = true;
  128. break;
  129. case 0:
  130. {
  131. var methodRef = ins.Operand as MethodReference;
  132. if (methodRef?.FullName != cbs.FullName)
  133. {
  134. ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs));
  135. modified = true;
  136. }
  137. break;
  138. }
  139. case 1 when ins.OpCode != OpCodes.Ret:
  140. ilp.Replace(ins, ilp.Create(OpCodes.Ret));
  141. modified = true;
  142. break;
  143. }
  144. }
  145. }
  146. if (modified)
  147. {
  148. bkp?.Add(unityPath);
  149. unityAsmDef.Write(unityPath);
  150. }
  151. else
  152. return; // shortcut
  153. }
  154. #endregion Insert patch into UnityEngine.CoreModule.dll
  155. loader.Debug("Ensuring Assembly-CSharp is virtualized");
  156. {
  157. var ascPath = Path.Combine(Environment.CurrentDirectory, "Beat Saber_Data", "Managed",
  158. "Assembly-CSharp.dll");
  159. #region Virtualize Assembly-CSharp.dll
  160. {
  161. var ascModule = VirtualizedModule.Load(ascPath);
  162. ascModule.Virtualize(cAsmName, () => bkp?.Add(ascPath));
  163. }
  164. #endregion Virtualize Assembly-CSharp.dll
  165. #region Anti-Yeet
  166. if (SelfConfig.SelfConfigRef.Value.ApplyAntiYeet)
  167. {
  168. loader.Debug("Applying anti-yeet patch");
  169. var ascAsmDef = AssemblyDefinition.ReadAssembly(ascPath, new ReaderParameters
  170. {
  171. ReadWrite = false,
  172. InMemory = true,
  173. ReadingMode = ReadingMode.Immediate
  174. });
  175. var ascModDef = ascAsmDef.MainModule;
  176. var deleter = ascModDef.GetType("IPAPluginsDirDeleter");
  177. deleter.Methods.Clear(); // delete all methods
  178. ascAsmDef.Write(ascPath);
  179. }
  180. #endregion
  181. }
  182. }
  183. private static bool bootstrapped;
  184. private static void CreateBootstrapper()
  185. {
  186. if (bootstrapped) return;
  187. bootstrapped = true;
  188. Application.logMessageReceived += delegate (string condition, string stackTrace, LogType type)
  189. {
  190. var level = UnityLogRedirector.LogTypeToLevel(type);
  191. UnityLogProvider.UnityLogger.Log(level, $"{condition.Trim()}");
  192. UnityLogProvider.UnityLogger.Log(level, $"{stackTrace.Trim()}");
  193. };
  194. // need to reinit streams singe Unity seems to redirect stdout
  195. WinConsole.InitializeStreams();
  196. var bootstrapper = new GameObject("NonDestructiveBootstrapper").AddComponent<Bootstrapper>();
  197. bootstrapper.Destroyed += Bootstrapper_Destroyed;
  198. }
  199. private static bool loadingDone;
  200. private static void Bootstrapper_Destroyed()
  201. {
  202. // wait for plugins to finish loading
  203. pluginAsyncLoadTask.Wait();
  204. log.Debug("Plugins loaded");
  205. log.Debug(string.Join(", ", PluginLoader.PluginsMetadata));
  206. PluginComponent.Create();
  207. }
  208. }
  209. }