%ebp需要的初始值是多少?

Wil*_*hes 0 x86 assembly abi

我有一个简单的汇编程序,它试图通过在内存中存储临时变量来返回3:

.text
    .global _start

_start:
    movl    $2, %ebx
    mov     %ebx, -0x4(%ebp)
    movl    $1, %ebx
    add     -0x4(%ebp), %ebx
    movl    $1, %eax
    int     $0x80
Run Code Online (Sandbox Code Playgroud)

但是,当我运行它时,这会给我一个分段错误:

$ as out.s -o out.o
$ ld -s -o out out.o
$ ./out
segmentation fault
Run Code Online (Sandbox Code Playgroud)

我想这是因为我从不初始化%ebp.如果我只使用寄存器而不访问相关的主内存,我的程序运行正常%ebp.

应该初始化到什么价值?程序malloc在启动时应该是自己的堆栈吗?

Gre*_*ill 5

在程序启动时,%esp寄存器初始化到堆栈的顶部(记住它向下增长),但是%ebp没有初始化.所以你必须这样做.

_start:
    movl     %esp, %ebp
    subl     $4, %esp
    ... rest of your code
Run Code Online (Sandbox Code Playgroud)

这为您的本地变量保留4个字节,可通过偏移量访问-4(%ebp).