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.

543 lines
22 KiB

6 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. }
  220. #region Create Plugin Folder
  221. if (!Directory.Exists(context.PluginsFolder))
  222. {
  223. Console.ForegroundColor = ConsoleColor.DarkYellow;
  224. Console.WriteLine("Creating plugins folder... ");
  225. Directory.CreateDirectory(context.PluginsFolder);
  226. Console.ResetColor();
  227. }
  228. #endregion
  229. #region Virtualizing
  230. if (ArgDestructive && File.Exists(context.AssemblyFile))
  231. {
  232. var virtualizedModule = VirtualizedModule.Load(context.AssemblyFile);
  233. if (!virtualizedModule.IsVirtualized)
  234. {
  235. Console.ForegroundColor = ConsoleColor.Green;
  236. Console.WriteLine("Virtualizing Assembly-Csharp.dll... ");
  237. backup.Add(context.AssemblyFile);
  238. virtualizedModule.Virtualize();
  239. Console.WriteLine("Done!");
  240. Console.ResetColor();
  241. }
  242. }
  243. #endregion
  244. }
  245. catch (Exception e)
  246. {
  247. Console.ForegroundColor = ConsoleColor.Red;
  248. Fail("Oops! This should not have happened.\n\n" + e);
  249. }
  250. Console.ResetColor();
  251. }
  252. private static void Revert(PatchContext context)
  253. {
  254. Console.ForegroundColor = ConsoleColor.Cyan;
  255. Console.Write("Restoring backup... ");
  256. if (BackupManager.Restore(context))
  257. {
  258. Console.WriteLine("Done!");
  259. }
  260. else
  261. {
  262. Console.WriteLine("Already vanilla or you removed your backups!");
  263. }
  264. if (File.Exists(context.ShortcutPath))
  265. {
  266. Console.WriteLine("Deleting shortcut...");
  267. File.Delete(context.ShortcutPath);
  268. }
  269. Console.WriteLine("");
  270. Console.WriteLine("--- Done reverting ---");
  271. Console.ResetColor();
  272. }
  273. private static void StartIfNeedBe(PatchContext context)
  274. {
  275. if (ArgStart.HasValue)
  276. {
  277. Process.Start(context.Executable, ArgStart.Value);
  278. }
  279. else
  280. {
  281. var argList = Arguments.CmdLine.PositionalArgs.ToList();
  282. argList.Remove(context.Executable);
  283. if (ArgLaunch)
  284. {
  285. Process.Start(context.Executable, Args(argList.ToArray()));
  286. }
  287. }
  288. }
  289. public static IEnumerable<FileInfo> NativePluginInterceptor(FileInfo from, FileInfo to,
  290. DirectoryInfo nativePluginFolder, bool isFlat, Architecture preferredArchitecture)
  291. {
  292. if (to.FullName.StartsWith(nativePluginFolder.FullName))
  293. {
  294. var relevantBit = to.FullName.Substring(nativePluginFolder.FullName.Length + 1);
  295. // Goes into the plugin folder!
  296. bool isFileFlat = !relevantBit.StartsWith("x86");
  297. if (isFlat && !isFileFlat)
  298. {
  299. // Flatten structure
  300. bool is64Bit = relevantBit.StartsWith("x86_64");
  301. if (!is64Bit && preferredArchitecture == Architecture.x86)
  302. {
  303. // 32 bit
  304. yield return new FileInfo(Path.Combine(nativePluginFolder.FullName,
  305. relevantBit.Substring("x86".Length + 1)));
  306. }
  307. else if (is64Bit && (preferredArchitecture == Architecture.x64 ||
  308. preferredArchitecture == Architecture.Unknown))
  309. {
  310. // 64 bit
  311. yield return new FileInfo(Path.Combine(nativePluginFolder.FullName,
  312. relevantBit.Substring("x86_64".Length + 1)));
  313. }
  314. else
  315. {
  316. // Throw away
  317. yield break;
  318. }
  319. }
  320. else if (!isFlat && isFileFlat)
  321. {
  322. // Deepen structure
  323. yield return new FileInfo(Path.Combine(Path.Combine(nativePluginFolder.FullName, "x86"),
  324. relevantBit));
  325. yield return new FileInfo(Path.Combine(Path.Combine(nativePluginFolder.FullName, "x86_64"),
  326. relevantBit));
  327. }
  328. else
  329. {
  330. yield return to;
  331. }
  332. }
  333. else
  334. {
  335. yield return to;
  336. }
  337. }
  338. public static void ClearLine()
  339. {
  340. Console.SetCursorPosition(0, Console.CursorTop);
  341. int tpos = Console.CursorTop;
  342. Console.Write(new string(' ', Console.WindowWidth));
  343. Console.SetCursorPosition(0, tpos);
  344. }
  345. private static IEnumerable<FileInfo> PassThroughInterceptor(FileInfo from, FileInfo to)
  346. {
  347. yield return to;
  348. }
  349. public static void CopyAll(DirectoryInfo source, DirectoryInfo target, bool aggressive, BackupUnit backup,
  350. Func<FileInfo, FileInfo, IEnumerable<FileInfo>> interceptor = null, bool recurse = true)
  351. {
  352. if (interceptor == null)
  353. {
  354. interceptor = PassThroughInterceptor;
  355. }
  356. // Copy each file into the new directory.
  357. foreach (FileInfo fi in source.GetFiles())
  358. {
  359. foreach (var targetFile in interceptor(fi, new FileInfo(Path.Combine(target.FullName, fi.Name))))
  360. {
  361. if (!targetFile.Exists || targetFile.LastWriteTimeUtc < fi.LastWriteTimeUtc || aggressive)
  362. {
  363. targetFile.Directory.Create();
  364. Console.CursorTop--;
  365. ClearLine();
  366. Console.WriteLine(@"Copying {0}", targetFile.FullName);
  367. backup.Add(targetFile);
  368. fi.CopyTo(targetFile.FullName, true);
  369. }
  370. }
  371. }
  372. // Copy each subdirectory using recursion.
  373. if (recurse)
  374. foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
  375. {
  376. DirectoryInfo nextTargetSubDir = new DirectoryInfo(Path.Combine(target.FullName, diSourceSubDir.Name));
  377. CopyAll(diSourceSubDir, nextTargetSubDir, aggressive, backup, interceptor, recurse);
  378. }
  379. }
  380. static void Fail(string message)
  381. {
  382. Console.Error.WriteLine("ERROR: " + message);
  383. WaitForEnd();
  384. Environment.Exit(1);
  385. }
  386. public static string Args(params string[] args)
  387. {
  388. return string.Join(" ", args.Select(EncodeParameterArgument).ToArray());
  389. }
  390. /// <summary>
  391. /// Encodes an argument for passing into a program
  392. /// </summary>
  393. /// <param name="original">The value that should be received by the program</param>
  394. /// <returns>The value which needs to be passed to the program for the original value
  395. /// to come through</returns>
  396. public static string EncodeParameterArgument(string original)
  397. {
  398. if (string.IsNullOrEmpty(original))
  399. return original;
  400. string value = Regex.Replace(original, @"(\\*)" + "\"", @"$1\$0");
  401. value = Regex.Replace(value, @"^(.*\s.*?)(\\*)$", "\"$1$2$2\"");
  402. return value;
  403. }
  404. public static Architecture DetectArchitecture(string assembly)
  405. {
  406. using (var reader = new BinaryReader(File.OpenRead(assembly)))
  407. {
  408. var header = reader.ReadUInt16();
  409. if (header == 0x5a4d)
  410. {
  411. reader.BaseStream.Seek(60, SeekOrigin.Begin); // this location contains the offset for the PE header
  412. var peOffset = reader.ReadUInt32();
  413. reader.BaseStream.Seek(peOffset + 4, SeekOrigin.Begin);
  414. var machine = reader.ReadUInt16();
  415. if (machine == 0x8664) // IMAGE_FILE_MACHINE_AMD64
  416. return Architecture.x64;
  417. else if (machine == 0x014c) // IMAGE_FILE_MACHINE_I386
  418. return Architecture.x86;
  419. else if (machine == 0x0200) // IMAGE_FILE_MACHINE_IA64
  420. return Architecture.x64;
  421. else
  422. return Architecture.Unknown;
  423. }
  424. else
  425. {
  426. // Not a supported binary
  427. return Architecture.Unknown;
  428. }
  429. }
  430. }
  431. public abstract class Keyboard
  432. {
  433. [Flags]
  434. private enum KeyStates
  435. {
  436. None = 0,
  437. Down = 1,
  438. Toggled = 2
  439. }
  440. [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
  441. private static extern short GetKeyState(int keyCode);
  442. private static KeyStates GetKeyState(Keys key)
  443. {
  444. KeyStates state = KeyStates.None;
  445. short retVal = GetKeyState((int)key);
  446. //If the high-order bit is 1, the key is down
  447. //otherwise, it is up.
  448. if ((retVal & 0x8000) == 0x8000)
  449. state |= KeyStates.Down;
  450. //If the low-order bit is 1, the key is toggled.
  451. if ((retVal & 1) == 1)
  452. state |= KeyStates.Toggled;
  453. return state;
  454. }
  455. public static bool IsKeyDown(Keys key)
  456. {
  457. return KeyStates.Down == (GetKeyState(key) & KeyStates.Down);
  458. }
  459. public static bool IsKeyToggled(Keys key)
  460. {
  461. return KeyStates.Toggled == (GetKeyState(key) & KeyStates.Toggled);
  462. }
  463. }
  464. }
  465. }