Revert "refactor(Dalamud): switch to file-scoped namespaces"

This reverts commit b5f34c3199.
This commit is contained in:
goat 2021-11-18 15:23:40 +01:00
parent d473826247
commit 1561fbac00
No known key found for this signature in database
GPG key ID: 7773BB5B43BA52E5
325 changed files with 45549 additions and 45209 deletions

View file

@ -6,177 +6,178 @@ 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
namespace Dalamud.Hooking
{
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.
/// 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>
/// <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)
public sealed class AsmHook : IDisposable, IDalamudHook
{
address = HookManager.FollowJmp(address);
private readonly IntPtr address;
private readonly Reloaded.Hooks.Definitions.IAsmHook hookImpl;
var hasOtherHooks = HookManager.Originals.ContainsKey(address);
if (!hasOtherHooks)
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)
{
MemoryHelper.ReadRaw(address, 0x32, out var original);
HookManager.Originals[address] = original;
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()));
}
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)
/// <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)
{
MemoryHelper.ReadRaw(address, 0x32, out var original);
HookManager.Originals[address] = original;
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()));
}
this.address = address;
this.hookImpl = ReloadedHooks.Instance.CreateAsmHook(assembly, address.ToInt64(), (Reloaded.Hooks.Definitions.Enums.AsmHookBehaviour)asmHookBehaviour);
/// <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;
}
}
this.statsMethod = new DynamicMethod(name, null, null);
this.statsMethod.GetILGenerator().Emit(OpCodes.Ret);
var dele = this.statsMethod.CreateDelegate(typeof(Action));
/// <summary>
/// Gets a value indicating whether or not the hook is enabled.
/// </summary>
public bool IsEnabled
{
get
{
this.CheckDisposed();
return this.isEnabled;
}
}
HookManager.TrackedHooks.Add(new HookInfo(this, dele, Assembly.GetCallingAssembly()));
}
/// <summary>
/// Gets a value indicating whether or not the hook has been disposed.
/// </summary>
public bool IsDisposed { get; private set; }
/// <summary>
/// Gets a memory address of the target function.
/// </summary>
/// <exception cref="ObjectDisposedException">Hook is already disposed.</exception>
public IntPtr Address
{
get
/// <inheritdoc/>
public string BackendName => "Reloaded/Asm";
/// <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();
return this.address;
}
}
/// <summary>
/// Gets a value indicating whether or not the hook is enabled.
/// </summary>
public bool IsEnabled
{
get
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();
return this.isEnabled;
}
}
/// <summary>
/// Gets a value indicating whether or not the hook has been disposed.
/// </summary>
public bool IsDisposed { get; private set; }
if (!this.isEnabled)
return;
/// <inheritdoc/>
public string BackendName => "Reloaded/Asm";
/// <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 = false;
this.hookImpl.Disable();
}
}
if (!this.isEnabled)
/// <summary>
/// Check if this object has been disposed already.
/// </summary>
private void CheckDisposed()
{
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);
if (this.IsDisposed)
{
throw new ObjectDisposedException(message: "Hook is already disposed", null);
}
}
}
}

View file

@ -1,23 +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
namespace Dalamud.Hooking
{
/// <summary>
/// Executes your assembly code before the original.
/// 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>
ExecuteFirst = 0,
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>
/// Executes your assembly code after the original.
/// </summary>
ExecuteAfter = 1,
/// <summary>
/// Do not execute original replaced code (Dangerous!).
/// </summary>
DoNotExecuteOriginal = 2,
/// <summary>
/// Do not execute original replaced code (Dangerous!).
/// </summary>
DoNotExecuteOriginal = 2,
}
}

View file

