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.

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