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.

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