"Where did the function call originate from?" version 2.0
In one of the earlier posts here I showed how the _ReturnAddress intrinsic could be used to see which module a call originated from. In this minimalistic episode, I'll show how to resolve the return address to a symbol (granted the symbol information, of course).
This following function will attempt to resolve the name of symbol at the referenced address. It can easily be merged with the previsouly mentioned _ReturnAddress function, in a way such as getSymbolName(GetCurrentProcess(), _ReturnAddress());
string getSymbolName(HANDLE hProcess, DWORD64 dwAddress)
{
static BOOL bSymbolsLoaded = FALSE;
if(!bSymbolsLoaded)
{
// Replace the second parameter of the following call with the path of the
// folder in which symbols for the process can be found. NULL will
// cause the current working directory to be searched.
if(!SymInitialize(GetCurrentProcess(), NULL, TRUE))
{
throw exception("Symbols could not be loaded");
}
bSymbolsLoaded = TRUE;
}
ULONG64 buf[(sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR) +
sizeof(ULONG64) - 1) / sizeof(ULONG64)];
SYMBOL_INFO* pSI = reinterpret_cast<SYMBOL_INFO*>(buf);
pSI->SizeOfStruct = sizeof(SYMBOL_INFO);
pSI->MaxNameLen = MAX_SYM_NAME;
pSI->Flags = SYMFLAG_FUNCTION;
DWORD64 dwDisplacement;
if(!SymFromAddr(hProcess, dwAddress, &dwDisplacement, pSI))
{
throw exception("Failed to retrieve the symbol information");
}
return static_cast<char*>(pSI->Name);
}
In case of the previous example, the first "Where did the function call originate from?" post, the expected output would include module name only. The preceeding snippet will allow you to show the symbol name aswell, that is the name of the calling function (which would be main in case of the expected output of the previous post).
A keen observer browsing throug the DbgHelp API will also notice that the need to iterate loaded modules is no longer needed in that old example. While this is true if you've got the symbols, and actually use the DbgHelp API, my use of the approach has had the luxury of none of the two. I might elaborate on that alongside a description of my API Hooking library :)


0 kommentarer:
Post a Comment