爲了深入理解彙編程序中的幀指針(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 ?? ()
程序結束