CLIPA/IPA/Program.cs

366 lines
13 KiB
C#
Raw Permalink Normal View History

2016-12-15 20:07:03 +00:00
using IPA.Patcher;
using System;
2016-12-14 21:45:50 +00:00
using System.Collections.Generic;
2017-01-20 19:29:51 +00:00
using System.Diagnostics;
2016-12-14 21:45:50 +00:00
using System.IO;
using System.Linq;
2017-01-20 19:29:51 +00:00
using System.Reflection;
using System.Runtime.InteropServices;
2016-12-14 21:45:50 +00:00
using System.Text;
2017-01-20 19:29:51 +00:00
using System.Text.RegularExpressions;
using System.Windows.Forms;
2016-12-14 21:45:50 +00:00
namespace IPA
{
2017-01-20 19:29:51 +00:00
public class Program
2016-12-14 21:45:50 +00:00
{
public enum Architecture {
x86,
x64,
Unknown
}
2017-01-20 19:29:51 +00:00
2016-12-14 21:45:50 +00:00
static void Main(string[] args)
{
if(args.Length < 1 || !args[0].EndsWith(".exe"))
{
Fail("Drag an (executable) file on the exe!");
}
2017-01-20 19:29:51 +00:00
try
{
var context = PatchContext.Create(args);
bool isRevert = args.Contains("--revert") || Keyboard.IsKeyDown(Keys.LMenu);
// Sanitizing
Validate(context);
2016-12-15 20:07:03 +00:00
2017-01-20 19:29:51 +00:00
if (isRevert)
{
Revert(context);
}
else
{
Install(context);
StartIfNeedBe(context);
}
} catch(Exception e)
{
Fail(e.Message);
}
}
2016-12-14 21:45:50 +00:00
2017-01-20 19:29:51 +00:00
private static void Validate(PatchContext c)
{
if (!File.Exists(c.LauncherPathSrc)) Fail("Couldn't find DLLs! Make sure you extracted all contents of the release archive.");
if (!Directory.Exists(c.DataPathDst) || !File.Exists(c.EngineFile))
2016-12-15 20:07:03 +00:00
{
2017-01-20 19:29:51 +00:00
Fail("Game does not seem to be a Unity project. Could not find the libraries to patch.");
}
}
2016-12-14 21:45:50 +00:00
2017-01-20 19:29:51 +00:00
private static void Install(PatchContext context)
{
2016-12-14 21:45:50 +00:00
try
{
2017-02-21 23:34:07 +00:00
var backup = new BackupUnit(context);
2016-12-15 20:07:03 +00:00
// Copying
Console.WriteLine("Updating files... ");
var nativePluginFolder = Path.Combine(context.DataPathDst, "Plugins");
bool isFlat = Directory.Exists(nativePluginFolder) && Directory.GetFiles(nativePluginFolder).Any(f => f.EndsWith(".dll"));
2017-02-21 23:34:07 +00:00
bool force = !BackupManager.HasBackup(context) || context.Args.Contains("-f") || context.Args.Contains("--force");
var architecture = DetectArchitecture(context.Executable);
Console.WriteLine("Architecture: {0}", architecture);
CopyAll(new DirectoryInfo(context.DataPathSrc), new DirectoryInfo(context.DataPathDst), force, backup,
(from, to) => NativePluginInterceptor(from, to, new DirectoryInfo(nativePluginFolder), isFlat, architecture) );
2017-01-08 16:49:11 +00:00
Console.WriteLine("Successfully updated files!");
2016-12-15 20:07:03 +00:00
2017-01-20 19:29:51 +00:00
if (!Directory.Exists(context.PluginsFolder))
2016-12-15 20:07:03 +00:00
{
2017-01-08 16:49:11 +00:00
Console.WriteLine("Creating plugins folder... ");
2017-01-20 19:29:51 +00:00
Directory.CreateDirectory(context.PluginsFolder);
2016-12-15 20:07:03 +00:00
}
// Patching
2017-01-20 19:29:51 +00:00
var patchedModule = PatchedModule.Load(context.EngineFile);
if (!patchedModule.IsPatched)
2016-12-15 20:07:03 +00:00
{
2017-01-08 16:49:11 +00:00
Console.Write("Patching UnityEngine.dll... ");
2017-02-21 23:34:07 +00:00
backup.Add(context.EngineFile);
2016-12-15 20:07:03 +00:00
patchedModule.Patch();
2017-01-08 16:49:11 +00:00
Console.WriteLine("Done!");
2016-12-15 20:07:03 +00:00
}
// Virtualizing
if (File.Exists(context.AssemblyFile))
2016-12-15 20:07:03 +00:00
{
var virtualizedModule = VirtualizedModule.Load(context.AssemblyFile);
if (!virtualizedModule.IsVirtualized)
{
Console.Write("Virtualizing Assembly-Csharp.dll... ");
backup.Add(context.AssemblyFile);
virtualizedModule.Virtualize();
Console.WriteLine("Done!");
}
2016-12-15 20:07:03 +00:00
}
2017-01-20 19:29:51 +00:00
// Creating shortcut
if(!File.Exists(context.ShortcutPath))
{
2017-02-17 17:33:07 +00:00
Console.Write("Creating shortcut to IPA ({0})... ", context.IPA);
try
{
Shortcut.Create(
fileName: context.ShortcutPath,
targetPath: context.IPA,
arguments: Args(context.Executable, "--launch"),
workingDirectory: context.ProjectRoot,
description: "Launches the game and makes sure it's in a patched state",
hotkey: "",
iconPath: context.Executable
);
Console.WriteLine("Created");
} catch (Exception e)
{
Console.Error.WriteLine("Failed to create shortcut, but game was patched!");
}
2017-01-20 19:29:51 +00:00
}
}
catch (Exception e)
2016-12-14 21:45:50 +00:00
{
Fail("Oops! This should not have happened.\n\n" + e);
}
2017-01-08 16:49:11 +00:00
Console.ForegroundColor = ConsoleColor.Green;
2017-01-08 16:49:11 +00:00
Console.WriteLine("Finished!");
Console.ResetColor();
2017-01-20 19:29:51 +00:00
}
private static void Revert(PatchContext context)
{
2017-02-21 23:34:07 +00:00
Console.Write("Restoring backup... ");
if(BackupManager.Restore(context))
2017-01-20 19:29:51 +00:00
{
Console.WriteLine("Done!");
} else
{
Console.WriteLine("Already vanilla!");
}
2017-02-21 23:34:07 +00:00
2017-01-20 19:29:51 +00:00
if (File.Exists(context.ShortcutPath))
{
Console.WriteLine("Deleting shortcut...");
File.Delete(context.ShortcutPath);
}
Console.WriteLine("");
Console.WriteLine("--- Done reverting ---");
if (!Environment.CommandLine.Contains("--nowait"))
{
Console.WriteLine("\n\n[Press any key to quit]");
Console.ReadKey();
}
}
private static void StartIfNeedBe(PatchContext context)
{
var argList = context.Args.ToList();
bool launch = argList.Remove("--launch");
argList.RemoveAt(0);
if(launch)
{
Process.Start(context.Executable, Args(argList.ToArray()));
}
2016-12-14 21:45:50 +00:00
}
public static IEnumerable<FileInfo> NativePluginInterceptor(FileInfo from, FileInfo to, DirectoryInfo nativePluginFolder, bool isFlat, Architecture preferredArchitecture)
{
if (to.FullName.StartsWith(nativePluginFolder.FullName))
{
var relevantBit = to.FullName.Substring(nativePluginFolder.FullName.Length + 1);
// Goes into the plugin folder!
bool isFileFlat = !relevantBit.StartsWith("x86");
if (isFlat && !isFileFlat)
{
// Flatten structure
bool is64Bit = relevantBit.StartsWith("x86_64");
if (!is64Bit && preferredArchitecture == Architecture.x86)
{
// 32 bit
yield return new FileInfo(Path.Combine(nativePluginFolder.FullName, relevantBit.Substring("x86".Length + 1)));
}
else if(is64Bit && (preferredArchitecture == Architecture.x64 || preferredArchitecture == Architecture.Unknown))
{
// 64 bit
yield return new FileInfo(Path.Combine(nativePluginFolder.FullName, relevantBit.Substring("x86_64".Length + 1)));
} else {
// Throw away
yield break;
}
}
else if (!isFlat && isFileFlat)
{
// Deepen structure
yield return new FileInfo(Path.Combine(Path.Combine(nativePluginFolder.FullName, "x86"), relevantBit));
yield return new FileInfo(Path.Combine(Path.Combine(nativePluginFolder.FullName, "x86_64"), relevantBit));
}
else
{
yield return to;
}
}
else
{
yield return to;
}
}
private static IEnumerable<FileInfo> PassThroughInterceptor(FileInfo from, FileInfo to)
{
yield return to;
}
2017-02-21 23:34:07 +00:00
public static void CopyAll(DirectoryInfo source, DirectoryInfo target, bool aggressive, BackupUnit backup, Func<FileInfo, FileInfo, IEnumerable<FileInfo>> interceptor = null)
2016-12-14 21:45:50 +00:00
{
if(interceptor == null)
{
interceptor = PassThroughInterceptor;
}
2016-12-14 21:45:50 +00:00
// Copy each file into the new directory.
foreach (FileInfo fi in source.GetFiles())
{
foreach(var targetFile in interceptor(fi, new FileInfo(Path.Combine(target.FullName, fi.Name)))) {
2017-02-21 23:34:07 +00:00
if (!targetFile.Exists || targetFile.LastWriteTimeUtc < fi.LastWriteTimeUtc || aggressive)
{
2017-02-21 23:34:07 +00:00
targetFile.Directory.Create();
Console.WriteLine(@"Copying {0}", targetFile.FullName);
2017-02-21 23:34:07 +00:00
backup.Add(targetFile);
fi.CopyTo(targetFile.FullName, true);
}
2016-12-15 20:07:03 +00:00
}
2016-12-14 21:45:50 +00:00
}
// Copy each subdirectory using recursion.
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
{
2017-02-21 23:34:07 +00:00
DirectoryInfo nextTargetSubDir = new DirectoryInfo(Path.Combine(target.FullName, diSourceSubDir.Name));
CopyAll(diSourceSubDir, nextTargetSubDir, aggressive, backup, interceptor);
2016-12-14 21:45:50 +00:00
}
}
static void Fail(string message)
{
2016-12-15 20:07:03 +00:00
Console.Error.Write("ERROR: " + message);
if (!Environment.CommandLine.Contains("--nowait"))
{
2016-12-15 20:13:27 +00:00
Console.WriteLine("\n\n[Press any key to quit]");
Console.ReadKey();
2016-12-15 20:07:03 +00:00
}
2016-12-14 21:45:50 +00:00
Environment.Exit(1);
}
2017-01-20 19:29:51 +00:00
public static string Args(params string[] args)
{
return string.Join(" ", args.Select(EncodeParameterArgument).ToArray());
}
/// <summary>
/// Encodes an argument for passing into a program
/// </summary>
/// <param name="original">The value that should be received by the program</param>
/// <returns>The value which needs to be passed to the program for the original value
/// to come through</returns>
public static string EncodeParameterArgument(string original)
{
if (string.IsNullOrEmpty(original))
return original;
string value = Regex.Replace(original, @"(\\*)" + "\"", @"$1\$0");
value = Regex.Replace(value, @"^(.*\s.*?)(\\*)$", "\"$1$2$2\"");
return value;
}
public static Architecture DetectArchitecture(string assembly)
{
using (var reader = new BinaryReader(File.OpenRead(assembly)))
{
var header = reader.ReadUInt16();
if(header == 0x5a4d)
{
reader.BaseStream.Seek(60, SeekOrigin.Begin); // this location contains the offset for the PE header
var peOffset = reader.ReadUInt32();
reader.BaseStream.Seek(peOffset + 4, SeekOrigin.Begin);
var machine = reader.ReadUInt16();
if (machine == 0x8664) // IMAGE_FILE_MACHINE_AMD64
return Architecture.x64;
else if (machine == 0x014c) // IMAGE_FILE_MACHINE_I386
return Architecture.x86;
else if (machine == 0x0200) // IMAGE_FILE_MACHINE_IA64
return Architecture.x64;
else
return Architecture.Unknown;
} else
{
// Not a supported binary
return Architecture.Unknown;
}
}
}
2017-01-20 19:29:51 +00:00
public abstract class Keyboard
{
[Flags]
private enum KeyStates
{
None = 0,
Down = 1,
Toggled = 2
}
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
private static extern short GetKeyState(int keyCode);
private static KeyStates GetKeyState(Keys key)
{
KeyStates state = KeyStates.None;
short retVal = GetKeyState((int)key);
//If the high-order bit is 1, the key is down
//otherwise, it is up.
if ((retVal & 0x8000) == 0x8000)
state |= KeyStates.Down;
//If the low-order bit is 1, the key is toggled.
if ((retVal & 1) == 1)
state |= KeyStates.Toggled;
return state;
}
public static bool IsKeyDown(Keys key)
{
return KeyStates.Down == (GetKeyState(key) & KeyStates.Down);
}
public static bool IsKeyToggled(Keys key)
{
return KeyStates.Toggled == (GetKeyState(key) & KeyStates.Toggled);
}
}
2016-12-14 21:45:50 +00:00
}
}