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.

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