How to intercept dll method calls?
- What are the techniques available for it?
- Can it be done only in C/C++?
- How to intercept method calls from all running processes to a given dll?
- How to intercept method calls from a given processes to a given dll?
How to intercept dll method calls?
On Linux, this can be done with the LD_PRELOAD environment variable. Set this variable to point at a shared library that contains a symbol you'd like to override, then launch your app.
Provided that you know all the DLL functions in advance, one technique is to write your own wrapper DLL that will forward all function calls to the real DLL. This DLL doesn't have to be written in C/C++. All you need to do is to match the function calling convention of the original DLL.
There are two standard ways I can think of for doing this
DLL import table hook.
For this you need to parse the PE Header of the DLL, find the import table and write the address of your own function instead of what is already written there. You can save the address of the original function to be able to call it later. The references in the external links of this wikipedia article should give you all the information you need to be able to do this.
Direct modification of the code. Find the actual code of the function you want to hook and modify the first opcodes of it to jump to your own code. you need to save the opcode which were there so they will eventually get executed. This is simpler than it sounds mostly because it was already implement by no less than Microsoft themselves in the form of the Detours library.
This is a really neat thing to do. with just a couple of lines of code you can for instance replace all calls to GetSystemMetrics() from say outlook.exe and watch the wonders that occur.
The advantages of one method are the disadvantages of the other. The first method allows you to add a surgical hook exactly to DLL you want where all other DLLs go by unhooked. The second method allows you the most global kind of hook to intercept all calls do the function.
See Microsoft Detours for a library with a C/C++ API. It's a bit non-trivial to inject it in all other programs without triggering virusscanners/malware detectors. But your own process is fair game.