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.

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