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.

271 lines
9.8 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. using IPA.Config;
  2. using IPA.Injector.Backups;
  3. using IPA.Loader;
  4. using IPA.Logging;
  5. using Mono.Cecil;
  6. using Mono.Cecil.Cil;
  7. using System;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Reflection;
  11. using System.Threading.Tasks;
  12. using UnityEngine;
  13. using static IPA.Logging.Logger;
  14. using MethodAttributes = Mono.Cecil.MethodAttributes;
  15. namespace IPA.Injector
  16. {
  17. // ReSharper disable once UnusedMember.Global
  18. public static class Injector
  19. {
  20. private static Task pluginAsyncLoadTask;
  21. // ReSharper disable once UnusedParameter.Global
  22. public static void Main(string[] args)
  23. { // entry point for doorstop
  24. // At this point, literally nothing but mscorlib is loaded,
  25. // and since this class doesn't have any static fields that
  26. // aren't defined in mscorlib, we can control exactly what
  27. // gets loaded.
  28. try
  29. {
  30. if (Environment.GetCommandLineArgs().Contains("--verbose"))
  31. WinConsole.Initialize();
  32. SetupLibraryLoading();
  33. EnsureDirectories();
  34. // this is weird, but it prevents Mono from having issues loading the type.
  35. // IMPORTANT: NO CALLS TO ANY LOGGER CAN HAPPEN BEFORE THIS
  36. var unused = StandardLogger.PrintFilter;
  37. #region // Above hack explaination
  38. /*
  39. * Due to an unknown bug in the version of Mono that Unity uses, if the first access to StandardLogger
  40. * is a call to a constructor, then Mono fails to load the type correctly. However, if the first access is to
  41. * the above static property (or maybe any, but I don't really know) it behaves as expected and works fine.
  42. */
  43. #endregion
  44. log.Debug("Initializing logger");
  45. SelfConfig.Load();
  46. DisabledConfig.Load();
  47. loader.Debug("Prepping bootstrapper");
  48. InstallBootstrapPatch();
  49. Updates.InstallPendingUpdates();
  50. LibLoader.SetupAssemblyFilenames(true);
  51. pluginAsyncLoadTask = PluginLoader.LoadTask();
  52. }
  53. catch (Exception e)
  54. {
  55. Console.WriteLine(e);
  56. }
  57. }
  58. private static void EnsureDirectories()
  59. {
  60. string path;
  61. if (!Directory.Exists(path = Path.Combine(Environment.CurrentDirectory, "UserData")))
  62. Directory.CreateDirectory(path);
  63. if (!Directory.Exists(path = Path.Combine(Environment.CurrentDirectory, "Plugins")))
  64. Directory.CreateDirectory(path);
  65. }
  66. private static void SetupLibraryLoading()
  67. {
  68. if (loadingDone) return;
  69. loadingDone = true;
  70. AppDomain.CurrentDomain.AssemblyResolve += LibLoader.AssemblyLibLoader;
  71. LibLoader.SetupAssemblyFilenames(true);
  72. }
  73. private static void InstallBootstrapPatch()
  74. {
  75. var cAsmName = Assembly.GetExecutingAssembly().GetName();
  76. var managedPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
  77. var dataDir = new DirectoryInfo(managedPath).Parent.Name;
  78. var gameName = dataDir.Substring(0, dataDir.Length - 5);
  79. loader.Debug("Finding backup");
  80. var backupPath = Path.Combine(Environment.CurrentDirectory, "IPA", "Backups", gameName);
  81. var bkp = BackupManager.FindLatestBackup(backupPath);
  82. if (bkp == null)
  83. loader.Warn("No backup found! Was BSIPA installed using the installer?");
  84. loader.Debug("Ensuring patch on UnityEngine.CoreModule exists");
  85. #region Insert patch into UnityEngine.CoreModule.dll
  86. {
  87. var unityPath = Path.Combine(managedPath,
  88. "UnityEngine.CoreModule.dll");
  89. var unityAsmDef = AssemblyDefinition.ReadAssembly(unityPath, new ReaderParameters
  90. {
  91. ReadWrite = false,
  92. InMemory = true,
  93. ReadingMode = ReadingMode.Immediate
  94. });
  95. var unityModDef = unityAsmDef.MainModule;
  96. bool modified = false;
  97. foreach (var asmref in unityModDef.AssemblyReferences)
  98. {
  99. if (asmref.Name == cAsmName.Name)
  100. {
  101. if (asmref.Version != cAsmName.Version)
  102. {
  103. asmref.Version = cAsmName.Version;
  104. modified = true;
  105. }
  106. }
  107. }
  108. var application = unityModDef.GetType("UnityEngine", "Application");
  109. MethodDefinition cctor = null;
  110. foreach (var m in application.Methods)
  111. if (m.IsRuntimeSpecialName && m.Name == ".cctor")
  112. cctor = m;
  113. var cbs = unityModDef.ImportReference(((Action)CreateBootstrapper).Method);
  114. if (cctor == null)
  115. {
  116. cctor = new MethodDefinition(".cctor",
  117. MethodAttributes.RTSpecialName | MethodAttributes.Static | MethodAttributes.SpecialName,
  118. unityModDef.TypeSystem.Void);
  119. application.Methods.Add(cctor);
  120. modified = true;
  121. var ilp = cctor.Body.GetILProcessor();
  122. ilp.Emit(OpCodes.Call, cbs);
  123. ilp.Emit(OpCodes.Ret);
  124. }
  125. else
  126. {
  127. var ilp = cctor.Body.GetILProcessor();
  128. for (var i = 0; i < Math.Min(2, cctor.Body.Instructions.Count); i++)
  129. {
  130. var ins = cctor.Body.Instructions[i];
  131. switch (i)
  132. {
  133. case 0 when ins.OpCode != OpCodes.Call:
  134. ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs));
  135. modified = true;
  136. break;
  137. case 0:
  138. {
  139. var methodRef = ins.Operand as MethodReference;
  140. if (methodRef?.FullName != cbs.FullName)
  141. {
  142. ilp.Replace(ins, ilp.Create(OpCodes.Call, cbs));
  143. modified = true;
  144. }
  145. break;
  146. }
  147. case 1 when ins.OpCode != OpCodes.Ret:
  148. ilp.Replace(ins, ilp.Create(OpCodes.Ret));
  149. modified = true;
  150. break;
  151. }
  152. }
  153. }
  154. if (modified)
  155. {
  156. bkp?.Add(unityPath);
  157. unityAsmDef.Write(unityPath);
  158. }
  159. /*else
  160. return; // shortcut*/
  161. }
  162. #endregion Insert patch into UnityEngine.CoreModule.dll
  163. loader.Debug("Ensuring Assembly-CSharp is virtualized");
  164. {
  165. var ascPath = Path.Combine(managedPath,
  166. "Assembly-CSharp.dll");
  167. #region Virtualize Assembly-CSharp.dll
  168. {
  169. var ascModule = VirtualizedModule.Load(ascPath);
  170. ascModule.Virtualize(cAsmName, () => bkp?.Add(ascPath));
  171. }
  172. #endregion Virtualize Assembly-CSharp.dll
  173. #region Anti-Yeet
  174. //if (SelfConfig.SelfConfigRef.Value.ApplyAntiYeet)
  175. try
  176. {
  177. loader.Debug("Applying anti-yeet patch");
  178. var ascAsmDef = AssemblyDefinition.ReadAssembly(ascPath, new ReaderParameters
  179. {
  180. ReadWrite = false,
  181. InMemory = true,
  182. ReadingMode = ReadingMode.Immediate
  183. });
  184. var ascModDef = ascAsmDef.MainModule;
  185. var deleter = ascModDef.GetType("IPAPluginsDirDeleter");
  186. deleter.Methods.Clear(); // delete all methods
  187. ascAsmDef.Write(ascPath);
  188. }
  189. catch (Exception)
  190. {
  191. // ignore
  192. }
  193. #endregion
  194. }
  195. }
  196. private static bool bootstrapped;
  197. private static void CreateBootstrapper()
  198. {
  199. if (bootstrapped) return;
  200. bootstrapped = true;
  201. Application.logMessageReceived += delegate (string condition, string stackTrace, LogType type)
  202. {
  203. var level = UnityLogRedirector.LogTypeToLevel(type);
  204. UnityLogProvider.UnityLogger.Log(level, $"{condition}");
  205. UnityLogProvider.UnityLogger.Log(level, $"{stackTrace}");
  206. };
  207. // need to reinit streams singe Unity seems to redirect stdout
  208. StdoutInterceptor.RedirectConsole();
  209. var bootstrapper = new GameObject("NonDestructiveBootstrapper").AddComponent<Bootstrapper>();
  210. bootstrapper.Destroyed += Bootstrapper_Destroyed;
  211. }
  212. private static bool loadingDone;
  213. private static void Bootstrapper_Destroyed()
  214. {
  215. // wait for plugins to finish loading
  216. pluginAsyncLoadTask.Wait();
  217. log.Debug("Plugins loaded");
  218. log.Debug(string.Join(", ", PluginLoader.PluginsMetadata));
  219. PluginComponent.Create();
  220. }
  221. }
  222. }