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.

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