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.

373 lines
14 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. static void Main(string[] args) {
  22. PatchContext context;
  23. if(args.Length < 1 || !args[0].EndsWith(".exe"))
  24. {
  25. //Fail("Drag an (executable) file on the exe!");
  26. context = PatchContext.Create(new [] {new DirectoryInfo(Directory.GetCurrentDirectory()).GetFiles().First(o => o.FullName.EndsWith(".exe"))
  27. .FullName});
  28. }
  29. else {
  30. context = PatchContext.Create(args);
  31. }
  32. try
  33. {
  34. bool isRevert = args.Contains("--revert") || Keyboard.IsKeyDown(Keys.LMenu);
  35. // Sanitizing
  36. Validate(context);
  37. if (isRevert)
  38. {
  39. Revert(context);
  40. }
  41. else
  42. {
  43. Install(context);
  44. StartIfNeedBe(context);
  45. }
  46. } catch(Exception e)
  47. {
  48. Fail(e.Message);
  49. }
  50. }
  51. private static void Validate(PatchContext c)
  52. {
  53. if (!File.Exists(c.LauncherPathSrc)) Fail("Couldn't find DLLs! Make sure you extracted all contents of the release archive.");
  54. if (!Directory.Exists(c.DataPathDst) || !File.Exists(c.EngineFile))
  55. {
  56. Fail("Game does not seem to be a Unity project. Could not find the libraries to patch.");
  57. Console.WriteLine($"DataPath: {c.DataPathDst}");
  58. Console.WriteLine($"EngineFile: {c.EngineFile}");
  59. }
  60. }
  61. private static void Install(PatchContext context)
  62. {
  63. try
  64. {
  65. var backup = new BackupUnit(context);
  66. // Copying
  67. Console.WriteLine("Updating files... ");
  68. var nativePluginFolder = Path.Combine(context.DataPathDst, "Plugins");
  69. bool isFlat = Directory.Exists(nativePluginFolder) && Directory.GetFiles(nativePluginFolder).Any(f => f.EndsWith(".dll"));
  70. bool force = !BackupManager.HasBackup(context) || context.Args.Contains("-f") || context.Args.Contains("--force");
  71. var architecture = DetectArchitecture(context.Executable);
  72. Console.WriteLine("Architecture: {0}", architecture);
  73. CopyAll(new DirectoryInfo(context.DataPathSrc), new DirectoryInfo(context.DataPathDst), force, backup,
  74. (from, to) => NativePluginInterceptor(from, to, new DirectoryInfo(nativePluginFolder), isFlat, architecture) );
  75. Console.WriteLine("Successfully updated files!");
  76. if (!Directory.Exists(context.PluginsFolder))
  77. {
  78. Console.WriteLine("Creating plugins folder... ");
  79. Directory.CreateDirectory(context.PluginsFolder);
  80. }
  81. // Patching
  82. var patchedModule = PatchedModule.Load(context.EngineFile);
  83. if (!patchedModule.IsPatched)
  84. {
  85. Console.Write("Patching UnityEngine.dll... ");
  86. backup.Add(context.EngineFile);
  87. patchedModule.Patch();
  88. Console.WriteLine("Done!");
  89. }
  90. // Virtualizing
  91. if (File.Exists(context.AssemblyFile))
  92. {
  93. var virtualizedModule = VirtualizedModule.Load(context.AssemblyFile);
  94. if (!virtualizedModule.IsVirtualized)
  95. {
  96. Console.Write("Virtualizing Assembly-Csharp.dll... ");
  97. backup.Add(context.AssemblyFile);
  98. virtualizedModule.Virtualize();
  99. Console.WriteLine("Done!");
  100. }
  101. }
  102. // Creating shortcut
  103. if(!File.Exists(context.ShortcutPath))
  104. {
  105. Console.Write("Creating shortcut to IPA ({0})... ", context.IPA);
  106. try
  107. {
  108. Shortcut.Create(
  109. fileName: context.ShortcutPath,
  110. targetPath: context.IPA,
  111. arguments: Args(context.Executable, "--launch"),
  112. workingDirectory: context.ProjectRoot,
  113. description: "Launches the game and makes sure it's in a patched state",
  114. hotkey: "",
  115. iconPath: context.Executable
  116. );
  117. Console.WriteLine("Created");
  118. } catch (Exception e)
  119. {
  120. Console.Error.WriteLine("Failed to create shortcut, but game was patched!");
  121. }
  122. }
  123. }
  124. catch (Exception e)
  125. {
  126. Fail("Oops! This should not have happened.\n\n" + e);
  127. }
  128. Console.ForegroundColor = ConsoleColor.Green;
  129. Console.WriteLine("Finished!");
  130. Console.ResetColor();
  131. }
  132. private static void Revert(PatchContext context)
  133. {
  134. Console.Write("Restoring backup... ");
  135. if(BackupManager.Restore(context))
  136. {
  137. Console.WriteLine("Done!");
  138. } else
  139. {
  140. Console.WriteLine("Already vanilla!");
  141. }
  142. if (File.Exists(context.ShortcutPath))
  143. {
  144. Console.WriteLine("Deleting shortcut...");
  145. File.Delete(context.ShortcutPath);
  146. }
  147. Console.WriteLine("");
  148. Console.WriteLine("--- Done reverting ---");
  149. if (!Environment.CommandLine.Contains("--nowait"))
  150. {
  151. Console.WriteLine("\n\n[Press any key to quit]");
  152. Console.ReadKey();
  153. }
  154. }
  155. private static void StartIfNeedBe(PatchContext context)
  156. {
  157. var argList = context.Args.ToList();
  158. bool launch = argList.Remove("--launch");
  159. argList.RemoveAt(0);
  160. if(launch)
  161. {
  162. Process.Start(context.Executable, Args(argList.ToArray()));
  163. }
  164. }
  165. public static IEnumerable<FileInfo> NativePluginInterceptor(FileInfo from, FileInfo to, DirectoryInfo nativePluginFolder, bool isFlat, Architecture preferredArchitecture)
  166. {
  167. if (to.FullName.StartsWith(nativePluginFolder.FullName))
  168. {
  169. var relevantBit = to.FullName.Substring(nativePluginFolder.FullName.Length + 1);
  170. // Goes into the plugin folder!
  171. bool isFileFlat = !relevantBit.StartsWith("x86");
  172. if (isFlat && !isFileFlat)
  173. {
  174. // Flatten structure
  175. bool is64Bit = relevantBit.StartsWith("x86_64");
  176. if (!is64Bit && preferredArchitecture == Architecture.x86)
  177. {
  178. // 32 bit
  179. yield return new FileInfo(Path.Combine(nativePluginFolder.FullName, relevantBit.Substring("x86".Length + 1)));
  180. }
  181. else if(is64Bit && (preferredArchitecture == Architecture.x64 || preferredArchitecture == Architecture.Unknown))
  182. {
  183. // 64 bit
  184. yield return new FileInfo(Path.Combine(nativePluginFolder.FullName, relevantBit.Substring("x86_64".Length + 1)));
  185. } else {
  186. // Throw away
  187. yield break;
  188. }
  189. }
  190. else if (!isFlat && isFileFlat)
  191. {
  192. // Deepen structure
  193. yield return new FileInfo(Path.Combine(Path.Combine(nativePluginFolder.FullName, "x86"), relevantBit));
  194. yield return new FileInfo(Path.Combine(Path.Combine(nativePluginFolder.FullName, "x86_64"), relevantBit));
  195. }
  196. else
  197. {
  198. yield return to;
  199. }
  200. }
  201. else
  202. {
  203. yield return to;
  204. }
  205. }
  206. private static IEnumerable<FileInfo> PassThroughInterceptor(FileInfo from, FileInfo to)
  207. {
  208. yield return to;
  209. }
  210. public static void CopyAll(DirectoryInfo source, DirectoryInfo target, bool aggressive, BackupUnit backup, Func<FileInfo, FileInfo, IEnumerable<FileInfo>> interceptor = null)
  211. {
  212. if(interceptor == null)
  213. {
  214. interceptor = PassThroughInterceptor;
  215. }
  216. // Copy each file into the new directory.
  217. foreach (FileInfo fi in source.GetFiles())
  218. {
  219. foreach(var targetFile in interceptor(fi, new FileInfo(Path.Combine(target.FullName, fi.Name)))) {
  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. 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. } else
  284. {
  285. // Not a supported binary
  286. return Architecture.Unknown;
  287. }
  288. }
  289. }
  290. public abstract class Keyboard
  291. {
  292. [Flags]
  293. private enum KeyStates
  294. {
  295. None = 0,
  296. Down = 1,
  297. Toggled = 2
  298. }
  299. [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
  300. private static extern short GetKeyState(int keyCode);
  301. private static KeyStates GetKeyState(Keys key)
  302. {
  303. KeyStates state = KeyStates.None;
  304. short retVal = GetKeyState((int)key);
  305. //If the high-order bit is 1, the key is down
  306. //otherwise, it is up.
  307. if ((retVal & 0x8000) == 0x8000)
  308. state |= KeyStates.Down;
  309. //If the low-order bit is 1, the key is toggled.
  310. if ((retVal & 1) == 1)
  311. state |= KeyStates.Toggled;
  312. return state;
  313. }
  314. public static bool IsKeyDown(Keys key)
  315. {
  316. return KeyStates.Down == (GetKeyState(key) & KeyStates.Down);
  317. }
  318. public static bool IsKeyToggled(Keys key)
  319. {
  320. return KeyStates.Toggled == (GetKeyState(key) & KeyStates.Toggled);
  321. }
  322. }
  323. }
  324. }