@ -7,259 +7,260 @@ 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>
/// <typeparam name="T">Delegate type to represents a function prototype. This must be the same prototype as original function do.</typeparam>
public sealed class Hook<T> : IDisposable, IDalamudHook where T : Delegate
namespace Dalamud.Hooking
{
private readonly IntPtr address;
private readonly Reloaded.Hooks.Definitions.IHook<T> hookImpl;
private readonly MinSharp.Hook<T> minHookImpl;
private readonly bool isMinHook;
/// <summary>
/// Initializes a new instance of the <see cref="Hook{T}"/> class.
/// Hook is not activated until Enable() method is called.
/// 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>
/// <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 Hook(IntPtr address, T detour)
: this(address, detour, false, Assembly.GetCallingAssembly())
/// <typeparam name="T">Delegate type to represents a function prototype. This must be the same prototype as original function do.</typeparam>
public sealed class Hook<T> : IDisposable, IDalamudHook where T : Delegate
{
}
private readonly IntPtr address;
private readonly Reloaded.Hooks.Definitions.IHook<T> hookImpl;
private readonly MinSharp.Hook<T> minHookImpl;
private readonly bool isMinHook;
/// <summary>
/// Initializes a new instance of the <see cref="Hook{T}"/> class.
/// Hook is not activated until Enable() method is called.
/// Please do not use MinHook unless you have thoroughly troubleshot why Reloaded does not work.
/// </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="useMinHook">Use the MinHook hooking library instead of Reloaded.</param>
public Hook(IntPtr address, T detour, bool useMinHook)
: this(address, detour, useMinHook, Assembly.GetCallingAssembly())
{
}
private Hook(IntPtr address, T detour, bool useMinHook, Assembly callingAssembly)
{
address = HookManager.FollowJmp(address);
this.isMinHook = !EnvironmentConfiguration.DalamudForceReloaded && (EnvironmentConfiguration.DalamudForceMinHook || useMinHook);
var hasOtherHooks = HookManager.Originals.ContainsKey(address);
if (!hasOtherHooks)
/// <summary>
/// Initializes a new instance of the <see cref="Hook{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 Hook(IntPtr address, T detour)
: this(address, detour, false, Assembly.GetCallingAssembly())
{
MemoryHelper.ReadRaw(address, 0x32, out var original);
HookManager.Originals[address] = original;
}
this.address = address;
if (this.isMinHook)
/// <summary>
/// Initializes a new instance of the <see cref="Hook{T}"/> class.
/// Hook is not activated until Enable() method is called.
/// Please do not use MinHook unless you have thoroughly troubleshot why Reloaded does not work.
/// </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="useMinHook">Use the MinHook hooking library instead of Reloaded.</param>
public Hook(IntPtr address, T detour, bool useMinHook)
: this(address, detour, useMinHook, Assembly.GetCallingAssembly())
{
if (!HookManager.MultiHookTracker.TryGetValue(address, out var indexList))
indexList = HookManager.MultiHookTracker[address] = new();
var index = (ulong)indexList.Count;
this.minHookImpl = new MinSharp.Hook<T>(address, detour, index);
// Add afterwards, so the hookIdent starts at 0.
indexList.Add(this);
}
else
{
this.hookImpl = ReloadedHooks.Instance.CreateHook<T>(detour, address.ToInt64());
}
HookManager.TrackedHooks.Add(new HookInfo(this, detour, callingAssembly));
}
/// <summary>
/// Gets a memory address of the target function.
/// </summary>
/// <exception cref="ObjectDisposedException">Hook is already disposed.</exception>
public IntPtr Address
{
get
private Hook(IntPtr address, T detour, bool useMinHook, Assembly callingAssembly)
{
this.CheckDisposed();
return this.address;
}
}
address = HookManager.FollowJmp(address);
this.isMinHook = !EnvironmentConfiguration.DalamudForceReloaded && (EnvironmentConfiguration.DalamudForceMinHook || useMinHook);
/// <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();
var hasOtherHooks = HookManager.Originals.ContainsKey(address);
if (!hasOtherHooks)
{
MemoryHelper.ReadRaw(address, 0x32, out var original);
HookManager.Originals[address] = original;
}
this.address = address;
if (this.isMinHook)
{
return this.minHookImpl.Original;
if (!HookManager.MultiHookTracker.TryGetValue(address, out var indexList))
indexList = HookManager.MultiHookTracker[address] = new();
var index = (ulong)indexList.Count;
this.minHookImpl = new MinSharp.Hook<T>(address, detour, index);
// Add afterwards, so the hookIdent starts at 0.
indexList.Add(this);
}
else
{
return this.hookImpl.OriginalFunction;
this.hookImpl = ReloadedHooks.Instance.CreateHook<T>(detour, address.ToInt64());
}
}
}
/// <summary>
/// Gets a value indicating whether or not the hook is enabled.
/// </summary>
public bool IsEnabled
{
get
HookManager.TrackedHooks.Add(new HookInfo(this, detour, callingAssembly));
}
/// <summary>
/// Gets a memory address of the target function.
/// </summary>
/// <exception cref="ObjectDisposedException">Hook is already disposed.</exception>
public IntPtr Address
{
this.CheckDisposed();
if (this.isMinHook)
get
{
return this.minHookImpl.Enabled;
this.CheckDisposed();
return this.address;
}
else
}
/// <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
{
return this.hookImpl.IsHookEnabled;
this.CheckDisposed();
if (this.isMinHook)
{
return this.minHookImpl.Original;
}
else
{
return this.hookImpl.OriginalFunction;
}
}
}
}
/// <summary>
/// Gets a value indicating whether or not the hook has been disposed.
/// </summary>
public bool IsDisposed { get; private set; }
/// <inheritdoc/>
public string BackendName
{
get
/// <summary>
/// Gets a value indicating whether or not the hook is enabled.
/// </summary>
public bool IsEnabled
{
if (this.isMinHook)
return "MinHook";
return "Reloaded";
}
}
/// <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 Hook<T> FromSymbol(string moduleName, string exportName, T detour)
=> FromSymbol(moduleName, exportName, detour, false);
/// <summary>
/// Creates a hook. Hooking address is inferred by calling to GetProcAddress() function.
/// The hook is not activated until Enable() method is called.
/// Please do not use MinHook unless you have thoroughly troubleshot why Reloaded does not work.
/// </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>
/// <param name="useMinHook">Use the MinHook hooking library instead of Reloaded.</param>
/// <returns>The hook with the supplied parameters.</returns>
public static Hook<T> FromSymbol(string moduleName, string exportName, T detour, bool useMinHook)
{
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 Hook<T>(procAddress, detour, useMinHook);
}
/// <summary>
/// Remove a hook from the current process.
/// </summary>
public void Dispose()
{
if (this.IsDisposed)
return;
if (this.isMinHook)
{
this.minHookImpl.Dispose();
var index = HookManager.MultiHookTracker[this.address].IndexOf(this);
HookManager.MultiHookTracker[this.address][index] = null;
}
else
{
this.Disable();
}
this.IsDisposed = true;
}
/// <summary>
/// Starts intercepting a call to the function.
/// </summary>
public void Enable()
{
this.CheckDisposed();
if (this.isMinHook)
{
if (!this.minHookImpl.Enabled)
get
{
this.minHookImpl.Enable();
this.CheckDisposed();
if (this.isMinHook)
{
return this.minHookImpl.Enabled;
}
else
{
return this.hookImpl.IsHookEnabled;
}
}
}
else
/// <summary>
/// Gets a value indicating whether or not the hook has been disposed.
/// </summary>
public bool IsDisposed { get; private set; }
/// <inheritdoc/>
public string BackendName
{
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.isMinHook)
{
if (this.minHookImpl.Enabled)
get
{
this.minHookImpl.Disable();
if (this.isMinHook)
return "MinHook";
return "Reloaded";
}
}
else
/// <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 Hook<T> FromSymbol(string moduleName, string exportName, T detour)
=> FromSymbol(moduleName, exportName, detour, false);
/// <summary>
/// Creates a hook. Hooking address is inferred by calling to GetProcAddress() function.
/// The hook is not activated until Enable() method is called.
/// Please do not use MinHook unless you have thoroughly troubleshot why Reloaded does not work.
/// </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>
/// <param name="useMinHook">Use the MinHook hooking library instead of Reloaded.</param>
/// <returns>The hook with the supplied parameters.</returns>
public static Hook<T> FromSymbol(string moduleName, string exportName, T detour, bool useMinHook)
{
if (!this.hookImpl.IsHookActivated)
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 Hook<T>(procAddress, detour, useMinHook);
}
/// <summary>
/// Remove a hook from the current process.
/// </summary>
public void Dispose()
{
if (this.IsDisposed)
return;
if (this.hookImpl.IsHookEnabled)
this.hookImpl.Disable();
}
}
if (this.isMinHook)
{
this.minHookImpl.Dispose();
/// <summary>
/// Check if this object has been disposed already.
/// </summary>
private void CheckDisposed()
{
if (this.IsDisposed)
var index = HookManager.MultiHookTracker[this.address].IndexOf(this);
HookManager.MultiHookTracker[this.address][index] = null;
}
else
{
this.Disable();
}
this.IsDisposed = true;
}
/// <summary>
/// Starts intercepting a call to the function.
/// </summary>
public void Enable()
{
throw new ObjectDisposedException(message: "Hook is already disposed", null);
this.CheckDisposed();
if (this.isMinHook)
{
if (!this.minHookImpl.Enabled)
{
this.minHookImpl.Enable();
}
}
else
{
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.isMinHook)
{
if (this.minHookImpl.Enabled)
{
this.minHookImpl.Disable();
}
}
else
{
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(message: "Hook is already disposed", null);
}
}
}
}

