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.

331 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. 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. Updates.InstallPendingUpdates();
  79. LibLoader.SetupAssemblyFilenames(true);
  80. GameVersionEarly.Load();
  81. InstallHarmonyProtections();
  82. pluginAsyncLoadTask = PluginLoader.LoadTask();
  83. permissionFixTask = PermissionFix.FixPermissions(new DirectoryInfo(Environment.CurrentDirectory));
  84. }
  85. catch (Exception e)
  86. {
  87. Console.WriteLine(e);
  88. throw;
  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. HarmonyProtector.Protect();
  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. }