NFRCR
NFRCR

Reputation: 5580

Visual C++ - overriding a function imported from a DLL?

I'm trying to override a specific function in kernel32.dll. Is it somehow possible to redefine that function in a static library and force the executable to use the one in the static library? I guess the different linkage could become a problem.

It would be possible to override it with my own custom DLL. However the problem is that the DLL itself needs to link to kernel32.dll, so it ignores my definition of that function.

EDIT: I got it working with my own DLL. When building it, link time code generation needs to be disabled. What about linking the overridden function statically though?

Upvotes: 3

Views: 7556

Answers (3)

MSalters
MSalters

Reputation: 180305

Yes, this is no big problem. Functions are defined as __dllimport, but that does not specify which DLL they're imported from. The linker simply picks the first import library that provides them. Therefore,. just pass your library first. In MSVC, you'll need to disable "include standard libraries", as those precede custom libraries.

Upvotes: 3

SigTerm
SigTerm

Reputation: 26439

If your application already exists and cannot be modified, then

you can write proxy dll. I.e. make your own dll called kernel32.dll, place it into application directory, and make your proxy dll provide all function application needs. Of course, your custom dll should redirect all calls it doesn't override to original kernel32.dll - by loading original dll using LoadLibrary.

Because LoadLibrary is provided by kernel32 and you're proxying kernel32, most likely you'll have to name your proxy dll kernel33.dll and patch original exe and make it load kernel33 instead of kernel32.

The whole thing is is pain, and to do it successfully you should be at least familiar with cli(command line interface - cmd.exe on windows) and dumpbin utility. This outdated tutorial can get you started.

Alternatively you could attempt to use dll injection or similar techniques. There's also "Detours" library which I haven't used (not sure why would I want to bother with it if I can make a proxy dll).

if you have source code access to your application and only specific part of program needs different routine...

Then simply make custom routine with whatever name you want (say, myLoadLibrary). Then make a header that uses #define to redefine your routine. I.e. something like #define LoadLibrary myLoadLibrary. Include that header in every file where you need override, and make sure it is included after <windows.h>.

Upvotes: 1

Ilian
Ilian

Reputation: 5355

If I understand you correctly, you want custom behavior for a Windows API function in kernel32.dll. If so, you need to hook into the Windows API. One way to do this is to use Detours. Haven't tried it myself but here's a link to a CodeProject article - http://www.codeproject.com/Articles/30140/API-Hooking-with-MS-Detours.

Upvotes: 4

Related Questions