如何确定堆栈上的返回地址? [英] How can I determine the return address on stack?

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

问题描述

我知道,如果我的一些功能富()这是从地方叫巴()函数内,那么这个返回地址被压在堆栈中。

I know that if I am inside some function foo() which is called somewhere from bar() function, then this return address is pushed on stack.

    #include <stdio.h>

    void foo()
    {
            unsigned int x;
            printf("inside foo %x\n", &x);
    }
    int main()
    {
            foo();
            printf("in main\n");
            return 0;
    }

在上面code,我会先推局部变量堆栈时富功能激活获取地址。我怎么能访问在堆栈这个变量在什么地方推的返回地址(主叫做foo)?被该位置的固定,并且可以相对于第一个局部变量来访问?我如何修改呢?

In above code, I will get address of first pushed local variable on stack when foo function is active. How can I access the return address (main called foo) that is pushed somewhere before this variable on stack? Is that location fixed and can be accessed relative to first local variable? How can I modify it?

编辑:我的环境是与gcc编译x86处理器的Ubuntu 9.04。

My environment is Ubuntu 9.04 on x86 processor with gcc compiler.

推荐答案

有是内置了这样的GCC:的void * __builtin_return_address(unsigned int类型级)

There is a gcc builtin for this: void * __builtin_return_address (unsigned int level)

请参阅http://gcc.gnu.org/onlinedocs/gcc/Return-Address.html

在某些架构中,你可以找到它相对于第一个参数堆栈。 IA32上,例如,所述参数被压(以相反的顺序),然​​后一个呼叫时,将推动的返回地址。请记住,堆几乎总是(和IA32)生长的向下的。虽然技术上你需要的 ABI 调用约定的(有时也称为的联动约定的),为您的语言和硬件平台,在实践中通常可以猜想,如果你知道过程调用机器操作是如何工作的。

On some architectures, you can find it on the stack relative to the first parameter. On ia32, for example, the parameters are pushed (in opposite order) and then a call is made that will push the return address. Remember that the stack almost always (and on ia32) grows downward. Although technically you need the ABI or calling conventions (sometimes called linkage conventions) for your language and hardware platform, in practice you can usually guess if you know how the procedure call machine op works.

的第一个参数的函数,该堆栈上的返回地址的位置之间的关系是更可能比本地和返回地址的关系的可靠固定值。但是,你当然可以打印出本地的地址,第一个参数,你会经常发现在PC间的权利。

The relationship between the first parameter to a function and the position of the return address on the stack is far more likely to be a reliably fixed value than the relationship between a local and the return address. However, you can certainly print out the address of a local, and of the first parameter, and you will often find the PC right in between.

$ expand < ra.c
#include <stdio.h>

int main(int ac, char **av) {
  printf("%p\n", __builtin_return_address(0));
  return 0;
}
$ cc -Wall ra.c; ./a.out
0xb7e09775
$

这篇关于如何确定堆栈上的返回地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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