Cardlife mod patcher
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.

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