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.

429 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. if (!Environment.CommandLine.Contains("--nowait"))
  171. {
  172. Console.ForegroundColor = ConsoleColor.Green;
  173. Console.WriteLine("Finished!");
  174. Console.ResetColor();
  175. Console.ReadLine();
  176. }
  177. }
  178. private static void Revert(PatchContext context, string[] args = null) {
  179. Console.ForegroundColor = ConsoleColor.Cyan;
  180. bool isNewVersion = (args != null && args.Contains("newVersion"));
  181. Console.Write("Restoring backup... ");
  182. if (BackupManager.Restore(context)) {
  183. Console.WriteLine("Done!");
  184. }
  185. else {
  186. Console.WriteLine("Already vanilla or you removed your backups!");
  187. }
  188. if (File.Exists(context.ShortcutPath)) {
  189. Console.WriteLine("Deleting shortcut...");
  190. File.Delete(context.ShortcutPath);
  191. }
  192. Console.WriteLine("");
  193. Console.WriteLine("--- Done reverting ---");
  194. if (!Environment.CommandLine.Contains("--nowait") && !isNewVersion) {
  195. Console.WriteLine("\n\n[Press any key to quit]");
  196. Console.ReadKey();
  197. }
  198. Console.ResetColor();
  199. }
  200. private static void StartIfNeedBe(PatchContext context) {
  201. string startArg = context.Args.FirstOrDefault(s => s.StartsWith("--start="));
  202. if (startArg != null)
  203. {
  204. var cmdlineSplit = startArg.Split('=').ToList();
  205. cmdlineSplit.RemoveAt(0); // remove first
  206. var cmdline = string.Join("=", cmdlineSplit);
  207. Process.Start(context.Executable, cmdline);
  208. }
  209. else
  210. {
  211. var argList = context.Args.ToList();
  212. bool launch = argList.Remove("--launch");
  213. argList.Remove(context.Executable);
  214. if (launch)
  215. {
  216. Process.Start(context.Executable, Args(argList.ToArray()));
  217. }
  218. }
  219. }
  220. public static IEnumerable<FileInfo> NativePluginInterceptor(FileInfo from, FileInfo to,
  221. DirectoryInfo nativePluginFolder, bool isFlat, Architecture preferredArchitecture) {
  222. if (to.FullName.StartsWith(nativePluginFolder.FullName)) {
  223. var relevantBit = to.FullName.Substring(nativePluginFolder.FullName.Length + 1);
  224. // Goes into the plugin folder!
  225. bool isFileFlat = !relevantBit.StartsWith("x86");
  226. if (isFlat && !isFileFlat) {
  227. // Flatten structure
  228. bool is64Bit = relevantBit.StartsWith("x86_64");
  229. if (!is64Bit && preferredArchitecture == Architecture.x86) {
  230. // 32 bit
  231. yield return new FileInfo(Path.Combine(nativePluginFolder.FullName,
  232. relevantBit.Substring("x86".Length + 1)));
  233. }
  234. else if (is64Bit && (preferredArchitecture == Architecture.x64 ||
  235. preferredArchitecture == Architecture.Unknown)) {
  236. // 64 bit
  237. yield return new FileInfo(Path.Combine(nativePluginFolder.FullName,
  238. relevantBit.Substring("x86_64".Length + 1)));
  239. }
  240. else {
  241. // Throw away
  242. yield break;
  243. }
  244. }
  245. else if (!isFlat && isFileFlat) {
  246. // Deepen structure
  247. yield return new FileInfo(Path.Combine(Path.Combine(nativePluginFolder.FullName, "x86"),
  248. relevantBit));
  249. yield return new FileInfo(Path.Combine(Path.Combine(nativePluginFolder.FullName, "x86_64"),
  250. relevantBit));
  251. }
  252. else {
  253. yield return to;
  254. }
  255. }
  256. else {
  257. yield return to;
  258. }
  259. }
  260. private static IEnumerable<FileInfo> PassThroughInterceptor(FileInfo from, FileInfo to) {
  261. yield return to;
  262. }
  263. public static void CopyAll(DirectoryInfo source, DirectoryInfo target, bool aggressive, BackupUnit backup,
  264. Func<FileInfo, FileInfo, IEnumerable<FileInfo>> interceptor = null) {
  265. if (interceptor == null) {
  266. interceptor = PassThroughInterceptor;
  267. }
  268. // Copy each file into the new directory.
  269. foreach (FileInfo fi in source.GetFiles()) {
  270. foreach (var targetFile in interceptor(fi, new FileInfo(Path.Combine(target.FullName, fi.Name)))) {
  271. if (!targetFile.Exists || targetFile.LastWriteTimeUtc < fi.LastWriteTimeUtc || aggressive) {
  272. targetFile.Directory.Create();
  273. Console.WriteLine(@"Copying {0}", targetFile.FullName);
  274. backup.Add(targetFile);
  275. fi.CopyTo(targetFile.FullName, true);
  276. }
  277. }
  278. }
  279. // Copy each subdirectory using recursion.
  280. foreach (DirectoryInfo diSourceSubDir in source.GetDirectories()) {
  281. DirectoryInfo nextTargetSubDir = new DirectoryInfo(Path.Combine(target.FullName, diSourceSubDir.Name));
  282. CopyAll(diSourceSubDir, nextTargetSubDir, aggressive, backup, interceptor);
  283. }
  284. }
  285. static void Fail(string message) {
  286. Console.Error.Write("ERROR: " + message);
  287. if (!Environment.CommandLine.Contains("--nowait")) {
  288. Console.WriteLine("\n\n[Press any key to quit]");
  289. Console.ReadKey();
  290. }
  291. Environment.Exit(1);
  292. }
  293. public static string Args(params string[] args) {
  294. return string.Join(" ", args.Select(EncodeParameterArgument).ToArray());
  295. }
  296. /// <summary>
  297. /// Encodes an argument for passing into a program
  298. /// </summary>
  299. /// <param name="original">The value that should be received by the program</param>
  300. /// <returns>The value which needs to be passed to the program for the original value
  301. /// to come through</returns>
  302. public static string EncodeParameterArgument(string original) {
  303. if (string.IsNullOrEmpty(original))
  304. return original;
  305. string value = Regex.Replace(original, @"(\\*)" + "\"", @"$1\$0");
  306. value = Regex.Replace(value, @"^(.*\s.*?)(\\*)$", "\"$1$2$2\"");
  307. return value;
  308. }
  309. public static Architecture DetectArchitecture(string assembly) {
  310. using (var reader = new BinaryReader(File.OpenRead(assembly))) {
  311. var header = reader.ReadUInt16();
  312. if (header == 0x5a4d) {
  313. reader.BaseStream.Seek(60, SeekOrigin.Begin); // this location contains the offset for the PE header
  314. var peOffset = reader.ReadUInt32();
  315. reader.BaseStream.Seek(peOffset + 4, SeekOrigin.Begin);
  316. var machine = reader.ReadUInt16();
  317. if (machine == 0x8664) // IMAGE_FILE_MACHINE_AMD64
  318. return Architecture.x64;
  319. else if (machine == 0x014c) // IMAGE_FILE_MACHINE_I386
  320. return Architecture.x86;
  321. else if (machine == 0x0200) // IMAGE_FILE_MACHINE_IA64
  322. return Architecture.x64;
  323. else
  324. return Architecture.Unknown;
  325. }
  326. else {
  327. // Not a supported binary
  328. return Architecture.Unknown;
  329. }
  330. }
  331. }
  332. public abstract class Keyboard {
  333. [Flags]
  334. private enum KeyStates {
  335. None = 0,
  336. Down = 1,
  337. Toggled = 2
  338. }
  339. [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
  340. private static extern short GetKeyState(int keyCode);
  341. private static KeyStates GetKeyState(Keys key) {
  342. KeyStates state = KeyStates.None;
  343. short retVal = GetKeyState((int) key);
  344. //If the high-order bit is 1, the key is down
  345. //otherwise, it is up.
  346. if ((retVal & 0x8000) == 0x8000)
  347. state |= KeyStates.Down;
  348. //If the low-order bit is 1, the key is toggled.
  349. if ((retVal & 1) == 1)
  350. state |= KeyStates.Toggled;
  351. return state;
  352. }
  353. public static bool IsKeyDown(Keys key) {
  354. return KeyStates.Down == (GetKeyState(key) & KeyStates.Down);
  355. }
  356. public static bool IsKeyToggled(Keys key) {
  357. return KeyStates.Toggled == (GetKeyState(key) & KeyStates.Toggled);
  358. }
  359. }
  360. }
  361. }