A fork of Eusth's IPA
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.

318 lines
11KB

  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. static void Main(string[] args)
  17. {
  18. if(args.Length < 1 || !args[0].EndsWith(".exe"))
  19. {
  20. Fail("Drag an (executable) file on the exe!");
  21. }
  22. try
  23. {
  24. var context = PatchContext.Create(args);
  25. bool isRevert = args.Contains("--revert") || Keyboard.IsKeyDown(Keys.LMenu);
  26. // Sanitizing
  27. Validate(context);
  28. if (isRevert)
  29. {
  30. Revert(context);
  31. }
  32. else
  33. {
  34. Install(context);
  35. StartIfNeedBe(context);
  36. }
  37. } catch(Exception e)
  38. {
  39. Fail(e.Message);
  40. }
  41. }
  42. private static void Validate(PatchContext c)
  43. {
  44. if (!File.Exists(c.LauncherPathSrc)) Fail("Couldn't find DLLs! Make sure you extracted all contents of the release archive.");
  45. if (!Directory.Exists(c.DataPathDst) || !File.Exists(c.EngineFile) || !File.Exists(c.AssemblyFile))
  46. {
  47. Fail("Game does not seem to be a Unity project. Could not find the libraries to patch.");
  48. }
  49. }
  50. private static void Install(PatchContext context)
  51. {
  52. try
  53. {
  54. // Copying
  55. Console.WriteLine("Updating files... ");
  56. var nativePluginFolder = Path.Combine(context.DataPathDst, "Plugins");
  57. bool isFlat = Directory.Exists(nativePluginFolder) && Directory.GetFiles(nativePluginFolder).Any(f => f.EndsWith(".dll"));
  58. CopyAll(new DirectoryInfo(context.DataPathSrc), new DirectoryInfo(context.DataPathDst), (from, to) => NativePluginInterceptor(from, to, new DirectoryInfo(nativePluginFolder), isFlat) );
  59. Console.WriteLine("Successfully updated files!");
  60. if (!Directory.Exists(context.PluginsFolder))
  61. {
  62. Console.WriteLine("Creating plugins folder... ");
  63. Directory.CreateDirectory(context.PluginsFolder);
  64. }
  65. // Patching
  66. var patchedModule = PatchedModule.Load(context.EngineFile);
  67. if (!patchedModule.IsPatched)
  68. {
  69. Console.Write("Patching UnityEngine.dll... ");
  70. BackupManager.MakeBackup(context.EngineFile);
  71. patchedModule.Patch();
  72. Console.WriteLine("Done!");
  73. }
  74. // Virtualizing
  75. var virtualizedModule = VirtualizedModule.Load(context.AssemblyFile);
  76. if (!virtualizedModule.IsVirtualized)
  77. {
  78. Console.Write("Virtualizing Assembly-Csharp.dll... ");
  79. BackupManager.MakeBackup(context.AssemblyFile);
  80. virtualizedModule.Virtualize();
  81. Console.WriteLine("Done!");
  82. }
  83. // Creating shortcut
  84. if(!File.Exists(context.ShortcutPath))
  85. {
  86. Console.Write("Creating shortcut to IPA ({0})... ", context.IPA);
  87. Shortcut.Create(
  88. fileName: context.ShortcutPath,
  89. targetPath: context.IPA,
  90. arguments: Args(context.Executable, "--launch"),
  91. workingDirectory: context.ProjectRoot,
  92. description: "Launches the game and makes sure it's in a patched state",
  93. hotkey: "",
  94. iconPath: context.Executable
  95. );
  96. Console.WriteLine("Created");
  97. }
  98. }
  99. catch (Exception e)
  100. {
  101. Fail("Oops! This should not have happened.\n\n" + e);
  102. }
  103. Console.WriteLine("Finished!");
  104. }
  105. private static void Revert(PatchContext context)
  106. {
  107. Console.Write("Restoring game assembly... ");
  108. if(BackupManager.Restore(context.AssemblyFile))
  109. {
  110. Console.WriteLine("Done!");
  111. } else
  112. {
  113. Console.WriteLine("Already vanilla!");
  114. }
  115. Console.Write("Restoring unity engine... ");
  116. if(BackupManager.Restore(context.EngineFile))
  117. {
  118. Console.WriteLine("Done!");
  119. }
  120. else
  121. {
  122. Console.WriteLine("Already vanilla!");
  123. }
  124. if (File.Exists(context.ShortcutPath))
  125. {
  126. Console.WriteLine("Deleting shortcut...");
  127. File.Delete(context.ShortcutPath);
  128. }
  129. Console.WriteLine("");
  130. Console.WriteLine("--- Done reverting ---");
  131. if (!Environment.CommandLine.Contains("--nowait"))
  132. {
  133. Console.WriteLine("\n\n[Press any key to quit]");
  134. Console.ReadKey();
  135. }
  136. }
  137. private static void StartIfNeedBe(PatchContext context)
  138. {
  139. var argList = context.Args.ToList();
  140. bool launch = argList.Remove("--launch");
  141. argList.RemoveAt(0);
  142. if(launch)
  143. {
  144. Process.Start(context.Executable, Args(argList.ToArray()));
  145. }
  146. }
  147. public static IEnumerable<FileInfo> NativePluginInterceptor(FileInfo from, FileInfo to, DirectoryInfo nativePluginFolder, bool isFlat)
  148. {
  149. if (to.FullName.StartsWith(nativePluginFolder.FullName))
  150. {
  151. var relevantBit = to.FullName.Substring(nativePluginFolder.FullName.Length + 1);
  152. // Goes into the plugin folder!
  153. bool isFileFlat = !relevantBit.StartsWith("x86");
  154. if (isFlat && !isFileFlat)
  155. {
  156. // Flatten structure
  157. if (relevantBit.StartsWith("x86_64"))
  158. {
  159. yield return new FileInfo(Path.Combine(nativePluginFolder.FullName, relevantBit.Substring("x86_64".Length + 1)));
  160. }
  161. else
  162. {
  163. // Throw away
  164. yield break;
  165. }
  166. }
  167. else if (!isFlat && isFileFlat)
  168. {
  169. // Deepen structure
  170. yield return new FileInfo(Path.Combine(Path.Combine(nativePluginFolder.FullName, "x86"), relevantBit));
  171. yield return new FileInfo(Path.Combine(Path.Combine(nativePluginFolder.FullName, "x86_64"), relevantBit));
  172. }
  173. else
  174. {
  175. yield return to;
  176. }
  177. }
  178. else
  179. {
  180. yield return to;
  181. }
  182. }
  183. private static IEnumerable<FileInfo> PassThroughInterceptor(FileInfo from, FileInfo to)
  184. {
  185. yield return to;
  186. }
  187. public static void CopyAll(DirectoryInfo source, DirectoryInfo target, Func<FileInfo, FileInfo, IEnumerable<FileInfo>> interceptor = null)
  188. {
  189. if(interceptor == null)
  190. {
  191. interceptor = PassThroughInterceptor;
  192. }
  193. Directory.CreateDirectory(target.FullName);
  194. // Copy each file into the new directory.
  195. foreach (FileInfo fi in source.GetFiles())
  196. {
  197. foreach(var targetFile in interceptor(fi, new FileInfo(Path.Combine(target.FullName, fi.Name)))) {
  198. if (!targetFile.Exists || targetFile.LastWriteTimeUtc < fi.LastWriteTimeUtc)
  199. {
  200. Console.WriteLine(@"Copying {0}", targetFile.FullName);
  201. fi.CopyTo(targetFile.FullName, true);
  202. }
  203. }
  204. }
  205. // Copy each subdirectory using recursion.
  206. foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
  207. {
  208. DirectoryInfo nextTargetSubDir =
  209. target.CreateSubdirectory(diSourceSubDir.Name);
  210. CopyAll(diSourceSubDir, nextTargetSubDir, interceptor);
  211. }
  212. }
  213. static void Fail(string message)
  214. {
  215. Console.Error.Write("ERROR: " + message);
  216. if (!Environment.CommandLine.Contains("--nowait"))
  217. {
  218. Console.WriteLine("\n\n[Press any key to quit]");
  219. Console.ReadKey();
  220. }
  221. Environment.Exit(1);
  222. }
  223. public static string Args(params string[] args)
  224. {
  225. return string.Join(" ", args.Select(EncodeParameterArgument).ToArray());
  226. }
  227. /// <summary>
  228. /// Encodes an argument for passing into a program
  229. /// </summary>
  230. /// <param name="original">The value that should be received by the program</param>
  231. /// <returns>The value which needs to be passed to the program for the original value
  232. /// to come through</returns>
  233. public static string EncodeParameterArgument(string original)
  234. {
  235. if (string.IsNullOrEmpty(original))
  236. return original;
  237. string value = Regex.Replace(original, @"(\\*)" + "\"", @"$1\$0");
  238. value = Regex.Replace(value, @"^(.*\s.*?)(\\*)$", "\"$1$2$2\"");
  239. return value;
  240. }
  241. public abstract class Keyboard
  242. {
  243. [Flags]
  244. private enum KeyStates
  245. {
  246. None = 0,
  247. Down = 1,
  248. Toggled = 2
  249. }
  250. [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
  251. private static extern short GetKeyState(int keyCode);
  252. private static KeyStates GetKeyState(Keys key)
  253. {
  254. KeyStates state = KeyStates.None;
  255. short retVal = GetKeyState((int)key);
  256. //If the high-order bit is 1, the key is down
  257. //otherwise, it is up.
  258. if ((retVal & 0x8000) == 0x8000)
  259. state |= KeyStates.Down;
  260. //If the low-order bit is 1, the key is toggled.
  261. if ((retVal & 1) == 1)
  262. state |= KeyStates.Toggled;
  263. return state;
  264. }
  265. public static bool IsKeyDown(Keys key)
  266. {
  267. return KeyStates.Down == (GetKeyState(key) & KeyStates.Down);
  268. }
  269. public static bool IsKeyToggled(Keys key)
  270. {
  271. return KeyStates.Toggled == (GetKeyState(key) & KeyStates.Toggled);
  272. }
  273. }
  274. }
  275. }