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.

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