Reloaded-Project / Reloaded.Hooks

Advanced native function hooks for x86, x64. Welcome to the next level!
GNU Lesser General Public License v3.0
213 stars 33 forks source link

Calling OriginalFunction on already hooked function crashes the process #22

Open nefarius opened 1 year ago

nefarius commented 1 year ago

Hello!

I have the following snippet that works perfectly when the process it runs is is untouched by other hooks:

using System.Runtime.InteropServices;

using Windows.Win32.Devices.DeviceAndDriverInstallation;
using Windows.Win32.Foundation;

using Reloaded.Hooks;
using Reloaded.Hooks.Definitions;
using Reloaded.Hooks.Definitions.X64;

using winmdroot = Windows.Win32;

internal sealed class UnhookingHelper
{
    [Function(CallingConventions.Microsoft)]
    [UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Unicode)]
    public unsafe delegate HDEVINFO SetupDiGetClassDevsW([Optional] Guid* ClassGuid, PCWSTR Enumerator, HWND hwndParent,
        uint Flags);

    private readonly IHook<SetupDiGetClassDevsW> _setupDiGetClassDevs;

    public unsafe UnhookingHelper()
    {
        winmdroot.FreeLibrarySafeHandle setupapiHandle = winmdroot.PInvoke.LoadLibrary("SetupAPI");
        FARPROC setupDiGetClassDevsWPtr = winmdroot.PInvoke.GetProcAddress(setupapiHandle, "SetupDiGetClassDevsW");

        _setupDiGetClassDevs = ReloadedHooks.Instance
            .CreateHook<SetupDiGetClassDevsW>(SetupDiGetClassDevsWImpl, setupDiGetClassDevsWPtr).Activate();
    }

    private unsafe HDEVINFO SetupDiGetClassDevsWImpl([Optional] Guid* ClassGuid, PCWSTR Enumerator, HWND hwndParent,
        uint Flags)
    {
        var ret = _setupDiGetClassDevs.OriginalFunction(ClassGuid, Enumerator, hwndParent, Flags);

        return ret;
    }
}

Here is where it gets weird; I've got a closed source SDK library which also hooks the mentioned function and I'm trying to "unhook"/bypass the nonsense it does with the above code. Unfortunately as soon as this other hook is present, the OriginalFunction crashes.

If I try to establish my hook first, then let the SDK hook, no more crash but I assume then I will never get my "real" WinApi function pointer? Need to do more testing to verify.

Any insights welcome, and very nice project 😁

Cheers

EDIT: Maybe my approach is the wrong one to begin with, the end goal is really to unhook/bypass the hooks done by the SDK lib.