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.

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