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.

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