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.

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