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.

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