View file

@ -1,29 +1,30 @@
using System;
namespace Dalamud.Hooking;
/// <summary>
/// Interface describing a generic hook.
/// </summary>
public interface IDalamudHook
namespace Dalamud.Hooking
{
/// <summary>
/// Gets the address to hook.
/// Interface describing a generic hook.
/// </summary>
public IntPtr Address { get; }
public 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 enabled.
/// </summary>
public bool IsEnabled { get; }
/// <summary>
/// Gets a value indicating whether or not the hook is disposed.
/// </summary>
public bool IsDisposed { get; }
/// <summary>
/// Gets a value indicating whether or not the hook is disposed.
/// </summary>
public bool IsDisposed { get; }
/// <summary>
/// Gets the name of the hooking backend used for the hook.
/// </summary>
public string BackendName { get; }
/// <summary>
/// Gets the name of the hooking backend used for the hook.
/// </summary>
public string BackendName { get; }
}
}

View file

@ -2,72 +2,73 @@ using System;
using System.Diagnostics;
using System.Reflection;
namespace Dalamud.Hooking.Internal;
/// <summary>
/// Class containing information about registered hooks.
/// </summary>
internal class HookInfo
namespace Dalamud.Hooking.Internal
{
private ulong? inProcessMemory = 0;
/// <summary>
/// Initializes a new instance of the <see cref="HookInfo"/> class.
/// Class containing information about registered hooks.
/// </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)
internal class HookInfo
{
this.Hook = hook;
this.Delegate = hookDelegate;
this.Assembly = assembly;
}
private ulong? inProcessMemory = 0;
/// <summary>
/// Gets the RVA of the hook.
/// </summary>
internal ulong? InProcessMemory
{
get
/// <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)
{
if (this.Hook.IsDisposed)
return 0;
this.Hook = hook;
this.Delegate = hookDelegate;
this.Assembly = assembly;
}
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();
var end = begin + (ulong)p.ModuleMemorySize;
var hookAddr = (ulong)this.Hook.Address.ToInt64();
if (hookAddr >= begin && hookAddr <= end)
/// <summary>
/// Gets the RVA of the hook.
/// </summary>
internal ulong? InProcessMemory
{
get
{
return this.inProcessMemory = hookAddr - begin;
}
else
{
return this.inProcessMemory = null;
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();
var end = begin + (ulong)p.ModuleMemorySize;
var hookAddr = (ulong)this.Hook.Address.ToInt64();
if (hookAddr >= begin && hookAddr <= end)
{
return this.inProcessMemory = hookAddr - begin;
}
else
{
return this.inProcessMemory = null;
}
}
}
/// <summary>
/// Gets the tracked hook.
/// </summary>
internal IDalamudHook Hook { get; }
/// <summary>
/// Gets the tracked delegate.
/// </summary>
internal Delegate Delegate { get; }
/// <summary>
/// Gets the assembly implementing the hook.
/// </summary>
internal Assembly Assembly { get; }
}
/// <summary>
/// Gets the tracked hook.
/// </summary>
internal IDalamudHook Hook { get; }
/// <summary>
/// Gets the tracked delegate.
/// </summary>
internal Delegate Delegate { get; }
/// <summary>
/// Gets the assembly implementing the hook.
/// </summary>
internal Assembly Assembly { get; }
}

