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.

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