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.

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