How to find the return address of a function in C?

▼魔方 西西 提交于 2019-12-23 22:49:23

问题


I'm trying to use a small amount of AT&T style inline assembly in C and GCC by reading an article on CodeProject here. The main reason I wish to do this is to find the old value of the EIP register to be able to have a reliable address of instructions in my code. I have written a simple example program to demonstrate my understanding of this concept thus far :

#include <stdio.h>
#include <stdlib.h>

int mainReturnAddress = 0;

int main()
{
    asm volatile (
         "popl %%eax;"
         "pushl %%eax;"
         "movl %%eax, %0;"
         : "=r" ( mainReturnAddress )
       );

    printf( "Address : %d\n",  mainReturnAddress );
    return 0;
}

The purpose of this particular example is to pop 4 bytes from the top of the stack representing the 32 bit return address saved from the EIP register, and then to push it back on the stack. Afterwards, I store it in the global mainReturnAddress variable. Finally, I print the value stored in mainReturnAddress.

The output from I recieve from this code 4200560.

Does this code achieve the purpose aforementioned, and is this is cross processor on the Windows platform 32-bit?


回答1:


In GCC, you should use __builtin_return_address rather then trying to use inline assembly.



来源:https://stackoverflow.com/questions/23818282/how-to-find-the-return-address-of-a-function-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!