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.

492 lines
19 KiB

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