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.

412 lines
15KB

  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. try
  82. {
  83. patchedModule.Patch();
  84. }
  85. catch (Exception)
  86. {
  87. Console.WriteLine($"Processes that are locking {context.EngineFile}:");
  88. foreach (Process proc in FileUtil.WhoIsLocking(context.EngineFile))
  89. {
  90. Console.WriteLine(proc.ProcessName);
  91. }
  92. }
  93. Console.WriteLine("Done!");
  94. }
  95. patchedModule.Dispose();
  96. // Virtualizing
  97. if (File.Exists(context.AssemblyFile))
  98. {
  99. var virtualizedModule = VirtualizedModule.Load(context.AssemblyFile);
  100. if (!virtualizedModule.IsVirtualized)
  101. {
  102. Console.Write("Virtualizing Assembly-Csharp.dll... ");
  103. backup.Add(context.AssemblyFile);
  104. virtualizedModule.Virtualize();
  105. Console.WriteLine("Done!");
  106. }
  107. virtualizedModule.Dispose();
  108. }
  109. // Creating shortcut
  110. if(!File.Exists(context.ShortcutPath))
  111. {
  112. Console.Write("Creating shortcut to IPA ({0})... ", context.IPA);
  113. try
  114. {
  115. Shortcut.Create(
  116. fileName: context.ShortcutPath,
  117. targetPath: context.IPA,
  118. arguments: Args(context.Executable, "--launch"),
  119. workingDirectory: context.ProjectRoot,
  120. description: "Launches the game and makes sure it's in a patched state",
  121. hotkey: "",
  122. iconPath: context.Executable
  123. );
  124. Console.WriteLine("Created");
  125. } catch (Exception e)
  126. {
  127. Console.Error.WriteLine("Failed to create shortcut, but game was patched! Exception: " + e);
  128. }
  129. }
  130. // copy back
  131. try
  132. {
  133. Console.WriteLine("Copying patched files back to correct locations");
  134. var engineFile = new FileInfo(context.EngineFile + "2");
  135. engineFile.CopyTo(context.EngineFile, true);
  136. engineFile.Delete();
  137. var assemblyFile = new FileInfo(context.AssemblyFile + "2");
  138. assemblyFile.CopyTo(context.AssemblyFile, true);
  139. assemblyFile.Delete();
  140. Console.WriteLine("Copied");
  141. }
  142. catch (Exception)
  143. {
  144. // Check stuff
  145. Console.WriteLine($"Processes that are locking {context.EngineFile}:");
  146. foreach (Process proc in FileUtil.WhoIsLocking(context.EngineFile))
  147. {
  148. Console.WriteLine(proc.ProcessName);
  149. }
  150. Console.WriteLine($"Processes that are locking {context.AssemblyFile}:");
  151. foreach (Process proc in FileUtil.WhoIsLocking(context.AssemblyFile))
  152. {
  153. Console.WriteLine(proc.ProcessName);
  154. }
  155. Console.WriteLine("Copy Back failed");
  156. }
  157. }
  158. catch (Exception e)
  159. {
  160. Fail("Oops! This should not have happened.\n\n" + e);
  161. }
  162. Console.ForegroundColor = ConsoleColor.Green;
  163. Console.WriteLine("Finished!");
  164. Console.ResetColor();
  165. }
  166. private static void Revert(PatchContext context)
  167. {
  168. Console.Write("Restoring backup... ");
  169. if(BackupManager.Restore(context))
  170. {
  171. Console.WriteLine("Done!");
  172. } else
  173. {
  174. Console.WriteLine("Already vanilla!");
  175. }
  176. if (File.Exists(context.ShortcutPath))
  177. {
  178. Console.WriteLine("Deleting shortcut...");
  179. File.Delete(context.ShortcutPath);
  180. }
  181. Console.WriteLine("");
  182. Console.WriteLine("--- Done reverting ---");
  183. if (!Environment.CommandLine.Contains("--nowait"))
  184. {
  185. Console.WriteLine("\n\n[Press any key to quit]");
  186. Console.ReadKey();
  187. }
  188. }
  189. private static void StartIfNeedBe(PatchContext context)
  190. {
  191. var argList = context.Args.ToList();
  192. bool launch = argList.Remove("--launch");
  193. argList.RemoveAt(0);
  194. if(launch)
  195. {
  196. Process.Start(context.Executable, Args(argList.ToArray()));
  197. }
  198. }
  199. public static IEnumerable<FileInfo> NativePluginInterceptor(FileInfo from, FileInfo to, DirectoryInfo nativePluginFolder, bool isFlat, Architecture preferredArchitecture)
  200. {
  201. if (to.FullName.StartsWith(nativePluginFolder.FullName))
  202. {
  203. var relevantBit = to.FullName.Substring(nativePluginFolder.FullName.Length + 1);
  204. // Goes into the plugin folder!
  205. bool isFileFlat = !relevantBit.StartsWith("x86");
  206. if (isFlat && !isFileFlat)
  207. {
  208. // Flatten structure
  209. bool is64Bit = relevantBit.StartsWith("x86_64");
  210. if (!is64Bit && preferredArchitecture == Architecture.x86)
  211. {
  212. // 32 bit
  213. yield return new FileInfo(Path.Combine(nativePluginFolder.FullName, relevantBit.Substring("x86".Length + 1)));
  214. }
  215. else if(is64Bit && (preferredArchitecture == Architecture.x64 || preferredArchitecture == Architecture.Unknown))
  216. {
  217. // 64 bit
  218. yield return new FileInfo(Path.Combine(nativePluginFolder.FullName, relevantBit.Substring("x86_64".Length + 1)));
  219. } else {
  220. // Throw away
  221. yield break;
  222. }
  223. }
  224. else if (!isFlat && isFileFlat)
  225. {
  226. // Deepen structure
  227. yield return new FileInfo(Path.Combine(Path.Combine(nativePluginFolder.FullName, "x86"), relevantBit));
  228. yield return new FileInfo(Path.Combine(Path.Combine(nativePluginFolder.FullName, "x86_64"), relevantBit));
  229. }
  230. else
  231. {
  232. yield return to;
  233. }
  234. }
  235. else
  236. {
  237. yield return to;
  238. }
  239. }
  240. private static IEnumerable<FileInfo> PassThroughInterceptor(FileInfo from, FileInfo to)
  241. {
  242. yield return to;
  243. }
  244. public static void CopyAll(DirectoryInfo source, DirectoryInfo target, bool aggressive, BackupUnit backup, Func<FileInfo, FileInfo, IEnumerable<FileInfo>> interceptor = null)
  245. {
  246. if(interceptor == null)
  247. {
  248. interceptor = PassThroughInterceptor;
  249. }
  250. // Copy each file into the new directory.
  251. foreach (FileInfo fi in source.GetFiles())
  252. {
  253. foreach(var targetFile in interceptor(fi, new FileInfo(Path.Combine(target.FullName, fi.Name)))) {
  254. if (!targetFile.Exists || targetFile.LastWriteTimeUtc < fi.LastWriteTimeUtc || aggressive)
  255. {
  256. targetFile.Directory.Create();
  257. Console.WriteLine(@"Copying {0}", targetFile.FullName);
  258. backup.Add(targetFile);
  259. fi.CopyTo(targetFile.FullName, true);
  260. }
  261. }
  262. }
  263. // Copy each subdirectory using recursion.
  264. foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
  265. {
  266. DirectoryInfo nextTargetSubDir = new DirectoryInfo(Path.Combine(target.FullName, diSourceSubDir.Name));
  267. CopyAll(diSourceSubDir, nextTargetSubDir, aggressive, backup, interceptor);
  268. }
  269. }
  270. static void Fail(string message)
  271. {
  272. Console.Error.Write("ERROR: " + message);
  273. if (!Environment.CommandLine.Contains("--nowait"))
  274. {
  275. Console.WriteLine("\n\n[Press any key to quit]");
  276. Console.ReadKey();
  277. }
  278. Environment.Exit(1);
  279. }
  280. public static string Args(params string[] args)
  281. {
  282. return string.Join(" ", args.Select(EncodeParameterArgument).ToArray());
  283. }
  284. /// <summary>
  285. /// Encodes an argument for passing into a program
  286. /// </summary>
  287. /// <param name="original">The value that should be received by the program</param>
  288. /// <returns>The value which needs to be passed to the program for the original value
  289. /// to come through</returns>
  290. public static string EncodeParameterArgument(string original)
  291. {
  292. if (string.IsNullOrEmpty(original))
  293. return original;
  294. string value = Regex.Replace(original, @"(\\*)" + "\"", @"$1\$0");
  295. value = Regex.Replace(value, @"^(.*\s.*?)(\\*)$", "\"$1$2$2\"");
  296. return value;
  297. }
  298. public static Architecture DetectArchitecture(string assembly)
  299. {
  300. using (var reader = new BinaryReader(File.OpenRead(assembly)))
  301. {
  302. var header = reader.ReadUInt16();
  303. if(header == 0x5a4d)
  304. {
  305. reader.BaseStream.Seek(60, SeekOrigin.Begin); // this location contains the offset for the PE header
  306. var peOffset = reader.ReadUInt32();
  307. reader.BaseStream.Seek(peOffset + 4, SeekOrigin.Begin);
  308. var machine = reader.ReadUInt16();
  309. if (machine == 0x8664) // IMAGE_FILE_MACHINE_AMD64
  310. return Architecture.x64;
  311. else if (machine == 0x014c) // IMAGE_FILE_MACHINE_I386
  312. return Architecture.x86;
  313. else if (machine == 0x0200) // IMAGE_FILE_MACHINE_IA64
  314. return Architecture.x64;
  315. else
  316. return Architecture.Unknown;
  317. } else
  318. {
  319. // Not a supported binary
  320. return Architecture.Unknown;
  321. }
  322. }
  323. }
  324. public enum Keys
  325. {
  326. LMenu = 164
  327. }
  328. public abstract class Keyboard
  329. {
  330. [Flags]
  331. private enum KeyStates
  332. {
  333. None = 0,
  334. Down = 1,
  335. Toggled = 2
  336. }
  337. [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
  338. private static extern short GetKeyState(int keyCode);
  339. private static KeyStates GetKeyState(Keys key)
  340. {
  341. KeyStates state = KeyStates.None;
  342. short retVal = GetKeyState((int)key);
  343. //If the high-order bit is 1, the key is down
  344. //otherwise, it is up.
  345. if ((retVal & 0x8000) == 0x8000)
  346. state |= KeyStates.Down;
  347. //If the low-order bit is 1, the key is toggled.
  348. if ((retVal & 1) == 1)
  349. state |= KeyStates.Toggled;
  350. return state;
  351. }
  352. public static bool IsKeyDown(Keys key)
  353. {
  354. return KeyStates.Down == (GetKeyState(key) & KeyStates.Down);
  355. }
  356. public static bool IsKeyToggled(Keys key)
  357. {
  358. return KeyStates.Toggled == (GetKeyState(key) & KeyStates.Toggled);
  359. }
  360. }
  361. }
  362. }