I'm trying to get address of main() function in this way:
int main(int argc, char *argv[])
{
void *pMainAddress=(void *)&main;
printf("Address of main() 0x%08X \n", pMainAddress);
When I build project using Release configuration, the result is:
Address of main() : 0x00401000
This is under debugger:
00401000 /$ 68 00104000 PUSH GetMain.00401000 ; Entry address
00401005 |. 68 50A14000 PUSH GetMain.0040A150 ; ASCII "0x%p \n"
0040100A |. E8 8B000000 CALL GetMain.0040109A
But when compiling with /Zi option, or use Debug build, address is redirected:
Address of main() : 0x0041178A
.
This address is obtained by performing an unconditional jump, the actual address is 0x00412530
This is under debugger:
00412530 /> \55 PUSH EBP
...
00412539 |. C745 FC 8A174100 MOV [LOCAL.1],GetMain.0041178A ; Entry address
00412540 |. 8B45 FC MOV EAX,[LOCAL.1]
00412543 |. 50 PUSH EAX
00412544 |. 68 5CEC4200 PUSH GetMain.0042EC5C ; ASCII "0x%p \n"
Why this hapenes ?
How to get the real address of main() function (0x00412530
in above example) if code is compiled in Debug build ?
Edit:
Why this happens ? is already answered here: strange level of indirection of a function call
Function below solve my second question, Here I wrote answer .
void *GetMainAddress(void)
{
void *pMainAddress=(void*)&main;/* address in main() function */
unsigned long calculateJump=0;
unsigned char *ptrJump;
printf("Address of main() : 0x%08X\n", pMainAddress);
ptrJump=(unsigned char*)pMainAddress;/* get pointer to main address */
if(*(unsigned char*)ptrJump == 0xE9)/* address point to jmp opcode ? */
{
calculateJump = ( *(unsigned long *)(ptrJump+1) ); /* get address after 0xe9 */
pMainAddress = ptrJump + calculateJump + 5; /* calculate real address */
printf("Unconditional jump is performed\n");
printf("Actual sddress of main() is: 0x%08X \n", pMainAddress);
}
else
{
printf("Unconditional jump is not performed\n");
}
return pMainAddress;
}