CLIPA/IPA/Patcher/Patcher.cs

100 lines
2.9 KiB
C#
Raw Normal View History

2016-12-15 20:07:03 +00:00
using Mono.Cecil;
using Mono.Cecil.Cil;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace IPA.Patcher
{
class PatchedModule
{
2017-01-08 16:49:11 +00:00
private static readonly string[] ENTRY_TYPES = { "Input", "Display" };
2016-12-15 20:07:03 +00:00
private FileInfo _File;
private ModuleDefinition _Module;
public static PatchedModule Load(string engineFile)
{
return new PatchedModule(engineFile);
}
private PatchedModule(string engineFile)
{
_File = new FileInfo(engineFile);
LoadModules();
}
private void LoadModules()
{
var resolver = new DefaultAssemblyResolver();
resolver.AddSearchDirectory(_File.DirectoryName);
var parameters = new ReaderParameters
{
AssemblyResolver = resolver,
};
_Module = ModuleDefinition.ReadModule(_File.FullName, parameters);
}
public bool IsPatched
{
get
{
foreach (var @ref in _Module.AssemblyReferences)
{
if (@ref.Name == "IllusionInjector") return true;
}
return false;
}
}
public void Patch()
{
// First, let's add the reference
var nameReference = new AssemblyNameReference("IllusionInjector", new Version(1, 0, 0, 0));
var injectorPath = Path.Combine(_File.DirectoryName, "IllusionInjector.dll");
2017-01-08 16:49:11 +00:00
var injector = ModuleDefinition.ReadModule(injectorPath);
2016-12-15 20:07:03 +00:00
_Module.AssemblyReferences.Add(nameReference);
2017-01-08 16:49:11 +00:00
int patched = 0;
foreach(var type in FindEntryTypes())
{
if(PatchType(type, injector))
{
patched++;
}
}
if(patched > 0)
{
_Module.Write(_File.FullName);
} else
{
throw new Exception("Could not find any entry type!");
}
}
2016-12-15 20:07:03 +00:00
2017-01-08 16:49:11 +00:00
private bool PatchType(TypeDefinition targetType, ModuleDefinition injector)
{
2016-12-15 20:07:03 +00:00
var targetMethod = targetType.Methods.FirstOrDefault(m => m.IsConstructor && m.IsStatic);
2017-01-08 16:49:11 +00:00
if (targetMethod != null)
2016-12-15 20:07:03 +00:00
{
2017-01-08 16:49:11 +00:00
var methodReference = _Module.Import(injector.GetType("IllusionInjector.Injector").Methods.First(m => m.Name == "Inject"));
targetMethod.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, methodReference));
return true;
2016-12-15 20:07:03 +00:00
}
2017-01-08 16:49:11 +00:00
return false;
2016-12-15 20:07:03 +00:00
}
2017-01-08 16:49:11 +00:00
private IEnumerable<TypeDefinition> FindEntryTypes()
2016-12-15 20:07:03 +00:00
{
2017-01-08 16:49:11 +00:00
return _Module.GetTypes().Where(m => ENTRY_TYPES.Contains(m.Name));
2016-12-15 20:07:03 +00:00
}
}
}