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.

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