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