Merge pull request #448 from daemitus/HookChanges

Proposed hook changes
This commit is contained in:
goaaats 2021-08-04 23:25:27 +02:00 committed by GitHub
commit e324d887be
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 252 additions and 92 deletions

View file

@ -12,6 +12,7 @@ using Dalamud.Game.ClientState;
using Dalamud.Game.Command;
using Dalamud.Game.Internal;
using Dalamud.Game.Network;
using Dalamud.Game.Network.Internal;
using Dalamud.Game.Text.SeStringHandling;
using Dalamud.Hooking.Internal;
using Dalamud.Interface.Internal;

View file

@ -60,7 +60,6 @@
<ItemGroup>
<PackageReference Include="CheapLoc" Version="1.1.5" />
<PackageReference Include="CoreHook" Version="1.0.4" />
<PackageReference Include="JetBrains.Annotations" Version="2021.1.0" />
<PackageReference Include="Lib.Harmony" Version="2.1.0" />
<PackageReference Include="Lumina" Version="3.3.0" />
@ -74,6 +73,7 @@
<PackageReference Include="Serilog" Version="2.10.0" />
<PackageReference Include="Serilog.Sinks.Async" Version="1.5.0" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
<PackageReference Include="Reloaded.Hooks" Version="3.2.3" />
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.333">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
@ -106,12 +106,6 @@
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<None Include="corehook64.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<Target Name="AddRuntimeDependenciesToContent" BeforeTargets="GetCopyToOutputDirectoryItems" DependsOnTargets="GenerateBuildDependencyFile;GenerateBuildRuntimeConfigurationFiles">
<ItemGroup>
<ContentWithTargetPath Include="$(ProjectDepsFilePath)" CopyToOutputDirectory="PreserveNewest" TargetPath="$(ProjectDepsFileName)" />

View file

@ -3,8 +3,9 @@ using System.Net.Sockets;
using System.Runtime.InteropServices;
using Dalamud.Hooking;
using Dalamud.Hooking.Internal;
namespace Dalamud.Game
namespace Dalamud.Game.Network.Internal
{
/// <summary>
/// This class enables TCP optimizations in the game socket for better performance.
@ -18,8 +19,9 @@ namespace Dalamud.Game
/// </summary>
public WinSockHandlers()
{
this.ws2SocketHook = Hook<SocketDelegate>.FromSymbol("ws2_32.dll", "socket", new SocketDelegate(this.OnSocket));
this.ws2SocketHook.Enable();
this.ws2SocketHook = HookManager.DirtyLinuxUser ? null
: Hook<SocketDelegate>.FromSymbol("ws2_32.dll", "socket", this.OnSocket);
this.ws2SocketHook?.Enable();
}
[UnmanagedFunctionPointer(CallingConvention.Winapi)]
@ -30,7 +32,7 @@ namespace Dalamud.Game
/// </summary>
public void Dispose()
{
this.ws2SocketHook.Dispose();
this.ws2SocketHook?.Dispose();
}
private IntPtr OnSocket(int af, int type, int protocol)
@ -47,11 +49,11 @@ namespace Dalamud.Game
// https://linux.die.net/man/7/tcp
// https://assets.extrahop.com/whitepapers/TCP-Optimization-Guide-by-ExtraHop.pdf
var value = new IntPtr(1);
NativeFunctions.SetSockOpt(socket, SocketOptionLevel.Tcp, SocketOptionName.NoDelay, ref value, 4);
_ = NativeFunctions.SetSockOpt(socket, SocketOptionLevel.Tcp, SocketOptionName.NoDelay, ref value, 4);
// Enable tcp_quickack option. This option is undocumented in MSDN but it is supported in Windows 7 and onwards.
value = new IntPtr(1);
NativeFunctions.SetSockOpt(socket, SocketOptionLevel.Tcp, SocketOptionName.AddMembership, ref value, 4);
_ = NativeFunctions.SetSockOpt(socket, SocketOptionLevel.Tcp, SocketOptionName.AddMembership, ref value, 4);
}
}

View file

