feat: AsmHook

This commit is contained in:
Raymond 2021-08-30 16:33:57 -04:00
parent 3fd1637cf0
commit 369d7af8a0
4 changed files with 278 additions and 75 deletions

180
Dalamud/Hooking/AsmHook.cs Normal file
View file

@ -0,0 +1,180 @@
using System;
using System.Reflection;
using System.Reflection.Emit;
using Dalamud.Hooking.Internal;
using Dalamud.Memory;
using Reloaded.Hooks;
namespace Dalamud.Hooking
{
/// <summary>
/// Manages a hook which can be used to intercept a call to native function.
/// This class is basically a thin wrapper around the LocalHook type to provide helper functions.
/// </summary>
public sealed class AsmHook : IDisposable, IDalamudHook
{
private readonly IntPtr address;
private readonly Reloaded.Hooks.Definitions.IAsmHook hookImpl;
private bool isActivated = false;
private bool isEnabled = false;
private DynamicMethod statsMethod;
/// <summary>
/// Initializes a new instance of the <see cref="AsmHook"/> class.
/// This is an assembly hook and should not be used for except under unique circumstances.
/// Hook is not activated until Enable() method is called.
/// </summary>
/// <param name="address">A memory address to install a hook.</param>
/// <param name="assembly">Assembly code representing your hook.</param>
/// <param name="name">The name of what you are hooking, since a delegate is not required.</param>
/// <param name="asmHookBehaviour">How the hook is inserted into the execution flow.</param>
public AsmHook(IntPtr address, byte[] assembly, string name, AsmHookBehaviour asmHookBehaviour = AsmHookBehaviour.ExecuteFirst)
{
address = HookManager.FollowJmp(address);
var hasOtherHooks = HookManager.Originals.ContainsKey(address);
if (!hasOtherHooks)
{
MemoryHelper.ReadRaw(address, 0x32, out var original);
HookManager.Originals[address] = original;
}
this.address = address;
this.hookImpl = ReloadedHooks.Instance.CreateAsmHook(assembly, address.ToInt64(), (Reloaded.Hooks.Definitions.Enums.AsmHookBehaviour)asmHookBehaviour);
this.statsMethod = new DynamicMethod(name, null, null);
this.statsMethod.GetILGenerator().Emit(OpCodes.Ret);
var dele = this.statsMethod.CreateDelegate(typeof(Action));
HookManager.TrackedHooks.Add(new HookInfo(this, dele, Assembly.GetCallingAssembly()));
}
/// <summary>
/// Initializes a new instance of the <see cref="AsmHook"/> class.
/// This is an assembly hook and should not be used for except under unique circumstances.
/// Hook is not activated until Enable() method is called.
/// </summary>
/// <param name="address">A memory address to install a hook.</param>
/// <param name="assembly">FASM syntax assembly code representing your hook. The first line should be use64.</param>
/// <param name="name">The name of what you are hooking, since a delegate is not required.</param>
/// <param name="asmHookBehaviour">How the hook is inserted into the execution flow.</param>
public AsmHook(IntPtr address, string[] assembly, string name, AsmHookBehaviour asmHookBehaviour = AsmHookBehaviour.ExecuteFirst)
{
address = HookManager.FollowJmp(address);
var hasOtherHooks = HookManager.Originals.ContainsKey(address);
if (!hasOtherHooks)
{
MemoryHelper.ReadRaw(address, 0x32, out var original);
HookManager.Originals[address] = original;
}
this.address = address;
this.hookImpl = ReloadedHooks.Instance.CreateAsmHook(assembly, address.ToInt64(), (Reloaded.Hooks.Definitions.Enums.AsmHookBehaviour)asmHookBehaviour);
this.statsMethod = new DynamicMethod(name, null, null);
this.statsMethod.GetILGenerator().Emit(OpCodes.Ret);
var dele = this.statsMethod.CreateDelegate(typeof(Action));
HookManager.TrackedHooks.Add(new HookInfo(this, dele, Assembly.GetCallingAssembly()));
}
/// <summary>
/// Gets a memory address of the target function.
/// </summary>
/// <exception cref="ObjectDisposedException">Hook is already disposed.</exception>
public IntPtr Address
{
get
{
this.CheckDisposed();
return this.address;
}
}
/// <summary>
/// Gets a value indicating whether or not the hook is enabled.
/// </summary>
public bool IsEnabled
{
get
{
this.CheckDisposed();
return this.isEnabled;
}
}
/// <summary>
/// Gets a value indicating whether or not the hook has been disposed.
/// </summary>
public bool IsDisposed { get; private set; }
/// <summary>
/// Remove a hook from the current process.
/// </summary>
public void Dispose()
{
if (this.IsDisposed)
return;
this.IsDisposed = true;
if (this.isEnabled)
{
this.isEnabled = false;
this.hookImpl.Disable();
}
}
/// <summary>
/// Starts intercepting a call to the function.
/// </summary>
public void Enable()
{
this.CheckDisposed();
if (!this.isActivated)
{
this.isActivated = true;
this.hookImpl.Activate();
}
if (!this.isEnabled)
{
this.isEnabled = true;
this.hookImpl.Enable();
}
}
/// <summary>
/// Stops intercepting a call to the function.
/// </summary>
public void Disable()
{
this.CheckDisposed();
if (!this.isEnabled)
return;
if (this.isEnabled)
{
this.isEnabled = false;
this.hookImpl.Disable();
}
}
/// <summary>
/// Check if this object has been disposed already.
/// </summary>
private void CheckDisposed()
{
if (this.IsDisposed)
{
throw new ObjectDisposedException(message: "Hook is already disposed", null);
}
}
}
}

