深入理解计算机系统读书笔记之一个简单汇编程序的调试分析

为了深入理解汇编程序中的帧指针(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 ?? ()


程序结束

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值