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.

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