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.

311 lines
11 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.Load();
  67. SelfConfig.ReadCommandLine(Environment.GetCommandLineArgs());
  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. loader.Debug("Prepping bootstrapper");
  75. // updates backup
  76. InstallBootstrapPatch();
  77. Updates.InstallPendingUpdates();
  78. LibLoader.SetupAssemblyFilenames(true);
  79. GameVersionEarly.Load();
  80. pluginAsyncLoadTask = PluginLoader.LoadTask();
  81. permissionFixTask = PermissionFix.FixPermissions(new DirectoryInfo(Environment.CurrentDirectory));
  82. }
  83. catch (Exception e)
  84. {
  85. Console.WriteLine(e);
  86. }
  87. }
  88. private static void EnsureDirectories()
  89. {
  90. string path;
  91. if (!Directory.Exists(path = Path.Combine(Environment.CurrentDirectory, "UserData")))
  92. Directory.CreateDirectory(path);
  93. if (!Directory.Exists(path = Path.Combine(Environment.CurrentDirectory, "Plugins")))
  94. Directory.CreateDirectory(path);
  95. }
  96. private static void SetupLibraryLoading()
  97. {
  98. if (loadingDone) return;
  99. loadingDone = true;
  100. LibLoader.Configure();
  101. }
  102. private static void InstallBootstrapPatch()
  103. {
  104. var cAsmName = Assembly.GetExecutingAssembly().GetName();
  105. var managedPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
  106. var dataDir = new DirectoryInfo(managedPath).Parent.Name;
  107. var gameName = dataDir.Substring(0, dataDir.Length - 5);
  108. loader.Debug("Finding backup");
  109. var backupPath = Path.Combine(Environment.CurrentDirectory, "IPA", "Backups", gameName);
  110. var bkp = BackupManager.FindLatestBackup(backupPath);
  111. if (bkp == null)
  112. loader.Warn("No backup found! Was BSIPA installed using the installer?");
  113. loader.Debug("Ensuring patch on UnityEngine.CoreModule exists");
  114. #region Insert patch into UnityEngine.CoreModule.dll
  115. {
  116. var unityPath = Path.Combine(managedPath,
  117. "UnityEngine.CoreModule.dll");
  118. var unityAsmDef = AssemblyDefinition.ReadAssembly(unityPath, new ReaderParameters
  119. {
  120. ReadWrite = false,
  121. InMemory = true,
  122. ReadingMode = ReadingMode.Immediate
  123. });
  124. var unityModDef = unityAsmDef.MainModule;
  125. bool modified = false;
  126. foreach (var asmref in unityModDef.AssemblyReferences)
  127. {
  128. if (asmref.Name == cAsmName.Name)
  129. {
  130. if (asmref.Version != cAsmName.Version)
  131. {
  132. asmref.Version = cAsmName.Version;
  133. modified = true;
  134. }
  135. }
  136. }
  137. var application = unityModDef.GetType("UnityEngine", "Application");
  138. MethodDefinition cctor = null;
  139. foreach (var m in application.Methods)
  140. if (m.IsRuntimeSpecialName && m.Name == ".cctor")
  141. cctor = m;
  142. var cbs = unityModDef.ImportReference(((Action)CreateBootstrapper).Method);
  143. if (cctor == null)
  144. {
  145. cctor = new MethodDefinition(".cctor",
  146. MethodAttributes.RTSpecialName | MethodAttributes.Static | MethodAttributes.SpecialName,
  147. unityModDef.TypeSystem.Void);
  148. application.Methods.Add(cctor);
  149. modified = true;
  150. var ilp = cctor.Body.GetILProcessor();
  151. ilp.Emit(OpCodes.Call, cbs);
  152. ilp.Emit(OpCodes.Ret);
  153. }
  154. else
  155. {
  156. var ilp = cctor.Body.GetILProcessor();
  157. for (var i = 0; i < Math.Min(2, cctor.Body.Instructions.Count); i++)
  158. {
  159. var ins = cctor.Body.Instructions[i];
  160. switch (i)
  161. {
  162. case 0 when ins.OpCode != OpCodes.Call:
  163. ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs));
  164. modified = true;
  165. break;
  166. case 0:
  167. {
  168. var methodRef = ins.Operand as MethodReference;
  169. if (methodRef?.FullName != cbs.FullName)
  170. {
  171. ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs));
  172. modified = true;
  173. }
  174. break;
  175. }
  176. case 1 when ins.OpCode != OpCodes.Ret:
  177. ilp.Replace(ins, ilp.Create(OpCodes.Ret));
  178. modified = true;
  179. break;
  180. }
  181. }
  182. }
  183. if (modified)
  184. {
  185. bkp?.Add(unityPath);
  186. unityAsmDef.Write(unityPath);
  187. }
  188. /*else
  189. return; // shortcut*/
  190. }
  191. #endregion Insert patch into UnityEngine.CoreModule.dll
  192. loader.Debug("Ensuring Assembly-CSharp is virtualized");
  193. {
  194. var ascPath = Path.Combine(managedPath,
  195. "Assembly-CSharp.dll");
  196. #region Virtualize Assembly-CSharp.dll
  197. {
  198. var ascModule = VirtualizedModule.Load(ascPath);
  199. ascModule.Virtualize(cAsmName, () => bkp?.Add(ascPath));
  200. }
  201. #endregion Virtualize Assembly-CSharp.dll
  202. #region Anti-Yeet
  203. //if (SelfConfig.SelfConfigRef.Value.ApplyAntiYeet)
  204. try
  205. {
  206. loader.Debug("Applying anti-yeet patch");
  207. var ascAsmDef = AssemblyDefinition.ReadAssembly(ascPath, new ReaderParameters
  208. {
  209. ReadWrite = false,
  210. InMemory = true,
  211. ReadingMode = ReadingMode.Immediate
  212. });
  213. var ascModDef = ascAsmDef.MainModule;
  214. var deleter = ascModDef.GetType("IPAPluginsDirDeleter");
  215. deleter.Methods.Clear(); // delete all methods
  216. ascAsmDef.Write(ascPath);
  217. }
  218. catch (Exception)
  219. {
  220. // ignore
  221. }
  222. #endregion
  223. }
  224. }
  225. private static bool bootstrapped;
  226. private static void CreateBootstrapper()
  227. {
  228. if (bootstrapped) return;
  229. bootstrapped = true;
  230. /*if (otherNewtonsoftJson != null)
  231. Assembly.LoadFrom(otherNewtonsoftJson);*/
  232. Application.logMessageReceived += delegate (string condition, string stackTrace, LogType type)
  233. {
  234. var level = UnityLogRedirector.LogTypeToLevel(type);
  235. UnityLogProvider.UnityLogger.Log(level, $"{condition}");
  236. UnityLogProvider.UnityLogger.Log(level, $"{stackTrace}");
  237. };
  238. // need to reinit streams singe Unity seems to redirect stdout
  239. StdoutInterceptor.RedirectConsole();
  240. var bootstrapper = new GameObject("NonDestructiveBootstrapper").AddComponent<Bootstrapper>();
  241. bootstrapper.Destroyed += Bootstrapper_Destroyed;
  242. }
  243. private static bool loadingDone;
  244. private static void Bootstrapper_Destroyed()
  245. {
  246. // wait for plugins to finish loading
  247. pluginAsyncLoadTask.Wait();
  248. permissionFixTask.Wait();
  249. BeatSaber.EnsureRuntimeGameVersion();
  250. log.Debug("Plugins loaded");
  251. log.Debug(string.Join(", ", PluginLoader.PluginsMetadata.StrJP()));
  252. PluginComponent.Create();
  253. }
  254. }
  255. }