Hook Changes

This commit is contained in:
Raymond 2021-08-02 17:08:01 -04:00
parent 42be18965d
commit 984ff81cb5
10 changed files with 231 additions and 434 deletions

View file

@ -1,5 +1,4 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
@ -12,6 +11,19 @@ namespace Dalamud.Hooking.Internal
{
private ulong? inProcessMemory = 0;
/// <summary>
/// Initializes a new instance of the <see cref="HookInfo"/> class.
/// </summary>
/// <param name="hook">The tracked hook.</param>
/// <param name="hookDelegate">The hook delegate.</param>
/// <param name="assembly">The assembly implementing the hook.</param>
public HookInfo(IDalamudHook hook, Delegate hookDelegate, Assembly assembly)
{
this.Hook = hook;
this.Delegate = hookDelegate;
this.Assembly = assembly;
}
/// <summary>
/// Gets the RVA of the hook.
/// </summary>
@ -19,9 +31,14 @@ namespace Dalamud.Hooking.Internal
{
get
{
if (this.Hook.IsDisposed) return 0;
if (this.inProcessMemory == null) return null;
if (this.inProcessMemory.Value > 0) return this.inProcessMemory.Value;
if (this.Hook.IsDisposed)
return 0;
if (this.inProcessMemory == null)
return null;
if (this.inProcessMemory.Value > 0)
return this.inProcessMemory.Value;
var p = Process.GetCurrentProcess().MainModule;
var begin = (ulong)p.BaseAddress.ToInt64();
@ -30,30 +47,28 @@ namespace Dalamud.Hooking.Internal
if (hookAddr >= begin && hookAddr <= end)
{
this.inProcessMemory = hookAddr - begin;
return this.inProcessMemory.Value;
return this.inProcessMemory = hookAddr - begin;
}
else
{
this.inProcessMemory = null;
return null;
return this.inProcessMemory = null;
}
}
}
/// <summary>
/// Gets or sets the tracked hook.
/// Gets the tracked hook.
/// </summary>
internal IDalamudHook Hook { get; set; }
internal IDalamudHook Hook { get; }
/// <summary>
/// Gets or sets the tracked delegate.
/// Gets the tracked delegate.
/// </summary>
internal Delegate Delegate { get; set; }
internal Delegate Delegate { get; }
/// <summary>
/// Gets or sets the hooked assembly.
/// Gets the hooked assembly.
/// </summary>
internal Assembly Assembly { get; set; }
internal Assembly Assembly { get; }
}
}

View file

