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.

464 lines
17 KiB

5 years ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Diagnostics.CodeAnalysis;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Reflection;
  8. using System.Runtime.InteropServices;
  9. using System.Text.RegularExpressions;
  10. using System.Windows.Forms;
  11. using IPA.Patcher;
  12. namespace IPA
  13. {
  14. [SuppressMessage("ReSharper", "ClassNeverInstantiated.Global")]
  15. public class Program
  16. {
  17. [SuppressMessage("ReSharper", "InconsistentNaming")]
  18. public enum Architecture
  19. {
  20. x86,
  21. x64,
  22. Unknown
  23. }
  24. public static Version Version => Assembly.GetEntryAssembly().GetName().Version;
  25. public static readonly ArgumentFlag ArgHelp = new ArgumentFlag("--help", "-h") { DocString = "prints this message" };
  26. public static readonly ArgumentFlag ArgWaitFor = new ArgumentFlag("--waitfor", "-w") { DocString = "waits for the specified PID to exit", ValueString = "PID" };
  27. public static readonly ArgumentFlag ArgForce = new ArgumentFlag("--force", "-f") { DocString = "forces the operation to go through" };
  28. public static readonly ArgumentFlag ArgRevert = new ArgumentFlag("--revert", "-r") { DocString = "reverts the IPA installation" };
  29. public static readonly ArgumentFlag ArgNoWait = new ArgumentFlag("--nowait", "-n") { DocString = "doesn't wait for user input after the operation" };
  30. public static readonly ArgumentFlag ArgStart = new ArgumentFlag("--start", "-s") { DocString = "uses value_ as arguments to start the game after the patch/unpatch", ValueString = "ARGUMENTS" };
  31. public static readonly ArgumentFlag ArgLaunch = new ArgumentFlag("--launch", "-l") { DocString = "uses positional parameters as arguments to start the game after patch/unpatch" };
  32. //public static readonly ArgumentFlag ArgDestructive = new ArgumentFlag("--destructive", "-d") { DocString = "patches the game using the now outdated destructive methods" };
  33. [STAThread]
  34. public static void Main(string[] args)
  35. {
  36. Arguments.CmdLine.Flags(ArgHelp, ArgWaitFor, ArgForce, ArgRevert, ArgNoWait, ArgStart, ArgLaunch/*, ArgDestructive*/).Process();
  37. if (ArgHelp)
  38. {
  39. Arguments.CmdLine.PrintHelp();
  40. return;
  41. }
  42. try
  43. {
  44. if (ArgWaitFor.HasValue)
  45. { // wait for process if necessary
  46. var pid = int.Parse(ArgWaitFor.Value);
  47. try
  48. { // wait for beat saber to exit (ensures we can modify the file)
  49. var parent = Process.GetProcessById(pid);
  50. Console.WriteLine($"Waiting for parent ({pid}) process to die...");
  51. parent.WaitForExit();
  52. }
  53. catch (Exception)
  54. {
  55. // ignored
  56. }
  57. }
  58. PatchContext context = null;
  59. Assembly AssemblyLibLoader(object source, ResolveEventArgs e)
  60. {
  61. // ReSharper disable AccessToModifiedClosure
  62. if (context == null) return null;
  63. var libsDir = context.LibsPathSrc;
  64. // ReSharper enable AccessToModifiedClosure
  65. var asmName = new AssemblyName(e.Name);
  66. var testFile = Path.Combine(libsDir, $"{asmName.Name}.{asmName.Version}.dll");
  67. if (File.Exists(testFile))
  68. return Assembly.LoadFile(testFile);
  69. Console.WriteLine($"Could not load library {asmName}");
  70. return null;
  71. }
  72. AppDomain.CurrentDomain.AssemblyResolve += AssemblyLibLoader;
  73. var argExeName = Arguments.CmdLine.PositionalArgs.FirstOrDefault(s => s.EndsWith(".exe"));
  74. if (argExeName == null)
  75. context = PatchContext.Create(new DirectoryInfo(Directory.GetCurrentDirectory()).GetFiles()
  76. .First(o => o.Extension == ".exe" && o.FullName != Assembly.GetCallingAssembly().Location)
  77. .FullName);
  78. else
  79. context = PatchContext.Create(argExeName);
  80. // Sanitizing
  81. Validate(context);
  82. if (ArgRevert || Keyboard.IsKeyDown(Keys.LMenu))
  83. Revert(context);
  84. else
  85. {
  86. Install(context);
  87. StartIfNeedBe(context);
  88. }
  89. }
  90. catch (Exception e)
  91. {
  92. Fail(e.Message);
  93. }
  94. WaitForEnd();
  95. }
  96. private static void WaitForEnd()
  97. {
  98. if (!ArgNoWait)
  99. {
  100. Console.ForegroundColor = ConsoleColor.DarkYellow;
  101. Console.WriteLine("[Press any key to continue]");
  102. Console.ResetColor();
  103. Console.ReadKey();
  104. }
  105. }
  106. private static void Validate(PatchContext c)
  107. {
  108. if (!Directory.Exists(c.DataPathDst) || !File.Exists(c.EngineFile))
  109. {
  110. Fail("Game does not seem to be a Unity project. Could not find the libraries to patch.");
  111. Console.WriteLine($"DataPath: {c.DataPathDst}");
  112. Console.WriteLine($"EngineFile: {c.EngineFile}");
  113. }
  114. }
  115. private static void Install(PatchContext context)
  116. {
  117. try
  118. {
  119. var backup = new BackupUnit(context);
  120. Console.ForegroundColor = ConsoleColor.Cyan;
  121. Console.WriteLine("Restoring old version... ");
  122. if (BackupManager.HasBackup(context))
  123. BackupManager.Restore(context);
  124. var nativePluginFolder = Path.Combine(context.DataPathDst, "Plugins");
  125. bool isFlat = Directory.Exists(nativePluginFolder) &&
  126. Directory.GetFiles(nativePluginFolder).Any(f => f.EndsWith(".dll"));
  127. bool force = !BackupManager.HasBackup(context) || ArgForce;
  128. var architecture = DetectArchitecture(context.Executable);
  129. Console.ForegroundColor = ConsoleColor.DarkCyan;
  130. Console.WriteLine("Installing files... ");
  131. CopyAll(new DirectoryInfo(context.DataPathSrc), new DirectoryInfo(context.DataPathDst), force,
  132. backup,
  133. (from, to) => NativePluginInterceptor(from, to, new DirectoryInfo(nativePluginFolder), isFlat,
  134. architecture));
  135. CopyAll(new DirectoryInfo(context.LibsPathSrc), new DirectoryInfo(context.LibsPathDst), force,
  136. backup,
  137. (from, to) => NativePluginInterceptor(from, to, new DirectoryInfo(nativePluginFolder), isFlat,
  138. architecture));
  139. CopyAll(new DirectoryInfo(context.IPARoot), new DirectoryInfo(context.ProjectRoot), force,
  140. backup,
  141. null, false);
  142. //backup.Add(context.AssemblyFile);
  143. //backup.Add(context.EngineFile);
  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. }
  154. catch (Exception e)
  155. {
  156. Console.ForegroundColor = ConsoleColor.Red;
  157. Fail("Oops! This should not have happened.\n\n" + e);
  158. }
  159. Console.ResetColor();
  160. }
  161. private static void Revert(PatchContext context)
  162. {
  163. Console.ForegroundColor = ConsoleColor.Cyan;
  164. Console.Write("Restoring backup... ");
  165. if (BackupManager.Restore(context))
  166. {
  167. Console.WriteLine("Done!");
  168. }
  169. else
  170. {
  171. Console.WriteLine("Already vanilla or you removed your backups!");
  172. }
  173. if (File.Exists(context.ShortcutPath))
  174. {
  175. Console.WriteLine("Deleting shortcut...");
  176. File.Delete(context.ShortcutPath);
  177. }
  178. Console.WriteLine("");
  179. Console.WriteLine("--- Done reverting ---");
  180. Console.ResetColor();
  181. }
  182. private static void StartIfNeedBe(PatchContext context)
  183. {
  184. if (ArgStart.HasValue)
  185. {
  186. Process.Start(context.Executable, ArgStart.Value);
  187. }
  188. else
  189. {
  190. var argList = Arguments.CmdLine.PositionalArgs.ToList();
  191. argList.Remove(context.Executable);
  192. if (ArgLaunch)
  193. {
  194. Process.Start(context.Executable, Args(argList.ToArray()));
  195. }
  196. }
  197. }
  198. public static IEnumerable<FileInfo> NativePluginInterceptor(FileInfo from, FileInfo to,
  199. DirectoryInfo nativePluginFolder, bool isFlat, Architecture preferredArchitecture)
  200. {
  201. if (to.FullName.StartsWith(nativePluginFolder.FullName))
  202. {
  203. var relevantBit = to.FullName.Substring(nativePluginFolder.FullName.Length + 1);
  204. // Goes into the plugin folder!
  205. bool isFileFlat = !relevantBit.StartsWith("x86");
  206. if (isFlat && !isFileFlat)
  207. {
  208. // Flatten structure
  209. bool is64Bit = relevantBit.StartsWith("x86_64");
  210. if (!is64Bit && preferredArchitecture == Architecture.x86)
  211. {
  212. // 32 bit
  213. yield return new FileInfo(Path.Combine(nativePluginFolder.FullName,
  214. relevantBit.Substring("x86".Length + 1)));
  215. }
  216. else if (is64Bit && (preferredArchitecture == Architecture.x64 ||
  217. preferredArchitecture == Architecture.Unknown))
  218. {
  219. // 64 bit
  220. yield return new FileInfo(Path.Combine(nativePluginFolder.FullName,
  221. relevantBit.Substring("x86_64".Length + 1)));
  222. }
  223. }
  224. else if (!isFlat && isFileFlat)
  225. {
  226. // Deepen structure
  227. yield return new FileInfo(Path.Combine(Path.Combine(nativePluginFolder.FullName, "x86"),
  228. relevantBit));
  229. yield return new FileInfo(Path.Combine(Path.Combine(nativePluginFolder.FullName, "x86_64"),
  230. relevantBit));
  231. }
  232. else
  233. {
  234. yield return to;
  235. }
  236. }
  237. else
  238. {
  239. yield return to;
  240. }
  241. }
  242. public static void ClearLine()
  243. {
  244. if (IsConsole)
  245. {
  246. Console.SetCursorPosition(0, Console.CursorTop);
  247. int tpos = Console.CursorTop;
  248. Console.Write(new string(' ', Console.WindowWidth));
  249. Console.SetCursorPosition(0, tpos);
  250. }
  251. }
  252. private static IEnumerable<FileInfo> PassThroughInterceptor(FileInfo from, FileInfo to)
  253. {
  254. yield return to;
  255. }
  256. public static void CopyAll(DirectoryInfo source, DirectoryInfo target, bool aggressive, BackupUnit backup,
  257. Func<FileInfo, FileInfo, IEnumerable<FileInfo>> interceptor = null, bool recurse = true)
  258. {
  259. if (interceptor == null)
  260. {
  261. interceptor = PassThroughInterceptor;
  262. }
  263. // Copy each file into the new directory.
  264. foreach (var fi in source.GetFiles())
  265. {
  266. foreach (var targetFile in interceptor(fi, new FileInfo(Path.Combine(target.FullName, fi.Name))))
  267. {
  268. if (targetFile.Exists && targetFile.LastWriteTimeUtc >= fi.LastWriteTimeUtc && !aggressive)
  269. continue;
  270. Debug.Assert(targetFile.Directory != null, "targetFile.Directory != null");
  271. targetFile.Directory?.Create();
  272. LineBack();
  273. ClearLine();
  274. Console.WriteLine(@"Copying {0}", targetFile.FullName);
  275. backup.Add(targetFile);
  276. fi.CopyTo(targetFile.FullName, true);
  277. }
  278. }
  279. // Copy each subdirectory using recursion.
  280. if (!recurse) return;
  281. foreach (var diSourceSubDir in source.GetDirectories())
  282. {
  283. var nextTargetSubDir = new DirectoryInfo(Path.Combine(target.FullName, diSourceSubDir.Name));
  284. CopyAll(diSourceSubDir, nextTargetSubDir, aggressive, backup, interceptor);
  285. }
  286. }
  287. private static void Fail(string message)
  288. {
  289. Console.Error.WriteLine("ERROR: " + message);
  290. WaitForEnd();
  291. Environment.Exit(1);
  292. }
  293. public static string Args(params string[] args)
  294. {
  295. return string.Join(" ", args.Select(EncodeParameterArgument).ToArray());
  296. }
  297. /// <summary>
  298. /// Encodes an argument for passing into a program
  299. /// </summary>
  300. /// <param name="original">The value_ that should be received by the program</param>
  301. /// <returns>The value_ which needs to be passed to the program for the original value_
  302. /// to come through</returns>
  303. public static string EncodeParameterArgument(string original)
  304. {
  305. if (string.IsNullOrEmpty(original))
  306. return original;
  307. string value = Regex.Replace(original, @"(\\*)" + "\"", @"$1\$0");
  308. value = Regex.Replace(value, @"^(.*\s.*?)(\\*)$", "\"$1$2$2\"");
  309. return value;
  310. }
  311. public static Architecture DetectArchitecture(string assembly)
  312. {
  313. using (var reader = new BinaryReader(File.OpenRead(assembly)))
  314. {
  315. var header = reader.ReadUInt16();
  316. if (header == 0x5a4d)
  317. {
  318. reader.BaseStream.Seek(60, SeekOrigin.Begin); // this location contains the offset for the PE header
  319. var peOffset = reader.ReadUInt32();
  320. reader.BaseStream.Seek(peOffset + 4, SeekOrigin.Begin);
  321. var machine = reader.ReadUInt16();
  322. if (machine == 0x8664) // IMAGE_FILE_MACHINE_AMD64
  323. return Architecture.x64;
  324. if (machine == 0x014c) // IMAGE_FILE_MACHINE_I386
  325. return Architecture.x86;
  326. if (machine == 0x0200) // IMAGE_FILE_MACHINE_IA64
  327. return Architecture.x64;
  328. return Architecture.Unknown;
  329. }
  330. // Not a supported binary
  331. return Architecture.Unknown;
  332. }
  333. }
  334. public static void ResetLine()
  335. {
  336. if (IsConsole)
  337. Console.CursorLeft = 0;
  338. else
  339. Console.Write("\r");
  340. }
  341. public static void LineBack()
  342. {
  343. if (IsConsole)
  344. Console.CursorTop--;
  345. else
  346. Console.Write("\x1b[1A");
  347. }
  348. [DllImport("kernel32.dll")]
  349. private static extern IntPtr GetConsoleWindow();
  350. private static bool? isConsole;
  351. public static bool IsConsole
  352. {
  353. get
  354. {
  355. if (isConsole == null)
  356. isConsole = GetConsoleWindow() != IntPtr.Zero;
  357. return isConsole.Value;
  358. }
  359. }
  360. public abstract class Keyboard
  361. {
  362. [Flags]
  363. private enum KeyStates
  364. {
  365. None = 0,
  366. Down = 1,
  367. Toggled = 2
  368. }
  369. [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
  370. private static extern short GetKeyState(int keyCode);
  371. private static KeyStates KeyState(Keys key)
  372. {
  373. KeyStates state = KeyStates.None;
  374. short retVal = GetKeyState((int)key);
  375. //If the high-order bit is 1, the key is down
  376. //otherwise, it is up.
  377. if ((retVal & 0x8000) == 0x8000)
  378. state |= KeyStates.Down;
  379. //If the low-order bit is 1, the key is toggled.
  380. if ((retVal & 1) == 1)
  381. state |= KeyStates.Toggled;
  382. return state;
  383. }
  384. public static bool IsKeyDown(Keys key)
  385. {
  386. return KeyStates.Down == (KeyState(key) & KeyStates.Down);
  387. }
  388. public static bool IsKeyToggled(Keys key)
  389. {
  390. return KeyStates.Toggled == (KeyState(key) & KeyStates.Toggled);
  391. }
  392. }
  393. }
  394. }