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.

426 lines
17 KiB

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