@ -2,6 +2,7 @@ using System;
using System.Collections.Generic;
using Dalamud.Memory;
using Microsoft.Win32;
namespace Dalamud.Hooking.Internal
{
@ -33,8 +34,32 @@ namespace Dalamud.Hooking.Internal
{
if (checkLinuxOnce)
{
var value = Environment.GetEnvironmentVariable("XL_WINEONLINUX");
isRunningLinux = value is not null;
checkLinuxOnce = false;
bool Check1()
{
return Environment.GetEnvironmentVariable("XL_WINEONLINUX") != null;
}
bool Check2()
{
var hModule = NativeFunctions.GetModuleHandleW("ntdll.dll");
var proc1 = NativeFunctions.GetProcAddress(hModule, "wine_get_version");
var proc2 = NativeFunctions.GetProcAddress(hModule, "wine_get_build_id");
return proc1 != IntPtr.Zero || proc2 != IntPtr.Zero;
}
bool Check3()
{
return Registry.CurrentUser.OpenSubKey(@"Software\Wine") != null ||
Registry.LocalMachine.OpenSubKey(@"Software\Wine") != null;
}
if (isRunningLinux = Check1() || Check2() || Check3())
{
Log.Information($"Dalamud detected running on Wine");
}
}
return isRunningLinux;
@ -47,9 +72,9 @@ namespace Dalamud.Hooking.Internal
internal static List<HookInfo> TrackedHooks { get; } = new();
/// <summary>
/// Gets a static list of original code for a hooked address.
/// Gets a static dictionary of original code for a hooked address.
/// </summary>
internal static List<(IntPtr Address, byte[] Original)> Originals { get; } = new();
internal static Dictionary<IntPtr, byte[]> Originals { get; } = new();
/// <inheritdoc/>
public void Dispose()
@ -74,7 +99,7 @@ namespace Dalamud.Hooking.Internal
if (i > 0)
{
Log.Debug($"Reverting hook at 0x{address.ToInt64():X}");
Log.Verbose($"Reverting hook at 0x{address.ToInt64():X}");
fixed (byte* original = originalBytes)
{
MemoryHelper.ChangePermission(address, i, MemoryProtection.ExecuteReadWrite, out var oldPermissions);

View file

@ -1,25 +0,0 @@
using System;
namespace Dalamud.Hooking.Internal
{
/// <summary>
/// Interface describing a generic hook.
/// </summary>
internal interface IDalamudHook
{
/// <summary>
/// Gets the address to hook.
/// </summary>
public IntPtr Address { get; }
/// <summary>
/// Gets a value indicating whether or not the hook is enabled.
/// </summary>
public bool IsEnabled { get; }
/// <summary>
/// Gets a value indicating whether or not the hook is disposed.
/// </summary>
public bool IsDisposed { get; }
}
}

View file

@ -1,133 +0,0 @@
using System;
using System.Reflection;
using System.Runtime.InteropServices;
namespace Dalamud.Hooking.Internal.Implementations
{
/// <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>
/// <typeparam name="T">Delegate type to represents a function prototype. This must be the same prototype as original function do.</typeparam>
internal sealed class CoreHookImpl<T> : IDisposable, IDalamudHookImpl<T> where T : Delegate
{
private readonly IntPtr address;
private readonly CoreHook.LocalHook hookImpl;
private readonly T original;
/// <summary>
/// Initializes a new instance of the <see cref="CoreHookImpl{T}"/> class.
/// Hook is not activated until Enable() method is called.
/// </summary>
/// <param name="address">A memory address to install a hook.</param>
/// <param name="detour">Callback function. Delegate must have a same original function prototype.</param>
public CoreHookImpl(IntPtr address, T detour)
{
this.address = address;
this.hookImpl = CoreHook.LocalHook.Create(address, detour, null);
this.original = Marshal.GetDelegateForFunctionPointer<T>(this.hookImpl.OriginalAddress);
HookManager.TrackedHooks.Add(new HookInfo(this, detour, 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 delegate function that can be used to call the actual function as if function is not hooked yet.
/// </summary>
/// <exception cref="ObjectDisposedException">Hook is already disposed.</exception>
public T Original
{
get
{
this.CheckDisposed();
return this.original;
}
}
/// <summary>
/// Gets a value indicating whether or not the hook is enabled.
/// </summary>
public bool IsEnabled
{
get
{
this.CheckDisposed();
return this.hookImpl.ThreadACL.IsExclusive;
}
}
/// <summary>
/// Gets a value indicating whether or not the hook has been disposed.
/// </summary>
public bool IsDisposed { get; private set; }
/// <summary>
/// Creates a hook. Hooking address is inferred by calling to GetProcAddress() function.
/// The hook is not activated until Enable() method is called.
/// </summary>
/// <param name="moduleName">A name of the module currently loaded in the memory. (e.g. ws2_32.dll).</param>
/// <param name="exportName">A name of the exported function name (e.g. send).</param>
/// <param name="detour">Callback function. Delegate must have a same original function prototype.</param>
/// <returns>The hook with the supplied parameters.</returns>
public static IDalamudHookImpl<T> FromSymbol(string moduleName, string exportName, T detour)
{
var address = CoreHook.LocalHook.GetProcAddress(moduleName, exportName);
return new CoreHookImpl<T>(address, detour);
}
/// <summary>
/// Remove a hook from the current process.
/// </summary>
public void Dispose()
{
if (this.IsDisposed)
return;
this.IsDisposed = true;
this.hookImpl.Dispose();
}
/// <summary>
/// Starts intercepting a call to the function.
/// </summary>
public void Enable()
{
this.CheckDisposed();
this.hookImpl.ThreadACL.SetExclusiveACL(null);
}
/// <summary>
/// Stops intercepting a call to the function.
/// </summary>
public void Disable()
{
this.CheckDisposed();
this.hookImpl.ThreadACL.SetExclusiveACL(null);
}
/// <summary>
/// Check if this object has been disposed already.
/// </summary>
private void CheckDisposed()
{
if (this.IsDisposed)
{
throw new ObjectDisposedException("Hook is already disposed.");
}
}
}
}

View file

@ -1,28 +0,0 @@
using System;
namespace Dalamud.Hooking.Internal.Implementations
{
/// <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>
/// <typeparam name="T">Delegate type to represents a function prototype. This must be the same prototype as original function do.</typeparam>
internal interface IDalamudHookImpl<T> : IDisposable, IDalamudHook where T : Delegate
{
/// <summary>
/// Gets a delegate function that can be used to call the actual function as if function is not hooked yet.
/// </summary>
/// <exception cref="ObjectDisposedException">Hook is already disposed.</exception>
public T Original { get; }
/// <summary>
/// Starts intercepting a call to the function.
/// </summary>
public void Enable();
/// <summary>
/// Stops intercepting a call to the function.
/// </summary>
public void Disable();
}
}

View file

@ -1,196 +0,0 @@
using System;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using Dalamud.Memory;
namespace Dalamud.Hooking.Internal.Implementations
{
/// <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>
/// <typeparam name="T">Delegate type to represents a function prototype. This must be the same prototype as original function do.</typeparam>
internal sealed class ReloadedHookImpl<T> : IDalamudHookImpl<T> where T : Delegate
{
private readonly IntPtr address;
private readonly Reloaded.Hooks.Definitions.IHook<T> hookImpl;
/// <summary>
/// Initializes a new instance of the <see cref="ReloadedHookImpl{T}"/> class.
/// Hook is not activated until Enable() method is called.
/// </summary>
/// <param name="address">A memory address to install a hook.</param>
/// <param name="detour">Callback function. Delegate must have a same original function prototype.</param>
public ReloadedHookImpl(IntPtr address, T detour)
: this(address, detour, false)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ReloadedHookImpl{T}"/> class.
/// Hook is not activated until Enable() method is called.
/// </summary>
/// <param name="address">A memory address to install a hook.</param>
/// <param name="detour">Callback function. Delegate must have a same original function prototype.</param>
/// <param name="followJmp">Follow any JMPs to the actual method that needs hooking.</param>
public ReloadedHookImpl(IntPtr address, T detour, bool followJmp)
{
if (followJmp)
{
// This is horrible hackery to follow various types of JMP.
// It likely needs to stop when entering a reloaded hook trampoline.
// I would much rather use Iced to check against a Instruction type.
while (true)
{
var b1 = Marshal.ReadByte(address);
if (b1 == 0xE9)
{
var jumpOffset = Marshal.ReadInt32(address + 1);
address += jumpOffset + 5;
continue;
}
var b2 = Marshal.ReadByte(address, 1);
if (b1 == 0xFF && b2 == 0x25)
{
address = Marshal.ReadIntPtr(address + 6);
continue;
}
break;
}
}
var otherHook = HookManager.Originals.FirstOrDefault(o => o.Address == address);
if (otherHook == default)
{
MemoryHelper.ReadRaw(address, 50, out var original);
HookManager.Originals.Add((address, original));
}
this.address = address;
this.hookImpl = Reloaded.Hooks.ReloadedHooks.Instance.CreateHook<T>(detour, address.ToInt64());
HookManager.TrackedHooks.Add(new HookInfo(this, detour, 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 delegate function that can be used to call the actual function as if function is not hooked yet.
/// </summary>
/// <exception cref="ObjectDisposedException">Hook is already disposed.</exception>
public T Original
{
get
{
this.CheckDisposed();
return this.hookImpl.OriginalFunction;
}
}
/// <summary>
/// Gets a value indicating whether or not the hook is enabled.
/// </summary>
public bool IsEnabled
{
get
{
this.CheckDisposed();
return this.hookImpl.IsHookEnabled;
}
}
/// <summary>
/// Gets a value indicating whether or not the hook has been disposed.
/// </summary>
public bool IsDisposed { get; private set; }
/// <summary>
/// Creates a hook. Hooking address is inferred by calling to GetProcAddress() function.
/// The hook is not activated until Enable() method is called.
/// </summary>
/// <param name="moduleName">A name of the module currently loaded in the memory. (e.g. ws2_32.dll).</param>
/// <param name="exportName">A name of the exported function name (e.g. send).</param>
/// <param name="detour">Callback function. Delegate must have a same original function prototype.</param>
/// <returns>The hook with the supplied parameters.</returns>
public static IDalamudHookImpl<T> FromSymbol(string moduleName, string exportName, T detour)
{
var moduleHandle = NativeFunctions.GetModuleHandleW(moduleName);
if (moduleHandle == IntPtr.Zero)
throw new Exception($"Could not get a handle to module {moduleName}");
var procAddress = NativeFunctions.GetProcAddress(moduleHandle, exportName);
if (procAddress == IntPtr.Zero)
throw new Exception($"Could not get the address of {moduleName}::{exportName}");
return new ReloadedHookImpl<T>(procAddress, detour, true);
}
/// <summary>
/// Remove a hook from the current process.
/// </summary>
public void Dispose()
{
if (this.IsDisposed)
return;
this.IsDisposed = true;
if (this.hookImpl.IsHookEnabled)
this.hookImpl.Disable();
}
/// <summary>
/// Starts intercepting a call to the function.
/// </summary>
public void Enable()
{
this.CheckDisposed();
if (!this.hookImpl.IsHookActivated)
this.hookImpl.Activate();
if (!this.hookImpl.IsHookEnabled)
this.hookImpl.Enable();
}
/// <summary>
/// Stops intercepting a call to the function.
/// </summary>
public void Disable()
{
this.CheckDisposed();
if (!this.hookImpl.IsHookActivated)
return;
if (this.hookImpl.IsHookEnabled)
this.hookImpl.Disable();
}
/// <summary>
/// Check if this object has been disposed already.
/// </summary>
private void CheckDisposed()
{
if (this.IsDisposed)
{
throw new ObjectDisposedException("Hook is already disposed.");
}
}
}
}