Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 818
user3476738 Avatar asked Jan 31 '26 03:01

user3476738


1 Answers

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

like image 101
Carl Norum Avatar answered Feb 01 '26 15:02

Carl Norum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!