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.

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