@ -1,10 +1,13 @@
using System;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using CoreHook;
using Dalamud.Hooking.Internal;
using Dalamud.Memory;
using Iced.Intel;
using Reloaded.Hooks;
using Serilog;
namespace Dalamud.Hooking
{
@ -16,10 +19,7 @@ namespace Dalamud.Hooking
public sealed class Hook<T> : IDisposable, IDalamudHook where T : Delegate
{
private readonly IntPtr address;
private readonly T original;
private readonly LocalHook hookInfo;
private readonly Reloaded.Hooks.Definitions.IHook<T> hookImpl;
/// <summary>
/// Initializes a new instance of the <see cref="Hook{T}"/> class.
@ -29,23 +29,19 @@ namespace Dalamud.Hooking
/// <param name="detour">Callback function. Delegate must have a same original function prototype.</param>
public Hook(IntPtr address, T detour)
{
this.hookInfo = LocalHook.Create(address, detour, null); // Installs a hook here
this.address = address;
this.original = Marshal.GetDelegateForFunctionPointer<T>(this.hookInfo.OriginalAddress);
HookManager.TrackedHooks.Add(new HookInfo() { Delegate = detour, Hook = this, Assembly = Assembly.GetCallingAssembly() });
}
address = FollowJmp(address);
/// <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>
/// <param name="callbackParam">A callback object which can be accessed within the detour.</param>
[Obsolete("There is no need to specify new YourDelegateType or callbackParam", true)]
public Hook(IntPtr address, Delegate detour, object callbackParam = null)
: this(address, detour as T)
{
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.CreateHook<T>(detour, address.ToInt64());
HookManager.TrackedHooks.Add(new HookInfo(this, detour, Assembly.GetCallingAssembly()));
}
/// <summary>
@ -54,7 +50,6 @@ namespace Dalamud.Hooking
/// <exception cref="ObjectDisposedException">Hook is already disposed.</exception>
public IntPtr Address
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
this.CheckDisposed();
@ -68,11 +63,10 @@ namespace Dalamud.Hooking
/// <exception cref="ObjectDisposedException">Hook is already disposed.</exception>
public T Original
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
this.CheckDisposed();
return this.original;
return this.hookImpl.OriginalFunction;
}
}
@ -84,7 +78,7 @@ namespace Dalamud.Hooking
get
{
this.CheckDisposed();
return this.hookInfo.ThreadACL.IsExclusive;
return this.hookImpl.IsHookEnabled;
}
}
@ -95,7 +89,7 @@ namespace Dalamud.Hooking
/// <summary>
/// Creates a hook. Hooking address is inferred by calling to GetProcAddress() function.
/// Hook is not activated until Enable() method is called.
/// 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>
@ -103,36 +97,29 @@ namespace Dalamud.Hooking
/// <returns>The hook with the supplied parameters.</returns>
public static Hook<T> FromSymbol(string moduleName, string exportName, T detour)
{
// Get a function address from the symbol name.
var address = LocalHook.GetProcAddress(moduleName, exportName);
var moduleHandle = NativeFunctions.GetModuleHandleW(moduleName);
if (moduleHandle == IntPtr.Zero)
throw new Exception($"Could not get a handle to module {moduleName}");
return new Hook<T>(address, detour);
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);
}
/// <summary>
/// Creates a hook. Hooking address is inferred by calling to GetProcAddress() function.
/// 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>
/// <param name="callbackParam">A callback object which can be accessed within the detour.</param>
/// <returns>The hook with the supplied parameters.</returns>
[Obsolete("There is no need to specify new YourDelegateType or callbackParam", true)]
public static Hook<T> FromSymbol(string moduleName, string exportName, Delegate detour, object callbackParam = null) => FromSymbol(moduleName, exportName, detour as T);
/// <summary>
/// Remove a hook from the current process.
/// </summary>
public void Dispose()
{
if (this.IsDisposed)
{
return;
}
this.IsDisposed = true;
this.hookInfo.Dispose();
if (this.hookImpl.IsHookEnabled)
this.hookImpl.Disable();
}
/// <summary>
@ -142,7 +129,11 @@ namespace Dalamud.Hooking
{
this.CheckDisposed();
this.hookInfo.ThreadACL.SetExclusiveACL(null);
if (!this.hookImpl.IsHookActivated)
this.hookImpl.Activate();
if (!this.hookImpl.IsHookEnabled)
this.hookImpl.Enable();
}
/// <summary>
@ -152,10 +143,86 @@ namespace Dalamud.Hooking
{
this.CheckDisposed();
this.hookInfo.ThreadACL.SetInclusiveACL(null);
if (!this.hookImpl.IsHookActivated)
return;
if (this.hookImpl.IsHookEnabled)
this.hookImpl.Disable();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
/// <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>
private void CheckDisposed()
{
if (this.IsDisposed)

View file

@ -1,11 +1,11 @@
using System;
namespace Dalamud.Hooking.Internal
namespace Dalamud.Hooking
{
/// <summary>
/// Interface describing a generic hook.
/// </summary>
internal interface IDalamudHook
public interface IDalamudHook
{
/// <summary>
/// Gets the address to hook.

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

@ -1,6 +1,9 @@
using System;
using System.Collections.Generic;
using Dalamud.Memory;
using Microsoft.Win32;
namespace Dalamud.Hooking.Internal
{
/// <summary>
@ -8,16 +11,59 @@ namespace Dalamud.Hooking.Internal
/// </summary>
internal class HookManager : IDisposable
{
// private readonly Dalamud dalamud;
private static readonly ModuleLog Log = new("HM");
private static bool checkLinuxOnce = true;
private static bool isRunningLinux = false;
/// <summary>
/// Initializes a new instance of the <see cref="HookManager"/> class.
/// </summary>
/// <param name="dalamud">Dalamud instance.</param>
public HookManager(Dalamud dalamud)
internal HookManager(Dalamud dalamud)
{
_ = dalamud;
// this.dalamud = dalamud;
}
/// <summary>
/// Gets a value indicating whether the client is running under Linux Wine.
/// </summary>
/// <returns>A value indicating whether the game is running under Wine.</returns>
internal static bool DirtyLinuxUser
{
get
{
if (checkLinuxOnce)
{
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;
}
}
/// <summary>
@ -25,9 +71,43 @@ namespace Dalamud.Hooking.Internal
/// </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();
/// <inheritdoc/>
public void Dispose()
{
RevertHooks();
TrackedHooks.Clear();
Originals.Clear();
}
private static unsafe void RevertHooks()
{
foreach (var (address, originalBytes) in Originals)
{
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;
}
if (i > 0)
{
Log.Verbose($"Reverting hook at 0x{address.ToInt64():X}");
fixed (byte* original = originalBytes)
{
MemoryHelper.ChangePermission(address, i, MemoryProtection.ExecuteReadWrite, out var oldPermissions);
MemoryHelper.WriteRaw(address, originalBytes);
MemoryHelper.ChangePermission(address, i, oldPermissions);
}
}
}
}
}
}

View file

@ -10,6 +10,7 @@ using Dalamud.Game;
using Dalamud.Game.ClientState;
using Dalamud.Game.Internal.DXGI;
using Dalamud.Hooking;
using Dalamud.Hooking.Internal;
using ImGuiNET;
using ImGuiScene;
using Serilog;
@ -101,17 +102,17 @@ namespace Dalamud.Interface.Internal
Log.Error(e, "RTSS Free failed");
}
var user32 = NativeFunctions.GetModuleHandleW("user32.dll");
var setCursorAddr = NativeFunctions.GetProcAddress(user32, "SetCursor");
Log.Verbose("===== S W A P C H A I N =====");
Log.Verbose($"SetCursor address 0x{setCursorAddr.ToInt64():X}");
Log.Verbose($"Present address 0x{this.address.Present.ToInt64():X}");
Log.Verbose($"ResizeBuffers address 0x{this.address.ResizeBuffers.ToInt64():X}");
this.setCursorHook = new Hook<SetCursorDelegate>(setCursorAddr, this.SetCursorDetour);
this.setCursorHook = HookManager.DirtyLinuxUser ? null
: Hook<SetCursorDelegate>.FromSymbol("user32.dll", "SetCursor", this.SetCursorDetour);
this.presentHook = new Hook<PresentDelegate>(this.address.Present, this.PresentDetour);
this.resizeBuffersHook = new Hook<ResizeBuffersDelegate>(this.address.ResizeBuffers, this.ResizeBuffersDetour);
var setCursorAddress = this.setCursorHook?.Address ?? IntPtr.Zero;
Log.Verbose("===== S W A P C H A I N =====");
Log.Verbose($"SetCursor address 0x{setCursorAddress.ToInt64():X}");
Log.Verbose($"Present address 0x{this.presentHook.Address.ToInt64():X}");
Log.Verbose($"ResizeBuffers address 0x{this.resizeBuffersHook.Address.ToInt64():X}");
}
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
@ -189,7 +190,7 @@ namespace Dalamud.Interface.Internal
/// </summary>
public void Enable()
{
this.setCursorHook.Enable();
this.setCursorHook?.Enable();
this.presentHook.Enable();
this.resizeBuffersHook.Enable();
@ -225,7 +226,7 @@ namespace Dalamud.Interface.Internal
Thread.Sleep(500);
this.scene?.Dispose();
this.setCursorHook.Dispose();
this.setCursorHook?.Dispose();
this.presentHook.Dispose();
this.resizeBuffersHook.Dispose();
}
@ -501,7 +502,7 @@ namespace Dalamud.Interface.Internal
private void Disable()
{
this.setCursorHook.Disable();
this.setCursorHook?.Disable();
this.presentHook.Disable();
this.resizeBuffersHook.Disable();
}