A fork of Eusth's IPA
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.

366 lines
13KB

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