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.

546 lines
22 KiB

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