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.

Program.cs 11KB

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