Unmanaged hooking, how to call original function / change return status?

Sep 9, 2013 at 8:15 AM
Migrated here from SO

So I have a hook function at winspool.drv!WritePrinter, which is successfully hooked with unmanaged C++ remotely injected to spoolsv.exe. Currently, the hook seems to either replace original function, or corrupt the stack in an undetectable way: after hooking, WritePrinter calls result in no printer activity outside the hook.

I've figured out there's at least one way to call original function, so-called LhGetOldProc. However, using it leads to crashes (see code).
So, how do I properly call original function in Easyhook unmanaged version?

Hook setting code:
HMODULE                 hSpoolsv = LoadLibraryA("winspool.drv");
NTSTATUS                NtStatus;
UNICODE_STRING*         NameBuffer = NULL;
HANDLE                  hRemoteThread;
FORCE(LhInstallHook(GetProcAddress(hSpoolsv, "WritePrinter"), WritePrinterHookA, 0x0, hHook));
ULONG ACLEntries[1] = { (ULONG) - 1 };
FORCE(LhSetExclusiveACL(ACLEntries, 1, hHook));

hhW = hHook;
Hook callback with LhGetOldProc:

LhGetOldProc(hhW, &uc);
typedef BOOL (__stdcall* wp)(_In_   HANDLE, _In_   LPVOID, _In_   DWORD cbBuf, _Out_  LPDWORD);
wp my_wp = reinterpret_cast<wp>(reinterpret_cast<long>(uc)); // http://stackoverflow.com/questions/1096341/function-pointers-casting-in-c
BOOL res = my_wp(hPrinter, pBuf, cbBuf, pcWritten); // crash
Unhandled exception at 0xF... in spoolsv.exe: Access violation executing location 0xF.. (probably DEP fires in?)

What's the error here, how to call original hooked function from unmanaged hook, and how to return custom values from hook function?
Sep 9, 2013 at 8:29 AM
upd: casting to void* seemingly solved the problem.
Sep 11, 2013 at 12:41 AM
You just call the original method the same as if it wasn't hooked. Easyhook will bypass the hook automatically because you are already within the hook.

Does this give u what you need?
Sep 28, 2013 at 8:29 PM
Edited Sep 28, 2013 at 8:29 PM
No, it didn't worked.

I have to stay with LhGetOldProc, because "calling original procedure" eventually returns me right into my hook, creating stack overflow at its worst face, and this seems very wrong because I have to modify 3rdparty source and redistribute it with a patch for the project.
Mar 7, 2014 at 2:26 AM
Same problem here!

Any code after call the original function will be left unexecuted. The funcion I hooked is in the exe file itself, not an entry point from other dll files, so GetProcDelegate has nothing to do with it.

Any help will be appreciated.
Mar 9, 2014 at 6:10 AM
Can you please show how you have tried it?

You should be able to just call the original function as you would normally from outside of the hook e.g. using the exported function.