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.

341 lines
12 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 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. 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. loader.Error("Invalid installation; please buy the game to run BSIPA.");
  72. return;
  73. }
  74. CriticalSection.Configure();
  75. loader.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. loader.Debug("Finding backup");
  114. var backupPath = Path.Combine(Environment.CurrentDirectory, "IPA", "Backups", gameName);
  115. var bkp = BackupManager.FindLatestBackup(backupPath);
  116. if (bkp == null)
  117. loader.Warn("No backup found! Was BSIPA installed using the installer?");
  118. loader.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. CriticalSection.EnterExecuteSection();
  125. 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", "Application");
  145. MethodDefinition cctor = null;
  146. foreach (var m in application.Methods)
  147. if (m.IsRuntimeSpecialName && m.Name == ".cctor")
  148. cctor = m;
  149. var cbs = unityModDef.ImportReference(((Action)CreateBootstrapper).Method);
  150. if (cctor == null)
  151. {
  152. cctor = new MethodDefinition(".cctor",
  153. MethodAttributes.RTSpecialName | MethodAttributes.Static | MethodAttributes.SpecialName,
  154. unityModDef.TypeSystem.Void);
  155. application.Methods.Add(cctor);
  156. modified = true;
  157. var ilp = cctor.Body.GetILProcessor();
  158. ilp.Emit(OpCodes.Call, cbs);
  159. ilp.Emit(OpCodes.Ret);
  160. }
  161. else
  162. {
  163. var ilp = cctor.Body.GetILProcessor();
  164. for (var i = 0; i < Math.Min(2, cctor.Body.Instructions.Count); i++)
  165. {
  166. var ins = cctor.Body.Instructions[i];
  167. switch (i)
  168. {
  169. case 0 when ins.OpCode != OpCodes.Call:
  170. ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs));
  171. modified = true;
  172. break;
  173. case 0:
  174. {
  175. var methodRef = ins.Operand as MethodReference;
  176. if (methodRef?.FullName != cbs.FullName)
  177. {
  178. ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs));
  179. modified = true;
  180. }
  181. break;
  182. }
  183. case 1 when ins.OpCode != OpCodes.Ret:
  184. ilp.Replace(ins, ilp.Create(OpCodes.Ret));
  185. modified = true;
  186. break;
  187. }
  188. }
  189. }
  190. if (modified)
  191. {
  192. bkp?.Add(unityPath);
  193. unityAsmDef.Write(unityPath);
  194. }
  195. CriticalSection.ExitExecuteSection();
  196. }
  197. #endregion Insert patch into UnityEngine.CoreModule.dll
  198. loader.Debug("Ensuring game assemblies are virtualized");
  199. #region Virtualize game assemblies
  200. bool isFirst = true;
  201. foreach(var name in SelfConfig.GameAssemblies_)
  202. {
  203. var ascPath = Path.Combine(managedPath, name);
  204. CriticalSection.EnterExecuteSection();
  205. try
  206. {
  207. loader.Debug($"Virtualizing {name}");
  208. using var ascModule = VirtualizedModule.Load(ascPath);
  209. ascModule.Virtualize(cAsmName, () => bkp?.Add(ascPath));
  210. }
  211. catch (Exception e)
  212. {
  213. loader.Error($"Could not virtualize {ascPath}");
  214. if (SelfConfig.Debug_.ShowHandledErrorStackTraces_)
  215. loader.Error(e);
  216. }
  217. if (isFirst)
  218. {
  219. try
  220. {
  221. loader.Debug("Applying anti-yeet patch");
  222. var ascAsmDef = AssemblyDefinition.ReadAssembly(ascPath, new ReaderParameters
  223. {
  224. ReadWrite = false,
  225. InMemory = true,
  226. ReadingMode = ReadingMode.Immediate
  227. });
  228. var ascModDef = ascAsmDef.MainModule;
  229. var deleter = ascModDef.GetType("IPAPluginsDirDeleter");
  230. deleter.Methods.Clear(); // delete all methods
  231. ascAsmDef.Write(ascPath);
  232. isFirst = false;
  233. }
  234. catch (Exception e)
  235. {
  236. loader.Warn($"Could not apply anti-yeet patch to {ascPath}");
  237. if (SelfConfig.Debug_.ShowHandledErrorStackTraces_)
  238. loader.Warn(e);
  239. }
  240. }
  241. CriticalSection.ExitExecuteSection();
  242. }
  243. #endregion
  244. }
  245. private static bool bootstrapped;
  246. private static void CreateBootstrapper()
  247. {
  248. if (bootstrapped) return;
  249. bootstrapped = true;
  250. /*if (otherNewtonsoftJson != null)
  251. Assembly.LoadFrom(otherNewtonsoftJson);*/
  252. #if DEBUG
  253. Config.Stores.GeneratedStore.DebugSaveAssembly("GeneratedAssembly.dll");
  254. #endif
  255. Application.logMessageReceived += delegate (string condition, string stackTrace, LogType type)
  256. {
  257. var level = UnityLogRedirector.LogTypeToLevel(type);
  258. UnityLogProvider.UnityLogger.Log(level, $"{condition}");
  259. UnityLogProvider.UnityLogger.Log(level, $"{stackTrace}");
  260. };
  261. // need to reinit streams singe Unity seems to redirect stdout
  262. StdoutInterceptor.RedirectConsole();
  263. InstallHarmonyProtections();
  264. var bootstrapper = new GameObject("NonDestructiveBootstrapper").AddComponent<Bootstrapper>();
  265. bootstrapper.Destroyed += Bootstrapper_Destroyed;
  266. }
  267. private static bool loadingDone;
  268. private static void Bootstrapper_Destroyed()
  269. {
  270. // wait for plugins to finish loading
  271. pluginAsyncLoadTask.Wait();
  272. permissionFixTask.Wait();
  273. BeatSaber.EnsureRuntimeGameVersion();
  274. log.Debug("Plugins loaded");
  275. log.Debug(string.Join(", ", PluginLoader.PluginsMetadata.StrJP()));
  276. PluginComponent.Create();
  277. }
  278. }
  279. }