为什么我的编译器保留的空间比函数堆栈帧所需的空间多? [英] Why is my compiler reserving more space than required for a function stack frame?

查看:16
本文介绍了为什么我的编译器保留的空间比函数堆栈帧所需的空间多?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数:

void func(int a)
{
    int x = a+2;
}

在汇编代码中,在函数prolog中:

In the assembly code, in function prolog:

push %ebp
mov %esp, %ebp
sub $0x10, %esp

代码只需要为 x 预留空间,即 4 个字节.但它保留了 16 个字节.这是为什么 ?我一直认为它会预留比所需更多的空间.

The code only needs to reserve space for x i.e. 4 bytes. But it is reserving 16 bytes. Why is that ? I have always seen it to reserve more space than required.

我的猜测:它倾向于以 16 个字节存储.即如果我需要说 20 个字节,无论如何它都会保留 32 个字节.

My guess: it tends to store in 16 bytes. i.e. if I needed say 20 bytes, it will reserve 32 bytes, no matter what.

推荐答案

这在很大程度上取决于你的架构和编译器标志,所以不可能在这里指着一个东西说这一定是它".不过,我可以给你一些建议,你可能会觉得有帮助.

This highly depends on your architecture and compiler flags, so it is impossible to point to a single thing and say "this must be it" here. However, I can give you some pointers you may find helpful.

首先,考虑堆栈边界.您可能听说过 GCC 的 -mpreferred-stack-boundary=X 标志.如果不是,它基本上会告诉您的编译器希望您在堆栈上的值每个为 2^X 字节.然后,您的编译器将尝试优化您的程序,以使这些值尽可能适合堆栈.另一方面,像 __packed__ 这样的 GCC 修饰符会使编译器尽量将数据放入栈中.

First, consider the stack boundary. You may have heard of the -mpreferred-stack-boundary=X flag to GCC. If not, it basically tells your compiler to prefer your values on the stack to be 2^X bytes each. Your compiler will then try to optimize your program so that these values fit on the stack as best as possible. On the other hand, GCC modifier such as __packed__ will make the compiler try to fit the data in the stack as tightly as possible.

还有堆栈保护器.基本上,GCC 会在堆栈上放置虚拟值,以确保缓冲区溢出除了对您的程序造成段错误之外不会造成任何伤害(这并不有趣,但比攻击者控制指令指针更好).您可以轻松地尝试一下:使用任何最新版本的 GCC 并让用户溢出缓冲区.您会注意到程序退出时会显示一条消息,即检测到堆栈粉碎,已终止".尝试用-fno-stack-protector编译你的程序,堆栈上分配的本地内存可能会更小.

There's also the stack protector. Basically, GCC places dummy values on the stack that make sure buffer overflows can't any harm other than segfaulting your program (which isn't fun, but better than an attacker tacking control of the instruction pointer). You can easily try this out: take any recent version of GCC and let the user overflow a buffer. You'll note that the program exits with a message along the lines of 'stack smashing detected, terminated'. Try compiling your program with -fno-stack-protector, and the allocated local memory on the stack will probably be smaller.

这篇关于为什么我的编译器保留的空间比函数堆栈帧所需的空间多?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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