View file

@ -3,140 +3,143 @@ using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using Dalamud.Configuration.Internal;
using Dalamud.Logging.Internal;
using Dalamud.Memory;
using Iced.Intel;
using Microsoft.Win32;
namespace Dalamud.Hooking.Internal;
/// <summary>
/// This class manages the final disposition of hooks, cleaning up any that have not reverted their changes.
/// </summary>
internal class HookManager : IDisposable
namespace Dalamud.Hooking.Internal
{
private static readonly ModuleLog Log = new("HM");
/// <summary>
/// Initializes a new instance of the <see cref="HookManager"/> class.
/// This class manages the final disposition of hooks, cleaning up any that have not reverted their changes.
/// </summary>
public HookManager()
internal class HookManager : IDisposable
{
}
private static readonly ModuleLog Log = new("HM");
/// <summary>
/// Gets a static list of tracked and registered hooks.
/// </summary>
internal static List<HookInfo> TrackedHooks { get; } = new();
/// <summary>
/// Gets a static dictionary of original code for a hooked address.
/// </summary>
internal static Dictionary<IntPtr, byte[]> Originals { get; } = new();
/// <summary>
/// Gets a static dictionary of the number of hooks on a given address.
/// </summary>
internal static Dictionary<IntPtr, List<IDalamudHook?>> MultiHookTracker { get; } = new();
/// <inheritdoc/>
public void Dispose()
{
RevertHooks();
TrackedHooks.Clear();
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)
/// <summary>
/// Initializes a new instance of the <see cref="HookManager"/> class.
/// </summary>
public HookManager()
{
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>
/// Gets a static list of tracked and registered hooks.
/// </summary>
internal static List<HookInfo> TrackedHooks { get; } = new();
private static unsafe void RevertHooks()
{
foreach (var (address, originalBytes) in Originals)
/// <summary>
/// Gets a static dictionary of original code for a hooked address.
/// </summary>
internal static Dictionary<IntPtr, byte[]> Originals { get; } = new();
/// <summary>
/// Gets a static dictionary of the number of hooks on a given address.
/// </summary>
internal static Dictionary<IntPtr, List<IDalamudHook?>> MultiHookTracker { get; } = new();
/// <inheritdoc/>
public void Dispose()
{
var i = 0;
var current = (byte*)address;
// Find how many bytes have been modified by comparing to the saved original
for (; i < originalBytes.Length; i++)
RevertHooks();
TrackedHooks.Clear();
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)
{
if (current[i] == originalBytes[i])
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;
}
}
var snippet = originalBytes[0..i];
return address;
}
if (i > 0)
private static unsafe void RevertHooks()
{
foreach (var (address, originalBytes) in Originals)
{
Log.Verbose($"Reverting hook at 0x{address.ToInt64():X} ({snippet.Length} bytes)");
MemoryHelper.ChangePermission(address, i, MemoryProtection.ExecuteReadWrite, out var oldPermissions);
MemoryHelper.WriteRaw(address, snippet);
MemoryHelper.ChangePermission(address, i, oldPermissions);
var i = 0;
var current = (byte*)address;
// Find how many bytes have been modified by comparing to the saved original
for (; i < originalBytes.Length; i++)
{
if (current[i] == originalBytes[i])
break;
}
var snippet = originalBytes[0..i];
if (i > 0)
{
Log.Verbose($"Reverting hook at 0x{address.ToInt64():X} ({snippet.Length} bytes)");
MemoryHelper.ChangePermission(address, i, MemoryProtection.ExecuteReadWrite, out var oldPermissions);
MemoryHelper.WriteRaw(address, snippet);
MemoryHelper.ChangePermission(address, i, oldPermissions);
}
}
}
}