如何在C中找到函数的返回地址? [英] How to find the return address of a function in C?

查看:224
本文介绍了如何在C中找到函数的返回地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过阅读CodeProject上的一篇文章,在C和GCC中使用少量AT& T风格的内联汇编 here 。我希望这样做的主要原因是找到EIP寄存器的旧值,以便能够在我的代码中拥有可靠的指令地址。我写了一个简单的示例程序来证明我对此概念的理解:
$ b $ pre $ #include< stdio.h>
#include< stdlib.h>

int mainReturnAddress = 0;

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

printf(地址:%d \\\
,mainReturnAddress);
返回0;

$ / code>

这个例子的目的是从顶部弹出4个字节堆栈表示从EIP寄存器保存的32位返回地址,然后将其推回堆栈。之后,我将它存储在全局 mainReturnAddress 变量中。最后,我打印存储在mainReturnAddress中的值。



我从这段代码收到的输出 4200560 p>

这段代码是否达到上述目的,这是32位Windows平台上的交叉处理器吗?

解决方案

在GCC中,您应该使用 __ builtin_return_address ,而不是尝试使用内联汇编。


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?

解决方案

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

这篇关于如何在C中找到函数的返回地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