为了深入理解汇编程序中的帧指针(ebp)和栈指针(esp)的用法,想亲自调试下程序,我写了一个简单的程序,如下:
保存为hello.c,然后在终端输入gcc -S hello.c,就会有个hello.s生成,也就是上面程序对应的汇编程序了,主要程序清单如下:
然后使用as -gstabs -o hello.o hello.s和ld -o hello hello.o生成可执行文件,最后就可以调试了,这里就是本文的重点了。
一、设断点
break *_start + 1,程序会在nop那里停下来
二、run
三、我调试的每一步
Breakpoint 1, _start () at hello.s:7
7 leal 4(%esp), %ecx
(gdb) next
8 andl $-16, %esp
然后的这句话比较费解 andl %-16, %esp,-16的二进制表示为0xFFFFFFF0,这里是将SP的低4位清零了,这样地址就是16的整数倍了,寻址会更快,因为esp的低4位本身就是0,所以这句话在这里并没有起到作用,我们就把这里跳过,直接next
(gdb) next
9 pushl -4(%ecx)
(gdb) next
10 pushl %ebp
(gdb) next
11 movl %esp, %ebp
(gdb) next
_start () at hello.s:12
12 pushl %ecx
(gdb) next
13 subl $36, %esp
(gdb) next
14 movl $3, -16(%ebp)
(gdb) next
15 movl $4, -12(%ebp)
(gdb) next
16 movl $5, -8(%ebp)
(gdb) next
17 movl -8(%ebp), %eax
3, 4, 5就分别存放到了ebp -16, ebp -12, ebp -8 这3个位置
我们查看下是不是这样的
(gdb) x /4 0xbffff5a8 //果然在
0xbffff5a8: 3 4 5 -1073744444
(gdb) next
18 movl %eax, 8(%esp)
(gdb) next
19 movl -12(%ebp), %eax
(gdb) next
20 movl %eax, 4(%esp)
(gdb) next
21 movl -16(%ebp), %eax
(gdb) next
22 movl %eax, (%esp)
(gdb) next
23 call add
(gdb) step
add () at hello.s:34
34 pushl %ebp
(gdb) next
35 movl %esp, %ebp
(gdb) next
36 movl 12(%ebp), %edx
(gdb) next
37 movl 8(%ebp), %eax
(gdb) next
38 addl %edx, %eax
(gdb) next
39 addl 16(%ebp), %eax
(gdb) next
40 popl %ebp
(gdb) next
add () at hello.s:41
41 ret
(gdb) next
_start () at hello.s:24
24 movl $0, %eax
(gdb) next
25 addl $36, %esp
(gdb) next
26 popl %ecx
(gdb) next
27 popl %ebp
(gdb) next
_start () at hello.s:28
28 leal -4(%ecx), %esp
(gdb) next
_start () at hello.s:29
29 ret
(gdb) next
0x00000001 in ?? ()
程序结束