gpt4 book ai didi

c - 汇编局部变量和寄存器

转载 作者:太空宇宙 更新时间:2023-11-04 08:05:00 25 4
gpt4 key购买 nike

我有这段反汇编的 C 代码 (AT&T),我对两件事有些困惑。首先,我的理解是 EBP-4 应该是堆栈上的第一个局部变量(这里是 int i)。我显然在 EBP-8 中。这是为什么?

其次,是否有必要在对它们进行算术运算之前将值移动到寄存器中? (这是一台 x86 32 位机器)示例:

0x08048402 <+21>: mov 0x8(%ebp),%eax //move parameter a into eax
0x08048405 <+24>: add %eax,-0x4(%ebp) //r += a

为什么不能这样:

0x08048405 <+24>: add 0x8(%ebp),-0x4(%ebp) //r += a

C 代码:

int loop_w (int a, int b){     
int i = 0;
int r = a;
while ( i < 256){
r += a;
a -= b;
i += b;
}
return r;

反汇编:

Dump of assembler code for function loop_w:
0x080483ed <+0>: push %ebp
0x080483ee <+1>: mov %esp,%ebp
0x080483f0 <+3>: sub $0x10,%esp
---------------Above is for stack setup-----------------
0x080483f3 <+6>: movl $0x0,-0x8(%ebp) //I=0
0x080483fa <+13>: mov 0x8(%ebp),%eax //move parameter a into eax
0x080483fd <+16>: mov %eax,-0x4(%ebp) //move a into local var (r=a)
0x08048400 <+19>: jmp 0x8048414 <loop_w+39> //start while loop
0x08048402 <+21>: mov 0x8(%ebp),%eax //move parameter a into eax
0x08048405 <+24>: add %eax,-0x4(%ebp) //r += a
0x08048408 <+27>: mov 0xc(%ebp),%eax //move parameter b into eax
0x0804840b <+30>: sub %eax,0x8(%ebp) //a += parameter b
0x0804840e <+33>: mov 0xc(%ebp),%eax //move parameter b into eax
0x08048411 <+36>: add %eax,-0x8(%ebp) //i+=b
0x08048414 <+39>: cmpl $0xff,-0x8(%ebp) //compare i to 256
0x0804841b <+46>: jle 0x8048402 <loop_w+21> //continue loop if failed condition
=> 0x0804841d <+48>: mov -0x4(%ebp),%eax //move r into eax
0x08048420 <+51>: leave
0x08048421 <+52>: ret //return eax
End of assembler dump.

最佳答案

编译器可以决定将局部变量放置在何处。出于对齐原因,它可能已将其放置在 %ebp - 8 处。

关于你的第二个问题——变量是否必须在操作前加载到寄存器中,取决于架构提供的操作和指令集。

您提到了 x86。特别是对于这种架构,X86 不允许带有两个内存操作数的指令(是的,有一些异常(exception))。

您可以按指令搜索以了解它们允许的操作数类型。

关于c - 汇编局部变量和寄存器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43439767/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com