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.

333 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. //HarmonyProtector.Protect();
  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 InstallBootstrapPatch()
  105. {
  106. var cAsmName = Assembly.GetExecutingAssembly().GetName();
  107. var managedPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
  108. var dataDir = new DirectoryInfo(managedPath).Parent.Name;
  109. var gameName = dataDir.Substring(0, dataDir.Length - 5);
  110. loader.Debug("Finding backup");
  111. var backupPath = Path.Combine(Environment.CurrentDirectory, "IPA", "Backups", gameName);
  112. var bkp = BackupManager.FindLatestBackup(backupPath);
  113. if (bkp == null)
  114. loader.Warn("No backup found! Was BSIPA installed using the installer?");
  115. loader.Debug("Ensuring patch on UnityEngine.CoreModule exists");
  116. #region Insert patch into UnityEngine.CoreModule.dll
  117. {
  118. var unityPath = Path.Combine(managedPath,
  119. "UnityEngine.CoreModule.dll");
  120. // this is a critical section because if you exit in here, CoreModule can die
  121. CriticalSection.EnterExecuteSection();
  122. var unityAsmDef = AssemblyDefinition.ReadAssembly(unityPath, new ReaderParameters
  123. {
  124. ReadWrite = false,
  125. InMemory = true,
  126. ReadingMode = ReadingMode.Immediate
  127. });
  128. var unityModDef = unityAsmDef.MainModule;
  129. bool modified = false;
  130. foreach (var asmref in unityModDef.AssemblyReferences)
  131. {
  132. if (asmref.Name == cAsmName.Name)
  133. {
  134. if (asmref.Version != cAsmName.Version)
  135. {
  136. asmref.Version = cAsmName.Version;
  137. modified = true;
  138. }
  139. }
  140. }
  141. var application = unityModDef.GetType("UnityEngine", "Application");
  142. MethodDefinition cctor = null;
  143. foreach (var m in application.Methods)
  144. if (m.IsRuntimeSpecialName && m.Name == ".cctor")
  145. cctor = m;
  146. var cbs = unityModDef.ImportReference(((Action)CreateBootstrapper).Method);
  147. if (cctor == null)
  148. {
  149. cctor = new MethodDefinition(".cctor",
  150. MethodAttributes.RTSpecialName | MethodAttributes.Static | MethodAttributes.SpecialName,
  151. unityModDef.TypeSystem.Void);
  152. application.Methods.Add(cctor);
  153. modified = true;
  154. var ilp = cctor.Body.GetILProcessor();
  155. ilp.Emit(OpCodes.Call, cbs);
  156. ilp.Emit(OpCodes.Ret);
  157. }
  158. else
  159. {
  160. var ilp = cctor.Body.GetILProcessor();
  161. for (var i = 0; i < Math.Min(2, cctor.Body.Instructions.Count); i++)
  162. {
  163. var ins = cctor.Body.Instructions[i];
  164. switch (i)
  165. {
  166. case 0 when ins.OpCode != OpCodes.Call:
  167. ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs));
  168. modified = true;
  169. break;
  170. case 0:
  171. {
  172. var methodRef = ins.Operand as MethodReference;
  173. if (methodRef?.FullName != cbs.FullName)
  174. {
  175. ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs));
  176. modified = true;
  177. }
  178. break;
  179. }
  180. case 1 when ins.OpCode != OpCodes.Ret:
  181. ilp.Replace(ins, ilp.Create(OpCodes.Ret));
  182. modified = true;
  183. break;
  184. }
  185. }
  186. }
  187. if (modified)
  188. {
  189. bkp?.Add(unityPath);
  190. unityAsmDef.Write(unityPath);
  191. }
  192. CriticalSection.ExitExecuteSection();
  193. }
  194. #endregion Insert patch into UnityEngine.CoreModule.dll
  195. loader.Debug("Ensuring Assembly-CSharp is virtualized");
  196. {
  197. var ascPath = Path.Combine(managedPath,
  198. "MainAssembly.dll"); // TODO: change to config option for other games
  199. #region Virtualize Assembly-CSharp.dll
  200. {
  201. CriticalSection.EnterExecuteSection();
  202. try
  203. {
  204. var ascModule = VirtualizedModule.Load(ascPath);
  205. ascModule.Virtualize(cAsmName, () => bkp?.Add(ascPath));
  206. }
  207. catch (Exception e)
  208. {
  209. loader.Error($"Could not virtualize {ascPath}");
  210. loader.Error(e);
  211. }
  212. CriticalSection.ExitExecuteSection();
  213. }
  214. #endregion Virtualize Assembly-CSharp.dll
  215. #region Anti-Yeet
  216. CriticalSection.EnterExecuteSection();
  217. try
  218. {
  219. loader.Debug("Applying anti-yeet patch");
  220. var ascAsmDef = AssemblyDefinition.ReadAssembly(ascPath, new ReaderParameters
  221. {
  222. ReadWrite = false,
  223. InMemory = true,
  224. ReadingMode = ReadingMode.Immediate
  225. });
  226. var ascModDef = ascAsmDef.MainModule;
  227. var deleter = ascModDef.GetType("IPAPluginsDirDeleter");
  228. deleter.Methods.Clear(); // delete all methods
  229. ascAsmDef.Write(ascPath);
  230. }
  231. catch (Exception)
  232. {
  233. // ignore
  234. }
  235. CriticalSection.ExitExecuteSection();
  236. #endregion
  237. }
  238. }
  239. private static bool bootstrapped;
  240. private static void CreateBootstrapper()
  241. {
  242. if (bootstrapped) return;
  243. bootstrapped = true;
  244. /*if (otherNewtonsoftJson != null)
  245. Assembly.LoadFrom(otherNewtonsoftJson);*/
  246. Application.logMessageReceived += delegate (string condition, string stackTrace, LogType type)
  247. {
  248. var level = UnityLogRedirector.LogTypeToLevel(type);
  249. UnityLogProvider.UnityLogger.Log(level, $"{condition}");
  250. UnityLogProvider.UnityLogger.Log(level, $"{stackTrace}");
  251. };
  252. // need to reinit streams singe Unity seems to redirect stdout
  253. StdoutInterceptor.RedirectConsole();
  254. var bootstrapper = new GameObject("NonDestructiveBootstrapper").AddComponent<Bootstrapper>();
  255. bootstrapper.Destroyed += Bootstrapper_Destroyed;
  256. }
  257. private static bool loadingDone;
  258. private static void Bootstrapper_Destroyed()
  259. {
  260. // wait for plugins to finish loading
  261. pluginAsyncLoadTask.Wait();
  262. permissionFixTask.Wait();
  263. BeatSaber.EnsureRuntimeGameVersion();
  264. log.Debug("Plugins loaded");
  265. log.Debug(string.Join(", ", PluginLoader.PluginsMetadata.StrJP()));
  266. PluginComponent.Create();
  267. }
  268. }
  269. }