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.

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