tags:

views:

46

answers:

4

Currently, I have a C++ exe project, which dynamic load N DLLs.

Those DLLs will perform calling to the functions which is re-inside exe project.

Now, within my exe project, I wish to know the callers are coming from which DLLs.

Is it possible to do so using any available Windows API?

+4  A: 

It depends on what your actual goal is. You cannot do it if you're expecting the DLLs to be possibly malicious (that is, if you're expecting them to try to trick you). But if it's just for debugging or logging or something relaitvely harmless like that, you can look at the stack and get the address that the ret instruction will use to return to the caller, enumerate through the loaded DLLs and test which of them that address is inside of.

To get the "return address", you can use the _ReturnAddress intrinsic in Visual C++, and then you can use the GetModuleHandleEx function, passing in GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS to get a handle to the DLL that the address is inside of.

But I must repeat: you cannot base security decisions off the results of this test. It is very easy for malicious code to fake and "trick" your program into thinking it's a "trusted" or "safe" DLL. As I said, if it's just for debugging or logging or something, then go right ahead.

Also, this will obviously only tell you the DLL the immediate caller is inside of. You can't do it if you're 5 levels deep or something....

Dean Harding
A: 

If you have given the same callback to multiple DLL's, then it is up to them to provide you with information about who's who. Most API callback have a parameter you can pass to the callback. If this is so for your callbacks, you can use this to identify the DLLs.

It probably isn't possible considering that the call stack will come back down to your exe anyway.

EDIT: By the look of your post, is this a hypothetical situation?

Alexander Rafferty
A: 

Is this helpful? Check the parameter 'GetModuleBaseRoutine'

Chubsdad
A: 

If you're architecting the exe, and you're not assuming the DLL's are hostile (see Dean's answer), you might be able to achieve the effect by providing each DLL with a different set of pointers for the callback functions, which each in-turn forward to the actual callback functions. You could then associate the calls with the calling DLL, based on which pass-through callback was actually called.

Of course, this assumes you're providing the callback addresses to the DLL's, but presumably this would be the normal design for an application where a DLL called back into the calling exe. It won't work if the DLL is mucking around in your process memory for internal functions, of course, but then you're probably into the hostile situation.

Nick