Pepsi_1
Pepsi_1

Reputation: 121

How to log the stack return address of a function in c++

I was wondering how to log the stack return address of a function?

If you log parameters like this:

int (WINAPI *pSend)(SOCKET s, const char* buf, int len, int flags) = send;
int WINAPI MySend(SOCKET s, const char* buf, int len, int flags);

// Below DllMain

int WINAPI MySend(SOCKET s, const char* buf, int len, int flags)
{
    fopen_s(&pSendLogFile, "C:\\SendLog.txt", "a+");
    fprintf(pSendLogFile, "%s\n", buf);
    fclose(pSendLogFile);
    return pSend(s, buf, len, flags);
}

Then how would I log the return address of Send?

Upvotes: 1

Views: 1212

Answers (2)

Nik Bougalis
Nik Bougalis

Reputation: 10613

I'm not sure what you are trying to achieve, so it's difficult to know if this is the correct answer. I'll assume you know what you're doing, but I would urge you to rethink your design.

With that said, check out the intrinsics _ReturnAddress() at http://msdn.microsoft.com/en-us/library/64ez38eh which will give you the address of the instruction that will be executed immediately after the function you call _ReturnAddress() from returns, and the _AddressOfReturnAddress() at http://msdn.microsoft.com/en-us/library/s975zw7 which will give you the address where the return address is stored.

Please be sure to read the documentation carefully and to understand what the address you are getting back represents. And be VERY CAREFUL if you manipulate the return address, as things can (and will) go boom if you do the wrong thing.

Upvotes: 3

Kirill Kobelev
Kirill Kobelev

Reputation: 10557

You cannot do this in a platform/compiler independent way. In Windows you can use StackWalk/StackWalk64 functions. I used them a couple of years ago. Provided you have debug info for the modules on the stack, you can get names of the functions.

For example look at this: http://msdn.microsoft.com/en-us/library/windows/desktop/ms680650(v=vs.85).aspx

Upvotes: 1

Related Questions