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.

372 lines
13KB

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