本文介绍了内存对齐现在和20年前的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在著名的论文德艺双馨堆栈的乐趣和利润,它的作者需要一个C函数

In the famous paper "Smashing the Stack for Fun and Profit", its author takes a C function

void function(int a, int b, int c) {
  char buffer1[5];
  char buffer2[10];
}

和生成相应的装配code输出

and generates the corresponding assembly code output

pushl %ebp
movl %esp,%ebp
subl $20,%esp

笔者解释说,因为电脑中字大小的倍数内存寻址,编译器保留堆栈(8字节缓冲器1,对于缓冲器2 12字节)的20个字节。

The author explains that since computers address memory in multiples of word size, the compiler reserved 20 bytes on the stack (8 bytes for buffer1, 12 bytes for buffer2).

我试图重新这个例子中,得到了以下

I tried to recreate this example and got the following

pushl   %ebp
movl    %esp, %ebp
subl    $16, %esp

一个不同的结果!我试着大小缓冲器1和缓冲器的各种组合,它似乎是现代GCC不垫缓冲区大小为字的倍数了。相反,它在遵守 -m preferred堆栈边界选项。

A different result! I tried various combinations of sizes for buffer1 and buffer2, and it seems that modern gcc does not pad buffer sizes to multiples of word size anymore. Instead it abides the -mpreferred-stack-boundary option.

作为说明 - 使用的纸张的算术规则,缓冲器1 [5] 1和缓冲器[13]编号得到保留在堆栈上8 + 16 = 24个字节。但在现实中我得到了32个字节。

As an illustration -- using the paper's arithmetic rules, for buffer1[5] and buffer2[13] I'd get 8+16 = 24 bytes reserved on the stack. But in reality I got 32 bytes.

该文件是很老,因为很多东西发生了。我想知道,究竟是什么动机行为的这种变化?它是对64位机器的举动?还是其他什么东西?

The paper is quite old and a lot of stuff happened since. I'd like to know, what exactly motivated this change of behavior? Is it the move towards 64bit machines? Or something else?

修改

在code使用gcc版本4.8.2(Ubuntu的4.8.2-19ubuntu1)这样的x86_64的机器上编译:

The code is compiled on a x86_64 machine using gcc version 4.8.2 (Ubuntu 4.8.2-19ubuntu1) like that:

$ GCC -S -o example1.s example1.c -fno-堆栈保护-m32

推荐答案

有所改变的是它说(的重点煤矿的):

What has changed is SSE, which requires 16 byte alignment, this is covered in this older gcc document for -mpreferred-stack-boundary=num which says (emphasis mine):

在Pentium和PentiumPro,double和long double值应该对齐到8字节边界(见-malign双)或遭受显著运行时的性能损失。 在奔腾III,流式SIMD扩展(SSE)数据类型__m128遭受类似的惩罚,如果它不是16字节对齐。

这也是由纸的涵盖这一点,打破了等现代改变的粉碎堆栈的乐趣和利润

This is also backed up by the paper Smashing The Modern Stack For Fun And Profit which covers this an other modern changes that break Smashing the Stack for Fun and Profit.

这篇关于内存对齐现在和20年前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 18:51