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.

258 lines
9.4 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. EnsureDirectories();
  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 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 EnsureDirectories()
  57. {
  58. string path;
  59. if (!Directory.Exists(path = Path.Combine(Environment.CurrentDirectory, "UserData")))
  60. Directory.CreateDirectory(path);
  61. if (!Directory.Exists(path = Path.Combine(Environment.CurrentDirectory, "Plugins")))
  62. Directory.CreateDirectory(path);
  63. }
  64. private static void SetupLibraryLoading()
  65. {
  66. if (loadingDone) return;
  67. loadingDone = true;
  68. AppDomain.CurrentDomain.AssemblyResolve += LibLoader.AssemblyLibLoader;
  69. }
  70. private static void InstallBootstrapPatch()
  71. {
  72. var cAsmName = Assembly.GetExecutingAssembly().GetName();
  73. loader.Debug("Finding backup");
  74. var backupPath = Path.Combine(Environment.CurrentDirectory, "IPA", "Backups", "Beat Saber");
  75. var bkp = BackupManager.FindLatestBackup(backupPath);
  76. if (bkp == null)
  77. loader.Warn("No backup found! Was BSIPA installed using the installer?");
  78. loader.Debug("Ensuring patch on UnityEngine.CoreModule exists");
  79. #region Insert patch into UnityEngine.CoreModule.dll
  80. {
  81. var unityPath = Path.Combine(Environment.CurrentDirectory, "Beat Saber_Data", "Managed",
  82. "UnityEngine.CoreModule.dll");
  83. var unityAsmDef = AssemblyDefinition.ReadAssembly(unityPath, new ReaderParameters
  84. {
  85. ReadWrite = false,
  86. InMemory = true,
  87. ReadingMode = ReadingMode.Immediate
  88. });
  89. var unityModDef = unityAsmDef.MainModule;
  90. bool modified = false;
  91. foreach (var asmref in unityModDef.AssemblyReferences)
  92. {
  93. if (asmref.Name == cAsmName.Name)
  94. {
  95. if (asmref.Version != cAsmName.Version)
  96. {
  97. asmref.Version = cAsmName.Version;
  98. modified = true;
  99. }
  100. }
  101. }
  102. var application = unityModDef.GetType("UnityEngine", "Application");
  103. MethodDefinition cctor = null;
  104. foreach (var m in application.Methods)
  105. if (m.IsRuntimeSpecialName && m.Name == ".cctor")
  106. cctor = m;
  107. var cbs = unityModDef.ImportReference(((Action)CreateBootstrapper).Method);
  108. if (cctor == null)
  109. {
  110. cctor = new MethodDefinition(".cctor",
  111. MethodAttributes.RTSpecialName | MethodAttributes.Static | MethodAttributes.SpecialName,
  112. unityModDef.TypeSystem.Void);
  113. application.Methods.Add(cctor);
  114. modified = true;
  115. var ilp = cctor.Body.GetILProcessor();
  116. ilp.Emit(OpCodes.Call, cbs);
  117. ilp.Emit(OpCodes.Ret);
  118. }
  119. else
  120. {
  121. var ilp = cctor.Body.GetILProcessor();
  122. for (var i = 0; i < Math.Min(2, cctor.Body.Instructions.Count); i++)
  123. {
  124. var ins = cctor.Body.Instructions[i];
  125. switch (i)
  126. {
  127. case 0 when ins.OpCode != OpCodes.Call:
  128. ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs));
  129. modified = true;
  130. break;
  131. case 0:
  132. {
  133. var methodRef = ins.Operand as MethodReference;
  134. if (methodRef?.FullName != cbs.FullName)
  135. {
  136. ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs));
  137. modified = true;
  138. }
  139. break;
  140. }
  141. case 1 when ins.OpCode != OpCodes.Ret:
  142. ilp.Replace(ins, ilp.Create(OpCodes.Ret));
  143. modified = true;
  144. break;
  145. }
  146. }
  147. }
  148. if (modified)
  149. {
  150. bkp?.Add(unityPath);
  151. unityAsmDef.Write(unityPath);
  152. }
  153. else
  154. return; // shortcut
  155. }
  156. #endregion Insert patch into UnityEngine.CoreModule.dll
  157. loader.Debug("Ensuring Assembly-CSharp is virtualized");
  158. {
  159. var ascPath = Path.Combine(Environment.CurrentDirectory, "Beat Saber_Data", "Managed",
  160. "Assembly-CSharp.dll");
  161. #region Virtualize Assembly-CSharp.dll
  162. {
  163. var ascModule = VirtualizedModule.Load(ascPath);
  164. ascModule.Virtualize(cAsmName, () => bkp?.Add(ascPath));
  165. }
  166. #endregion Virtualize Assembly-CSharp.dll
  167. #region Anti-Yeet
  168. if (SelfConfig.SelfConfigRef.Value.ApplyAntiYeet)
  169. {
  170. loader.Debug("Applying anti-yeet patch");
  171. var ascAsmDef = AssemblyDefinition.ReadAssembly(ascPath, new ReaderParameters
  172. {
  173. ReadWrite = false,
  174. InMemory = true,
  175. ReadingMode = ReadingMode.Immediate
  176. });
  177. var ascModDef = ascAsmDef.MainModule;
  178. var deleter = ascModDef.GetType("IPAPluginsDirDeleter");
  179. deleter.Methods.Clear(); // delete all methods
  180. ascAsmDef.Write(ascPath);
  181. }
  182. #endregion
  183. }
  184. }
  185. private static bool bootstrapped;
  186. private static void CreateBootstrapper()
  187. {
  188. if (bootstrapped) return;
  189. bootstrapped = true;
  190. Application.logMessageReceived += delegate (string condition, string stackTrace, LogType type)
  191. {
  192. var level = UnityLogRedirector.LogTypeToLevel(type);
  193. UnityLogProvider.UnityLogger.Log(level, $"{condition.Trim()}");
  194. UnityLogProvider.UnityLogger.Log(level, $"{stackTrace.Trim()}");
  195. };
  196. // need to reinit streams singe Unity seems to redirect stdout
  197. StdoutInterceptor.RedirectConsole();
  198. var bootstrapper = new GameObject("NonDestructiveBootstrapper").AddComponent<Bootstrapper>();
  199. bootstrapper.Destroyed += Bootstrapper_Destroyed;
  200. }
  201. private static bool loadingDone;
  202. private static void Bootstrapper_Destroyed()
  203. {
  204. // wait for plugins to finish loading
  205. pluginAsyncLoadTask.Wait();
  206. log.Debug("Plugins loaded");
  207. log.Debug(string.Join(", ", PluginLoader.PluginsMetadata));
  208. PluginComponent.Create();
  209. }
  210. }
  211. }