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.

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