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.

332 lines
12 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 IPA.Utilities;
  6. using Mono.Cecil;
  7. using Mono.Cecil.Cil;
  8. using System;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Reflection;
  12. using System.Threading.Tasks;
  13. using UnityEngine;
  14. using static IPA.Logging.Logger;
  15. using MethodAttributes = Mono.Cecil.MethodAttributes;
  16. #if NET3
  17. using Net3_Proxy;
  18. using Path = Net3_Proxy.Path;
  19. using File = Net3_Proxy.File;
  20. using Directory = Net3_Proxy.Directory;
  21. #endif
  22. namespace IPA.Injector
  23. {
  24. /// <summary>
  25. /// The entry point type for BSIPA's Doorstop injector.
  26. /// </summary>
  27. // ReSharper disable once UnusedMember.Global
  28. internal static class Injector
  29. {
  30. private static Task pluginAsyncLoadTask;
  31. private static Task permissionFixTask;
  32. //private static string otherNewtonsoftJson = null;
  33. // ReSharper disable once UnusedParameter.Global
  34. internal static void Main(string[] args)
  35. { // entry point for doorstop
  36. // At this point, literally nothing but mscorlib is loaded,
  37. // and since this class doesn't have any static fields that
  38. // aren't defined in mscorlib, we can control exactly what
  39. // gets loaded.
  40. try
  41. {
  42. if (Environment.GetCommandLineArgs().Contains("--verbose"))
  43. WinConsole.Initialize();
  44. Console.WriteLine("Setting up library loading");
  45. SetupLibraryLoading();
  46. /*var otherNewtonsoft = Path.Combine(
  47. Directory.EnumerateDirectories(Environment.CurrentDirectory, "*_Data").First(),
  48. "Managed",
  49. "Newtonsoft.Json.dll");
  50. if (File.Exists(otherNewtonsoft))
  51. { // this game ships its own Newtonsoft; force load ours and flag loading theirs
  52. LibLoader.LoadLibrary(new AssemblyName("Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed"));
  53. otherNewtonsoftJson = otherNewtonsoft;
  54. }*/
  55. EnsureDirectories();
  56. // this is weird, but it prevents Mono from having issues loading the type.
  57. // IMPORTANT: NO CALLS TO ANY LOGGER CAN HAPPEN BEFORE THIS
  58. var unused = StandardLogger.PrintFilter;
  59. #region // Above hack explaination
  60. /*
  61. * Due to an unknown bug in the version of Mono that Unity uses, if the first access to StandardLogger
  62. * is a call to a constructor, then Mono fails to load the type correctly. However, if the first access is to
  63. * the above static property (or maybe any, but I don't really know) it behaves as expected and works fine.
  64. */
  65. #endregion
  66. log.Debug("Initializing logger");
  67. SelfConfig.ReadCommandLine(Environment.GetCommandLineArgs());
  68. SelfConfig.Load();
  69. DisabledConfig.Load();
  70. if (AntiPiracy.IsInvalid(Environment.CurrentDirectory))
  71. {
  72. loader.Error("Invalid installation; please buy the game to run BSIPA.");
  73. return;
  74. }
  75. CriticalSection.Configure();
  76. loader.Debug("Prepping bootstrapper");
  77. // updates backup
  78. InstallBootstrapPatch();
  79. Updates.InstallPendingUpdates();
  80. LibLoader.SetupAssemblyFilenames(true);
  81. GameVersionEarly.Load();
  82. InstallHarmonyProtections();
  83. pluginAsyncLoadTask = PluginLoader.LoadTask();
  84. permissionFixTask = PermissionFix.FixPermissions(new DirectoryInfo(Environment.CurrentDirectory));
  85. }
  86. catch (Exception e)
  87. {
  88. Console.WriteLine(e);
  89. }
  90. }
  91. private static void EnsureDirectories()
  92. {
  93. string path;
  94. if (!Directory.Exists(path = Path.Combine(Environment.CurrentDirectory, "UserData")))
  95. Directory.CreateDirectory(path);
  96. if (!Directory.Exists(path = Path.Combine(Environment.CurrentDirectory, "Plugins")))
  97. Directory.CreateDirectory(path);
  98. }
  99. private static void SetupLibraryLoading()
  100. {
  101. if (loadingDone) return;
  102. loadingDone = true;
  103. LibLoader.Configure();
  104. }
  105. private static void InstallHarmonyProtections()
  106. { // proxy function to delay resolution
  107. HarmonyProtectorProxy.ProtectNull();
  108. }
  109. private static void InstallBootstrapPatch()
  110. {
  111. var cAsmName = Assembly.GetExecutingAssembly().GetName();
  112. var managedPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
  113. var dataDir = new DirectoryInfo(managedPath).Parent.Name;
  114. var gameName = dataDir.Substring(0, dataDir.Length - 5);
  115. loader.Debug("Finding backup");
  116. var backupPath = Path.Combine(Environment.CurrentDirectory, "IPA", "Backups", gameName);
  117. var bkp = BackupManager.FindLatestBackup(backupPath);
  118. if (bkp == null)
  119. loader.Warn("No backup found! Was BSIPA installed using the installer?");
  120. loader.Debug("Ensuring patch on UnityEngine.CoreModule exists");
  121. #region Insert patch into UnityEngine.CoreModule.dll
  122. {
  123. var unityPath = Path.Combine(managedPath,
  124. "UnityEngine.CoreModule.dll");
  125. // this is a critical section because if you exit in here, CoreModule can die
  126. CriticalSection.EnterExecuteSection();
  127. var unityAsmDef = AssemblyDefinition.ReadAssembly(unityPath, new ReaderParameters
  128. {
  129. ReadWrite = false,
  130. InMemory = true,
  131. ReadingMode = ReadingMode.Immediate
  132. });
  133. var unityModDef = unityAsmDef.MainModule;
  134. bool modified = false;
  135. foreach (var asmref in unityModDef.AssemblyReferences)
  136. {
  137. if (asmref.Name == cAsmName.Name)
  138. {
  139. if (asmref.Version != cAsmName.Version)
  140. {
  141. asmref.Version = cAsmName.Version;
  142. modified = true;
  143. }
  144. }
  145. }
  146. var application = unityModDef.GetType("UnityEngine", "Application");
  147. MethodDefinition cctor = null;
  148. foreach (var m in application.Methods)
  149. if (m.IsRuntimeSpecialName && m.Name == ".cctor")
  150. cctor = m;
  151. var cbs = unityModDef.ImportReference(((Action)CreateBootstrapper).Method);
  152. if (cctor == null)
  153. {
  154. cctor = new MethodDefinition(".cctor",
  155. MethodAttributes.RTSpecialName | MethodAttributes.Static | MethodAttributes.SpecialName,
  156. unityModDef.TypeSystem.Void);
  157. application.Methods.Add(cctor);
  158. modified = true;
  159. var ilp = cctor.Body.GetILProcessor();
  160. ilp.Emit(OpCodes.Call, cbs);
  161. ilp.Emit(OpCodes.Ret);
  162. }
  163. else
  164. {
  165. var ilp = cctor.Body.GetILProcessor();
  166. for (var i = 0; i < Math.Min(2, cctor.Body.Instructions.Count); i++)
  167. {
  168. var ins = cctor.Body.Instructions[i];
  169. switch (i)
  170. {
  171. case 0 when ins.OpCode != OpCodes.Call:
  172. ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs));
  173. modified = true;
  174. break;
  175. case 0:
  176. {
  177. var methodRef = ins.Operand as MethodReference;
  178. if (methodRef?.FullName != cbs.FullName)
  179. {
  180. ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs));
  181. modified = true;
  182. }
  183. break;
  184. }
  185. case 1 when ins.OpCode != OpCodes.Ret:
  186. ilp.Replace(ins, ilp.Create(OpCodes.Ret));
  187. modified = true;
  188. break;
  189. }
  190. }
  191. }
  192. if (modified)
  193. {
  194. bkp?.Add(unityPath);
  195. unityAsmDef.Write(unityPath);
  196. }
  197. CriticalSection.ExitExecuteSection();
  198. }
  199. #endregion Insert patch into UnityEngine.CoreModule.dll
  200. loader.Debug("Ensuring Assembly-CSharp is virtualized");
  201. {
  202. var ascPath = Path.Combine(managedPath,
  203. "Assembly-CSharp.dll");
  204. #region Virtualize Assembly-CSharp.dll
  205. {
  206. CriticalSection.EnterExecuteSection();
  207. var ascModule = VirtualizedModule.Load(ascPath);
  208. ascModule.Virtualize(cAsmName, () => bkp?.Add(ascPath));
  209. CriticalSection.ExitExecuteSection();
  210. }
  211. #endregion Virtualize Assembly-CSharp.dll
  212. #region Anti-Yeet
  213. CriticalSection.EnterExecuteSection();
  214. try
  215. {
  216. loader.Debug("Applying anti-yeet patch");
  217. var ascAsmDef = AssemblyDefinition.ReadAssembly(ascPath, new ReaderParameters
  218. {
  219. ReadWrite = false,
  220. InMemory = true,
  221. ReadingMode = ReadingMode.Immediate
  222. });
  223. var ascModDef = ascAsmDef.MainModule;
  224. var deleter = ascModDef.GetType("IPAPluginsDirDeleter");
  225. deleter.Methods.Clear(); // delete all methods
  226. ascAsmDef.Write(ascPath);
  227. }
  228. catch (Exception)
  229. {
  230. // ignore
  231. }
  232. CriticalSection.ExitExecuteSection();
  233. #endregion
  234. }
  235. }
  236. private static bool bootstrapped;
  237. private static void CreateBootstrapper()
  238. {
  239. if (bootstrapped) return;
  240. bootstrapped = true;
  241. /*if (otherNewtonsoftJson != null)
  242. Assembly.LoadFrom(otherNewtonsoftJson);*/
  243. Application.logMessageReceived += delegate (string condition, string stackTrace, LogType type)
  244. {
  245. var level = UnityLogRedirector.LogTypeToLevel(type);
  246. UnityLogProvider.UnityLogger.Log(level, $"{condition}");
  247. UnityLogProvider.UnityLogger.Log(level, $"{stackTrace}");
  248. };
  249. // need to reinit streams singe Unity seems to redirect stdout
  250. StdoutInterceptor.RedirectConsole();
  251. var bootstrapper = new GameObject("NonDestructiveBootstrapper").AddComponent<Bootstrapper>();
  252. bootstrapper.Destroyed += Bootstrapper_Destroyed;
  253. }
  254. private static bool loadingDone;
  255. private static void Bootstrapper_Destroyed()
  256. {
  257. // wait for plugins to finish loading
  258. pluginAsyncLoadTask.Wait();
  259. permissionFixTask.Wait();
  260. BeatSaber.EnsureRuntimeGameVersion();
  261. log.Debug("Plugins loaded");
  262. log.Debug(string.Join(", ", PluginLoader.PluginsMetadata.StrJP()));
  263. PluginComponent.Create();
  264. }
  265. }
  266. }