Batata
Batata

Reputation: 133

Get function name by address

With this code I can get the address of a function by its name:

DWORD dwAddr = (DWORD)GetProcAddress(GetModuleHandleA("user32.dll"), "MessageBoxA");

But it's possible to do the reverse process? From the function address find the function name?

Let's assume that the MessageBoxA address is 0x1234abcd. What I want is this:

char *func_name = this_is_what_i_want(0x1234abcd);
printf("%s", func_name); // this will print "MessageBoxA"

OS: Windows

Upvotes: 3

Views: 4342

Answers (1)

2501
2501

Reputation: 25753

Use SymFromAddr which takes SYMBOL_INFO structure. The structure will contain the name in the Name member.

Allocation memory for SYMBOL_INFO is tricky, make sure to read the documentation.

How to allocate SYMBOL_INFO:

const size_t array_size = 256 ;
const size_t size = sizeof( SYMBOL_INFO ) + ( array_size-1 )*sizeof( TCHAR ) ;
SYMBOL_INFO* symbol = calloc( 1 , size ) ;
if( !symbol )
{
    //deal with it
}
symbol->SizeOfStruct = sizeof( *symbol ) ;  //both values must
symbol->MaxNameLen = array_size ;           //be set by user

Note that we subtracted 1 here:( array_size-1 ) because the struct already give us one byte, and we want our string array to be of size 256 not 257.

The structure now has enough space for a string of length 255.

Upvotes: 3

Related Questions