gpt4 book ai didi

linux - 汇编函数整型局部变量

转载 作者:太空狗 更新时间:2023-10-29 11:24:55 25 4
gpt4 key购买 nike

我正在尝试学习基本的 assembly 。我用 C 写了一个简单的程序来翻译成汇编:

void myFunc(int x, int y) {
int z;
}

int main() {
myFunc(20, 10);
return 0;
}

我认为函数的正确翻译应该是这样的:

.text
.globl _start
.type myFunc, @function

myFunc:
pushl %ebp #Push old ebp register on to stack
movl %esp, %ebp #Move esp into ebp so we can reference vars
sub $4, %esp #Subtract 4 bytes from esp to make room for 'z' var
movl $2, -4(%ebp) #Move value 2 into 'z'
movl %ebp, %esp #Restore esp
popl %ebp #Set ebp to 0?
ret #Restore eip and jump to next instruction

_start:
pushl $10 #Push 10 onto stack for 'y' var
pushl $20 #Push 20 onto stack for 'x' var
call myFunc #Jump to myFunc (this pushes ret onto stack)
add $8, %esp #Restore esp to where it was before

movl $1, %eax #Exit syscall
movl $0, %ebx #Return 0
int $0x80 #Interrupt

只是为了仔细检查它,我在 gdb 中运行了它,但对结果感到困惑:

(gdb) disas myFunc
Dump of assembler code for function myFunc:
0x08048374 <myFunc+0>: push ebp
0x08048375 <myFunc+1>: mov ebp,esp
0x08048377 <myFunc+3>: sub esp,0x10
0x0804837a <myFunc+6>: leave
0x0804837b <myFunc+7>: ret
End of assembler dump.

当一个整数的长度是 4 字节时,为什么 gcc 在 0x08048377 从堆栈中减去 0x10(16 字节)?

另外,请假指令等同于以下吗?

    movl %ebp, %esp   #Restore esp
popl %ebp #Set ebp to 0?

使用:

gcc version 4.3.2 (Debian 4.3.2-1.1)
GNU gdb 6.8-debian

最佳答案

根据平台的不同,GCC 可能会选择不同的堆栈对齐方式;这可以被覆盖,但这样做会使程序变慢或崩溃。默认的 -mpreferred-stack-boundary=4 使堆栈与 16 字节地址对齐。假设堆栈指针在函数开始时已经适当对齐,它将在 sub %esp, $10 之后保持对齐。

leave 是一个 x86 宏指令,等同于 mov %ebp, %esp;弹出 %ebp

关于linux - 汇编函数整型局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4684465/

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