我试图通过使用程序集
编写一个简单的求和函数来理解堆栈以下是我的计划:
.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
关于我做错的任何指示
答案 0 :(得分:4)
您好像在覆盖堆栈指针。 sum
函数的开头应该是;
sum:
pushl %ebp
movl %esp, %ebp <<< copy stack pointer to %ebp, not the other way around
subl $4, %esp