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.

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