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.

361 lines
14 KiB

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