View file

@ -0,0 +1,24 @@
namespace Dalamud.Hooking
{
/// <summary>
/// Defines the behaviour used by the Dalamud.Hooking.AsmHook.
/// This is equivalent to the same enumeration in Reloaded and is included so you do not have to reference the assembly.
/// </summary>
public enum AsmHookBehaviour
{
/// <summary>
/// Executes your assembly code before the original.
/// </summary>
ExecuteFirst = 0,
/// <summary>
/// Executes your assembly code after the original.
/// </summary>
ExecuteAfter = 1,
/// <summary>
/// Do not execute original replaced code (Dangerous!).
/// </summary>
DoNotExecuteOriginal = 2,
}
}

View file

@ -1,13 +1,9 @@
using System;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using Dalamud.Hooking.Internal;
using Dalamud.Memory;
using Iced.Intel;
using Reloaded.Hooks;
using Serilog;
namespace Dalamud.Hooking
{
@ -29,7 +25,7 @@ namespace Dalamud.Hooking
/// <param name="detour">Callback function. Delegate must have a same original function prototype.</param>
public Hook(IntPtr address, T detour)
{
address = FollowJmp(address);
address = HookManager.FollowJmp(address);
var hasOtherHooks = HookManager.Originals.ContainsKey(address);
if (!hasOtherHooks)
@ -150,76 +146,6 @@ namespace Dalamud.Hooking
this.hookImpl.Disable();
}
/// <summary>
/// Follow a JMP or Jcc instruction to the next logical location.
/// </summary>
/// <param name="address">Address of the instruction.</param>
/// <returns>The address referenced by the jmp.</returns>
private static IntPtr FollowJmp(IntPtr address)
{
while (true)
{
var hasOtherHooks = HookManager.Originals.ContainsKey(address);
if (hasOtherHooks)
{
// This address has been hooked already. Do not follow a jmp into a trampoline of our own making.
Log.Verbose($"Detected hook trampoline at {address.ToInt64():X}, stopping jump resolution.");
return address;
}
var bytes = MemoryHelper.ReadRaw(address, 8);
var codeReader = new ByteArrayCodeReader(bytes);
var decoder = Decoder.Create(64, codeReader);
decoder.IP = (ulong)address.ToInt64();
decoder.Decode(out var inst);
if (inst.Mnemonic == Mnemonic.Jmp)
{
var kind = inst.Op0Kind;
IntPtr newAddress;
switch (inst.Op0Kind)
{
case OpKind.NearBranch64:
case OpKind.NearBranch32:
case OpKind.NearBranch16:
newAddress = (IntPtr)inst.NearBranchTarget;
break;
case OpKind.Immediate16:
case OpKind.Immediate8to16:
case OpKind.Immediate8to32:
case OpKind.Immediate8to64:
case OpKind.Immediate32to64:
case OpKind.Immediate32 when IntPtr.Size == 4:
case OpKind.Immediate64:
newAddress = (IntPtr)inst.GetImmediate(0);
break;
case OpKind.Memory when inst.IsIPRelativeMemoryOperand:
newAddress = (IntPtr)inst.IPRelativeMemoryAddress;
newAddress = Marshal.ReadIntPtr(newAddress);
break;
case OpKind.Memory:
newAddress = (IntPtr)inst.MemoryDisplacement64;
newAddress = Marshal.ReadIntPtr(newAddress);
break;
default:
var debugBytes = string.Join(" ", bytes.Take(inst.Length).Select(b => $"{b:X2}"));
throw new Exception($"Unknown OpKind {inst.Op0Kind} from {debugBytes}");
}
Log.Verbose($"Resolving assembly jump ({kind}) from {address.ToInt64():X} to {newAddress.ToInt64():X}");
address = newAddress;
}
else
{
break;
}
}
return address;
}
/// <summary>
/// Check if this object has been disposed already.
/// </summary>

View file

@ -1,8 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using Dalamud.Logging.Internal;
using Dalamud.Memory;
using Iced.Intel;
using Microsoft.Win32;
namespace Dalamud.Hooking.Internal
@ -83,6 +86,76 @@ namespace Dalamud.Hooking.Internal
Originals.Clear();
}
/// <summary>
/// Follow a JMP or Jcc instruction to the next logical location.
/// </summary>
/// <param name="address">Address of the instruction.</param>
/// <returns>The address referenced by the jmp.</returns>
internal static IntPtr FollowJmp(IntPtr address)
{
while (true)
{
var hasOtherHooks = HookManager.Originals.ContainsKey(address);
if (hasOtherHooks)
{
// This address has been hooked already. Do not follow a jmp into a trampoline of our own making.
Log.Verbose($"Detected hook trampoline at {address.ToInt64():X}, stopping jump resolution.");
return address;
}
var bytes = MemoryHelper.ReadRaw(address, 8);
var codeReader = new ByteArrayCodeReader(bytes);
var decoder = Decoder.Create(64, codeReader);
decoder.IP = (ulong)address.ToInt64();
decoder.Decode(out var inst);
if (inst.Mnemonic == Mnemonic.Jmp)
{
var kind = inst.Op0Kind;
IntPtr newAddress;
switch (inst.Op0Kind)
{
case OpKind.NearBranch64:
case OpKind.NearBranch32:
case OpKind.NearBranch16:
newAddress = (IntPtr)inst.NearBranchTarget;
break;
case OpKind.Immediate16:
case OpKind.Immediate8to16:
case OpKind.Immediate8to32:
case OpKind.Immediate8to64:
case OpKind.Immediate32to64:
case OpKind.Immediate32 when IntPtr.Size == 4:
case OpKind.Immediate64:
newAddress = (IntPtr)inst.GetImmediate(0);
break;
case OpKind.Memory when inst.IsIPRelativeMemoryOperand:
newAddress = (IntPtr)inst.IPRelativeMemoryAddress;
newAddress = Marshal.ReadIntPtr(newAddress);
break;
case OpKind.Memory:
newAddress = (IntPtr)inst.MemoryDisplacement64;
newAddress = Marshal.ReadIntPtr(newAddress);
break;
default:
var debugBytes = string.Join(" ", bytes.Take(inst.Length).Select(b => $"{b:X2}"));
throw new Exception($"Unknown OpKind {inst.Op0Kind} from {debugBytes}");
}
Log.Verbose($"Resolving assembly jump ({kind}) from {address.ToInt64():X} to {newAddress.ToInt64():X}");
address = newAddress;
}
else
{
break;
}
}
return address;
}
private static unsafe void RevertHooks()
{
foreach (var (address, originalBytes) in Originals)