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.

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