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.

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