1

我试图通过使用汇编编写一个简单的求和函数来理解堆栈

下面是我的程序:

.section .data

.section .text
.globl _start
_start:
        pushl $3
        pushl $2
        call sum
        addl $8, %esp
        movl %eax, %ebx
        movl $1, %eax
        int $0x80
#Purpose: This function is used to compute sum of 2 numbers
.type sum, @function
sum:   
        pushl %ebp
        movl %ebp, %esp
        subl $4, %esp
        movl 8(%ebp), %ecx
        movl 12(%ebp), %ebx
        addl %ecx,%ebx
        movl %ebx,-4(%ebp)
        movl -4(%ebp), %eax
        movl %ebp,%esp
        ret

以上原因是:

[ashok@localhost alp]$ as mysum.s -o mysum.o
[ashok@localhost alp]$ ld mysum.o -o mysum
[ashok@localhost alp]$ ./mysum 
Segmentation fault (core dumped)

当我使用 gdb 检查时,我的 ebp 最初是 0x0,这是导致段错误的原因

(gdb) break 11
    Breakpoint 1 at 0x8048054: file mysum.s, line 11.
    (gdb) n
    The program is not being run.
    (gdb) r
    Starting program: /home/ashok/practice/alp/mysum 
    Breakpoint 1, _start () at mysum.s:11
    11              pushl $3
    (gdb) n
    12              pushl $2
    (gdb) n
    13              call sum
    (gdb) info registers
    eax            0x0      0
    ecx            0x0      0
    edx            0x0      0
    ebx            0x0      0
    esp            0xbffff598       0xbffff598
    ebp            0x0      0x0
    esi            0x0      0
    edi            0x0      0
    eip            0x8048058        0x8048058 <_start+4>
    eflags         0x212    [ AF IF ]
    cs             0x73     115
    ss             0x7b     123
    ds             0x7b     123
    es             0x7b     123
    fs              0x0      0
    gs             0x0      0
    (gdb) s
    21              pushl %ebp
    (gdb) s
    22              movl %ebp, %esp

关于我做错了什么的任何指示

4

1 回答 1

4

您似乎正在覆盖您的堆栈指针。函数的开头sum应该是;

sum:   
    pushl %ebp
    movl %esp, %ebp   <<< copy stack pointer to %ebp, not the other way around
    subl $4, %esp
于 2013-04-28T08:36:00.567 回答