Reloaded.Hooks icon indicating copy to clipboard operation
Reloaded.Hooks copied to clipboard

Calling OriginalFunction on already hooked function crashes the process

Open nefarius opened this issue 2 years ago • 0 comments

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.

nefarius avatar Apr 24 '23 03:04 nefarius