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.

346 lines
13 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. if (Environment.GetCommandLineArgs().Contains("--verbose"))
  44. WinConsole.Initialize();
  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. log.Error("Invalid installation; please buy the game to run BSIPA.");
  73. return;
  74. }
  75. CriticalSection.Configure();
  76. injector.Debug("Prepping bootstrapper");
  77. // updates backup
  78. InstallBootstrapPatch();
  79. GameVersionEarly.Load();
  80. Updates.InstallPendingUpdates();
  81. LibLoader.SetupAssemblyFilenames(true);
  82. pluginAsyncLoadTask = PluginLoader.LoadTask();
  83. permissionFixTask = PermissionFix.FixPermissions(new DirectoryInfo(Environment.CurrentDirectory));
  84. }
  85. catch (Exception e)
  86. {
  87. Console.WriteLine(e);
  88. }
  89. }
  90. private static void EnsureDirectories()
  91. {
  92. string path;
  93. if (!Directory.Exists(path = Path.Combine(Environment.CurrentDirectory, "UserData")))
  94. Directory.CreateDirectory(path);
  95. if (!Directory.Exists(path = Path.Combine(Environment.CurrentDirectory, "Plugins")))
  96. Directory.CreateDirectory(path);
  97. }
  98. private static void SetupLibraryLoading()
  99. {
  100. if (loadingDone) return;
  101. loadingDone = true;
  102. LibLoader.Configure();
  103. }
  104. private static void InstallHarmonyProtections()
  105. { // proxy function to delay resolution
  106. HarmonyProtectorProxy.ProtectNull();
  107. }
  108. private static void InstallBootstrapPatch()
  109. {
  110. var sw = Stopwatch.StartNew();
  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. injector.Debug("Finding backup");
  116. var backupPath = Path.Combine(Environment.CurrentDirectory, "IPA", "Backups", gameName);
  117. var bkp = BackupManager.FindLatestBackup(backupPath);
  118. if (bkp == null)
  119. injector.Warn("No backup found! Was BSIPA installed using the installer?");
  120. injector.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. using var critSec = CriticalSection.ExecuteSection();
  127. using 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", "Camera");
  147. if (application == null)
  148. {
  149. injector.Critical("UnityEngine.CoreModule doesn't have a definition for UnityEngine.Camera!"
  150. + "Nothing to patch to get ourselves into the Unity run cycle!");
  151. goto endPatchCoreModule;
  152. }
  153. MethodDefinition cctor = null;
  154. foreach (var m in application.Methods)
  155. if (m.IsRuntimeSpecialName && m.Name == ".cctor")
  156. cctor = m;
  157. var cbs = unityModDef.ImportReference(((Action)CreateBootstrapper).Method);
  158. if (cctor == null)
  159. {
  160. cctor = new MethodDefinition(".cctor",
  161. MethodAttributes.RTSpecialName | MethodAttributes.Static | MethodAttributes.SpecialName,
  162. unityModDef.TypeSystem.Void);
  163. application.Methods.Add(cctor);
  164. modified = true;
  165. var ilp = cctor.Body.GetILProcessor();
  166. ilp.Emit(OpCodes.Call, cbs);
  167. ilp.Emit(OpCodes.Ret);
  168. }
  169. else
  170. {
  171. var ilp = cctor.Body.GetILProcessor();
  172. for (var i = 0; i < Math.Min(2, cctor.Body.Instructions.Count); i++)
  173. {
  174. var ins = cctor.Body.Instructions[i];
  175. switch (i)
  176. {
  177. case 0 when ins.OpCode != OpCodes.Call:
  178. ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs));
  179. modified = true;
  180. break;
  181. case 0:
  182. {
  183. var methodRef = ins.Operand as MethodReference;
  184. if (methodRef?.FullName != cbs.FullName)
  185. {
  186. ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs));
  187. modified = true;
  188. }
  189. break;
  190. }
  191. case 1 when ins.OpCode != OpCodes.Ret:
  192. ilp.Replace(ins, ilp.Create(OpCodes.Ret));
  193. modified = true;
  194. break;
  195. }
  196. }
  197. }
  198. if (modified)
  199. {
  200. bkp?.Add(unityPath);
  201. unityAsmDef.Write(unityPath);
  202. }
  203. }
  204. endPatchCoreModule:
  205. #endregion Insert patch into UnityEngine.CoreModule.dll
  206. injector.Debug("Ensuring game assemblies are virtualized");
  207. #region Virtualize game assemblies
  208. bool isFirst = true;
  209. foreach (var name in SelfConfig.GameAssemblies_)
  210. {
  211. var ascPath = Path.Combine(managedPath, name);
  212. using var execSec = CriticalSection.ExecuteSection();
  213. try
  214. {
  215. injector.Debug($"Virtualizing {name}");
  216. using var ascModule = VirtualizedModule.Load(ascPath);
  217. ascModule.Virtualize(cAsmName, () => bkp?.Add(ascPath));
  218. }
  219. catch (Exception e)
  220. {
  221. injector.Error($"Could not virtualize {ascPath}");
  222. if (SelfConfig.Debug_.ShowHandledErrorStackTraces_)
  223. injector.Error(e);
  224. }
  225. #if BeatSaber
  226. if (isFirst)
  227. {
  228. try
  229. {
  230. injector.Debug("Applying anti-yeet patch");
  231. using var ascAsmDef = AssemblyDefinition.ReadAssembly(ascPath, new ReaderParameters
  232. {
  233. ReadWrite = false,
  234. InMemory = true,
  235. ReadingMode = ReadingMode.Immediate
  236. });
  237. var ascModDef = ascAsmDef.MainModule;
  238. var deleter = ascModDef.GetType("IPAPluginsDirDeleter");
  239. deleter.Methods.Clear(); // delete all methods
  240. ascAsmDef.Write(ascPath);
  241. isFirst = false;
  242. }
  243. catch (Exception e)
  244. {
  245. injector.Warn($"Could not apply anti-yeet patch to {ascPath}");
  246. if (SelfConfig.Debug_.ShowHandledErrorStackTraces_)
  247. injector.Warn(e);
  248. }
  249. }
  250. #endif
  251. }
  252. #endregion
  253. sw.Stop();
  254. injector.Info($"Installing bootstrapper took {sw.Elapsed}");
  255. }
  256. private static bool bootstrapped;
  257. private static void CreateBootstrapper()
  258. {
  259. if (bootstrapped) return;
  260. bootstrapped = true;
  261. /*if (otherNewtonsoftJson != null)
  262. Assembly.LoadFrom(otherNewtonsoftJson);*/
  263. Application.logMessageReceived += delegate (string condition, string stackTrace, LogType type)
  264. {
  265. var level = UnityLogRedirector.LogTypeToLevel(type);
  266. UnityLogProvider.UnityLogger.Log(level, $"{condition}");
  267. UnityLogProvider.UnityLogger.Log(level, $"{stackTrace}");
  268. };
  269. // need to reinit streams singe Unity seems to redirect stdout
  270. StdoutInterceptor.RedirectConsole();
  271. InstallHarmonyProtections();
  272. var bootstrapper = new GameObject("NonDestructiveBootstrapper").AddComponent<Bootstrapper>();
  273. bootstrapper.Destroyed += Bootstrapper_Destroyed;
  274. }
  275. private static bool loadingDone;
  276. private static void Bootstrapper_Destroyed()
  277. {
  278. // wait for plugins to finish loading
  279. pluginAsyncLoadTask.Wait();
  280. permissionFixTask.Wait();
  281. log.Debug("Plugins loaded");
  282. log.Debug(string.Join(", ", PluginLoader.PluginsMetadata.StrJP()));
  283. PluginComponent.Create();
  284. }
  285. }
  286. }