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.

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