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.

439 lines
18 KiB

  1. using IPA.Patcher;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Reflection;
  8. using System.Runtime.InteropServices;
  9. using System.Text;
  10. using System.Text.RegularExpressions;
  11. using System.Windows.Forms;
  12. using IPA.ArgParsing;
  13. namespace IPA {
  14. public class Program {
  15. public enum Architecture {
  16. x86,
  17. x64,
  18. Unknown
  19. }
  20. private static Version Version => Assembly.GetEntryAssembly().GetName().Version;
  21. public static ArgumentFlag ArgHelp = new ArgumentFlag("--help", "-h") { DocString = "prints this message" };
  22. public static ArgumentFlag ArgWaitFor = new ArgumentFlag("--waitfor") { DocString = "waits for the specified PID to exit" };
  23. public static ArgumentFlag ArgForce = new ArgumentFlag("--force", "-f") { DocString = "forces the operation to go through" };
  24. public static ArgumentFlag ArgRevert = new ArgumentFlag("--revert") { DocString = "reverts the IPA installation" };
  25. public static ArgumentFlag ArgNoWait = new ArgumentFlag("--nowait") { DocString = "doesn't wait for user input after the operation" };
  26. public static ArgumentFlag ArgStart = new ArgumentFlag("--start") { DocString = "uses value as arguments to start the game after the patch/unpatch" };
  27. public static ArgumentFlag ArgLaunch = new ArgumentFlag("--launch") { DocString = "uses positional parameters as arguments to start the game after patch/unpatch" };
  28. static void Main(string[] args)
  29. {
  30. Arguments.CmdLine.Flags(ArgHelp, ArgWaitFor, ArgForce, ArgRevert, ArgNoWait, ArgStart, ArgLaunch).Process();
  31. if (ArgHelp)
  32. {
  33. Arguments.CmdLine.PrintHelp();
  34. return;
  35. }
  36. try
  37. {
  38. if (ArgWaitFor && ArgWaitFor.Value != null)
  39. {
  40. int pid = int.Parse(ArgWaitFor.Value);
  41. try
  42. { // wait for beat saber to exit (ensures we can modify the file)
  43. var parent = Process.GetProcessById(pid);
  44. Console.WriteLine($"Waiting for parent ({pid}) process to die...");
  45. parent.WaitForExit();
  46. }
  47. catch (Exception) { }
  48. }
  49. PatchContext context;
  50. var argExeName = Arguments.CmdLine.PositionalArgs.FirstOrDefault(s => s.EndsWith(".exe"));
  51. if (argExeName == null)
  52. {
  53. //Fail("Drag an (executable) file on the exe!");
  54. context = PatchContext.Create(new DirectoryInfo(Directory.GetCurrentDirectory()).GetFiles()
  55. .First(o => o.FullName.EndsWith(".exe"))
  56. .FullName);
  57. }
  58. else
  59. {
  60. context = PatchContext.Create(argExeName);
  61. }
  62. bool isRevert = ArgRevert || Keyboard.IsKeyDown(Keys.LMenu);
  63. // Sanitizing
  64. Validate(context);
  65. if (isRevert)
  66. {
  67. Revert(context);
  68. }
  69. else
  70. {
  71. Install(context);
  72. StartIfNeedBe(context);
  73. }
  74. }
  75. catch (Exception e) {
  76. Fail(e.Message);
  77. }
  78. }
  79. private static void Validate(PatchContext c) {
  80. if (!Directory.Exists(c.DataPathDst) || !File.Exists(c.EngineFile)) {
  81. Fail("Game does not seem to be a Unity project. Could not find the libraries to patch.");
  82. Console.WriteLine($"DataPath: {c.DataPathDst}");
  83. Console.WriteLine($"EngineFile: {c.EngineFile}");
  84. }
  85. }
  86. private static void Install(PatchContext context) {
  87. try {
  88. var backup = new BackupUnit(context);
  89. #region Patch Version Check
  90. var patchedModule = PatchedModule.Load(context.EngineFile);
  91. var isCurrentNewer = Version.CompareTo(patchedModule.Data.Version) > 0;
  92. Console.WriteLine($"Current: {Version} Patched: {patchedModule.Data.Version}");
  93. if (isCurrentNewer) {
  94. Console.ForegroundColor = ConsoleColor.White;
  95. Console.WriteLine(
  96. $"Preparing for update, {(patchedModule.Data.Version == null ? "UnPatched" : patchedModule.Data.Version.ToString())} => {Version}");
  97. Console.WriteLine("--- Starting ---");
  98. Revert(context, new[] {"newVersion"});
  99. Console.ResetColor();
  100. #region File Copying
  101. Console.ForegroundColor = ConsoleColor.Magenta;
  102. Console.WriteLine("Updating files... ");
  103. var nativePluginFolder = Path.Combine(context.DataPathDst, "Plugins");
  104. bool isFlat = Directory.Exists(nativePluginFolder) &&
  105. Directory.GetFiles(nativePluginFolder).Any(f => f.EndsWith(".dll"));
  106. bool force = !BackupManager.HasBackup(context) || ArgForce;
  107. var architecture = DetectArchitecture(context.Executable);
  108. Console.WriteLine("Architecture: {0}", architecture);
  109. CopyAll(new DirectoryInfo(context.DataPathSrc), new DirectoryInfo(context.DataPathDst), force,
  110. backup,
  111. (from, to) => NativePluginInterceptor(from, to, new DirectoryInfo(nativePluginFolder), isFlat,
  112. architecture));
  113. CopyAll(new DirectoryInfo(context.LibsPathSrc), new DirectoryInfo(context.LibsPathDst), force,
  114. backup,
  115. (from, to) => NativePluginInterceptor(from, to, new DirectoryInfo(nativePluginFolder), isFlat,
  116. architecture));
  117. Console.WriteLine("Successfully updated files!");
  118. #endregion
  119. }
  120. else {
  121. Console.ForegroundColor = ConsoleColor.Red;
  122. Console.WriteLine($"Files up to date @ Version {Version}!");
  123. Console.ResetColor();
  124. }
  125. #endregion
  126. #region Create Plugin Folder
  127. if (!Directory.Exists(context.PluginsFolder)) {
  128. Console.ForegroundColor = ConsoleColor.DarkYellow;
  129. Console.WriteLine("Creating plugins folder... ");
  130. Directory.CreateDirectory(context.PluginsFolder);
  131. Console.ResetColor();
  132. }
  133. #endregion
  134. #region Patching
  135. if (!patchedModule.Data.IsPatched || isCurrentNewer) {
  136. Console.ForegroundColor = ConsoleColor.Yellow;
  137. Console.WriteLine($"Patching UnityEngine.dll with Version {Application.ProductVersion}... ");
  138. backup.Add(context.EngineFile);
  139. patchedModule.Patch(Version);
  140. Console.WriteLine("Done!");
  141. Console.ResetColor();
  142. }
  143. #endregion
  144. #region Virtualizing
  145. if (File.Exists(context.AssemblyFile)) {
  146. var virtualizedModule = VirtualizedModule.Load(context.AssemblyFile);
  147. if (!virtualizedModule.IsVirtualized) {
  148. Console.ForegroundColor = ConsoleColor.Blue;
  149. Console.WriteLine("Virtualizing Assembly-Csharp.dll... ");
  150. backup.Add(context.AssemblyFile);
  151. virtualizedModule.Virtualize();
  152. Console.WriteLine("Done!");
  153. Console.ResetColor();
  154. }
  155. }
  156. #endregion
  157. #region Creating shortcut
  158. /*if(!File.Exists(context.ShortcutPath))
  159. {
  160. Console.Write("Creating shortcut to IPA ({0})... ", context.IPA);
  161. try
  162. {
  163. Shortcut.Create(
  164. fileName: context.ShortcutPath,
  165. targetPath: context.IPA,
  166. arguments: Args(context.Executable, "--launch"),
  167. workingDirectory: context.ProjectRoot,
  168. description: "Launches the game and makes sure it's in a patched state",
  169. hotkey: "",
  170. iconPath: context.Executable
  171. );
  172. Console.WriteLine("Created");
  173. } catch (Exception e)
  174. {
  175. Console.Error.WriteLine("Failed to create shortcut, but game was patched!");
  176. }
  177. }*/
  178. #endregion
  179. }
  180. catch (Exception e) {
  181. Fail("Oops! This should not have happened.\n\n" + e);
  182. }
  183. if (!ArgNoWait)
  184. {
  185. Console.ForegroundColor = ConsoleColor.Green;
  186. Console.WriteLine("Finished!");
  187. Console.ResetColor();
  188. Console.ReadLine();
  189. }
  190. }
  191. private static void Revert(PatchContext context, string[] args = null) {
  192. Console.ForegroundColor = ConsoleColor.Cyan;
  193. bool isNewVersion = (args != null && args.Contains("newVersion"));
  194. Console.Write("Restoring backup... ");
  195. if (BackupManager.Restore(context)) {
  196. Console.WriteLine("Done!");
  197. }
  198. else {
  199. Console.WriteLine("Already vanilla or you removed your backups!");
  200. }
  201. if (File.Exists(context.ShortcutPath)) {
  202. Console.WriteLine("Deleting shortcut...");
  203. File.Delete(context.ShortcutPath);
  204. }
  205. Console.WriteLine("");
  206. Console.WriteLine("--- Done reverting ---");
  207. if (!ArgNoWait && !isNewVersion) {
  208. Console.WriteLine("\n\n[Press any key to quit]");
  209. Console.ReadKey();
  210. }
  211. Console.ResetColor();
  212. }
  213. private static void StartIfNeedBe(PatchContext context) {
  214. if (ArgStart && ArgStart.Value != null)
  215. {
  216. Process.Start(context.Executable, ArgStart.Value);
  217. }
  218. else
  219. {
  220. var argList = Arguments.CmdLine.PositionalArgs.ToList();
  221. argList.Remove(context.Executable);
  222. if (ArgLaunch)
  223. {
  224. Process.Start(context.Executable, Args(argList.ToArray()));
  225. }
  226. }
  227. }
  228. public static IEnumerable<FileInfo> NativePluginInterceptor(FileInfo from, FileInfo to,
  229. DirectoryInfo nativePluginFolder, bool isFlat, Architecture preferredArchitecture) {
  230. if (to.FullName.StartsWith(nativePluginFolder.FullName)) {
  231. var relevantBit = to.FullName.Substring(nativePluginFolder.FullName.Length + 1);
  232. // Goes into the plugin folder!
  233. bool isFileFlat = !relevantBit.StartsWith("x86");
  234. if (isFlat && !isFileFlat) {
  235. // Flatten structure
  236. bool is64Bit = relevantBit.StartsWith("x86_64");
  237. if (!is64Bit && preferredArchitecture == Architecture.x86) {
  238. // 32 bit
  239. yield return new FileInfo(Path.Combine(nativePluginFolder.FullName,
  240. relevantBit.Substring("x86".Length + 1)));
  241. }
  242. else if (is64Bit && (preferredArchitecture == Architecture.x64 ||
  243. preferredArchitecture == Architecture.Unknown)) {
  244. // 64 bit
  245. yield return new FileInfo(Path.Combine(nativePluginFolder.FullName,
  246. relevantBit.Substring("x86_64".Length + 1)));
  247. }
  248. else {
  249. // Throw away
  250. yield break;
  251. }
  252. }
  253. else if (!isFlat && isFileFlat) {
  254. // Deepen structure
  255. yield return new FileInfo(Path.Combine(Path.Combine(nativePluginFolder.FullName, "x86"),
  256. relevantBit));
  257. yield return new FileInfo(Path.Combine(Path.Combine(nativePluginFolder.FullName, "x86_64"),
  258. relevantBit));
  259. }
  260. else {
  261. yield return to;
  262. }
  263. }
  264. else {
  265. yield return to;
  266. }
  267. }
  268. private static IEnumerable<FileInfo> PassThroughInterceptor(FileInfo from, FileInfo to) {
  269. yield return to;
  270. }
  271. public static void CopyAll(DirectoryInfo source, DirectoryInfo target, bool aggressive, BackupUnit backup,
  272. Func<FileInfo, FileInfo, IEnumerable<FileInfo>> interceptor = null) {
  273. if (interceptor == null) {
  274. interceptor = PassThroughInterceptor;
  275. }
  276. // Copy each file into the new directory.
  277. foreach (FileInfo fi in source.GetFiles()) {
  278. foreach (var targetFile in interceptor(fi, new FileInfo(Path.Combine(target.FullName, fi.Name)))) {
  279. if (!targetFile.Exists || targetFile.LastWriteTimeUtc < fi.LastWriteTimeUtc || aggressive) {
  280. targetFile.Directory.Create();
  281. Console.WriteLine(@"Copying {0}", targetFile.FullName);
  282. backup.Add(targetFile);
  283. fi.CopyTo(targetFile.FullName, true);
  284. }
  285. }
  286. }
  287. // Copy each subdirectory using recursion.
  288. foreach (DirectoryInfo diSourceSubDir in source.GetDirectories()) {
  289. DirectoryInfo nextTargetSubDir = new DirectoryInfo(Path.Combine(target.FullName, diSourceSubDir.Name));
  290. CopyAll(diSourceSubDir, nextTargetSubDir, aggressive, backup, interceptor);
  291. }
  292. }
  293. static void Fail(string message) {
  294. Console.Error.Write("ERROR: " + message);
  295. if (!ArgNoWait) {
  296. Console.WriteLine("\n\n[Press any key to quit]");
  297. Console.ReadKey();
  298. }
  299. Environment.Exit(1);
  300. }
  301. public static string Args(params string[] args) {
  302. return string.Join(" ", args.Select(EncodeParameterArgument).ToArray());
  303. }
  304. /// <summary>
  305. /// Encodes an argument for passing into a program
  306. /// </summary>
  307. /// <param name="original">The value that should be received by the program</param>
  308. /// <returns>The value which needs to be passed to the program for the original value
  309. /// to come through</returns>
  310. public static string EncodeParameterArgument(string original) {
  311. if (string.IsNullOrEmpty(original))
  312. return original;
  313. string value = Regex.Replace(original, @"(\\*)" + "\"", @"$1\$0");
  314. value = Regex.Replace(value, @"^(.*\s.*?)(\\*)$", "\"$1$2$2\"");
  315. return value;
  316. }
  317. public static Architecture DetectArchitecture(string assembly) {
  318. using (var reader = new BinaryReader(File.OpenRead(assembly))) {
  319. var header = reader.ReadUInt16();
  320. if (header == 0x5a4d) {
  321. reader.BaseStream.Seek(60, SeekOrigin.Begin); // this location contains the offset for the PE header
  322. var peOffset = reader.ReadUInt32();
  323. reader.BaseStream.Seek(peOffset + 4, SeekOrigin.Begin);
  324. var machine = reader.ReadUInt16();
  325. if (machine == 0x8664) // IMAGE_FILE_MACHINE_AMD64
  326. return Architecture.x64;
  327. else if (machine == 0x014c) // IMAGE_FILE_MACHINE_I386
  328. return Architecture.x86;
  329. else if (machine == 0x0200) // IMAGE_FILE_MACHINE_IA64
  330. return Architecture.x64;
  331. else
  332. return Architecture.Unknown;
  333. }
  334. else {
  335. // Not a supported binary
  336. return Architecture.Unknown;
  337. }
  338. }
  339. }
  340. public abstract class Keyboard {
  341. [Flags]
  342. private enum KeyStates {
  343. None = 0,
  344. Down = 1,
  345. Toggled = 2
  346. }
  347. [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
  348. private static extern short GetKeyState(int keyCode);
  349. private static KeyStates GetKeyState(Keys key) {
  350. KeyStates state = KeyStates.None;
  351. short retVal = GetKeyState((int) key);
  352. //If the high-order bit is 1, the key is down
  353. //otherwise, it is up.
  354. if ((retVal & 0x8000) == 0x8000)
  355. state |= KeyStates.Down;
  356. //If the low-order bit is 1, the key is toggled.
  357. if ((retVal & 1) == 1)
  358. state |= KeyStates.Toggled;
  359. return state;
  360. }
  361. public static bool IsKeyDown(Keys key) {
  362. return KeyStates.Down == (GetKeyState(key) & KeyStates.Down);
  363. }
  364. public static bool IsKeyToggled(Keys key) {
  365. return KeyStates.Toggled == (GetKeyState(key) & KeyStates.Toggled);
  366. }
  367. }
  368. }
  369. }