组装中的 EBP、ESP 和堆栈框架 [英] EBP, ESP and stack frame in assembly

查看:64
本文介绍了组装中的 EBP、ESP 和堆栈框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对以下代码中的 EBP、ESP 和堆栈帧有一些疑问.

I have a few questions about EBP, ESP and stack frame in following code.

  1. 为什么我们要从 esp 中减去 28?我们在 main 中有两个局部变量 x 和 y.那么为什么我们不减去 8?

  1. Why did we subtract 28 from esp? We have two local variables x and y in main. So why didn't we subtract 8?

难道我们不把值从右(或上)到左(或下)堆叠吗?那么为什么我们在 [eax+8] 上加 1 而不是 [eax+4]?

And don't we put values to stack from right (or top) to left (or bottom)? So why did we add 1 to [eax+8] instead of [eax+4]?


func(int a, int b, int c)
{
  return a+b+c;
}
main()
{
 int x, y=3;
 x=func(y,2,1);
}

推荐答案

  1. 堆栈指针减去 28,因为两个局部变量需要 8 个字节,func 的参数需要 12 个字节.额外的 8 个字节可能是由于您的编译器试图将 main 的堆栈对齐到 16 字节的边界(堆栈上已经有 4 个字节用于 main 的返回地址,当 EBP 被推送以在 main 的第一条指令中建立堆栈帧时,还有另外 4 个字节).参见 -mpreferred-stack-boundary 如果您使用的是 GCC.

  1. The stack pointer is subtracted by 28 because you need 8 bytes for your two local variables and 12 bytes for the parameters to func. The extra 8 bytes are likely due to your compiler's attempt to align main's stack to a 16-byte boundary (there's already 4 bytes on the stack for main's return address and another 4 bytes when EBP was pushed to establish the stack frame in main's first instruction). See -mpreferred-stack-boundary if you're using GCC.

参数是从右到左传递的.由于在从堆栈指针中减去时已经为三个参数分配了堆栈空间,因此将1移到相对于当前堆栈指针的最高"位置(+8),将2移到中间(+4), y 中的值被移动到堆栈指针本身.这与在堆栈上压入 1,在堆栈上压入 2,然后在堆栈上压入 y 相同.到最后一个push指令,1是ESP的+8,2是ESP的+4,y是ESP的+0.请注意,在 func 内部,它必须将这些偏移量加 8,因为返回地址是从 call 指令压入堆栈的,而 func 压入 EBP 以建立堆栈帧.

The parameters are being passed right-to-left. Since the stack space was already allocated for the three parameters when it was subtracted from the stack pointer, 1 is moved into the "highest" position relative to the current stack pointer (+8), 2 is moved into the middle (+4), and the value in y is moved into the stack pointer itself. This is the same as pushing 1 on the stack, pushing 2 on the stack, and then pushing y on the stack. By the last push instruction, 1 is +8 from ESP, 2 is +4 from ESP, and y is +0 from ESP. Note that inside of func, it has to add 8 to these offsets because the return address is pushed on the stack from the call instruction and func pushes EBP to establish a stack frame.

对哪种结构感到困惑?

这篇关于组装中的 EBP、ESP 和堆栈框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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