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.

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