分类: LINUX
2012-03-30 17:17:02
载入一个程序并设置一个断点
把之前的try1.c编译成可执行文件,并用gdb来载入:
$ gdb try1
GNU gdb (Ubuntu/Linaro 7.3-0ubuntu2) 7.3-2011.08
Copyright (C) 2011 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "i686-linux-gnu".
For bug reporting instructions, please see:
<
Reading symbols from /home/tommy/tmp/try1...done.
(gdb)
(gdb)是GDB的输入提示。用run命令运行程序:
(gdb) run
Starting program: /home/tommy/tmp/try1
In main():
x is 5 and is stored at 0xbffff2a8.
xptr points to 0xbffff2a8 which holds 5.
In display():
z is 5 and is stored at 0xbffff290.
zptr points to 0xbffff2a8 which holds 5.
[Inferior 1 (process 18365) exited normally]
我们可以用“break 行号”的方式来设置断点。比如break 5表示在第5行暂停,这时第4行已经执行,而第5行还没有。
(gdb) break 10
Breakpoint 1 at 0x8048475: file try1.c, line 10.
(gdb) run
Starting program: /home/tommy/tmp/try1
In main():
x is 5 and is stored at 0xbffff2a8.
xptr points to 0xbffff2a8 which holds 5.
Breakpoint 1, main () at try1.c:10
10 display(x, xptr);
backtrace命令简单地列出当前在栈上的框架。
(gdb) backtrace
#0 main () at try1.c:10
接着可以用step命令执行下一行代码:
(gdb) step
display (z=5, zptr=0xbffff2a8) at try1.c:15
15 printf("In display():\n");
再用backtrace看下栈上的框架:
(gdb) backtrace
#0 display (z=5, zptr=0xbffff2a8) at try1.c:15
#1 0x08048489 in main () at try1.c:10
一些要注意的地方:
1、我们现在有两个框架。框架1属于main()而框架0属于display()。
2、每个框架列项给出函数的参数。我们看到main没有参数,而display有,而且显示出了参数的值。
3、每个框架列项给出了框架里正被执行的行号。
4、框架的编号系统可能有点令人疑惑。main是1而display是0。这是为了个栈往下增长的概念一致。
不带参数的frame命令可以让GDB告诉我们现在在哪个框架里:
(gdb) frame
#0 display (z=5, zptr=0xbffff2a8) at try1.c:17
17 printf(" zptr points to %p which holds %d.\n", zptr, *zptr);
当前的frame是0,我们可以访问在frame 0里的所有局部变量。相反,我们不能访问其它框架的自动变量。
我们可以用print打印display函数里的z和zptr变量:
(gdb) print z
$3 = 5
(gdb) print zptr
$4 = (int *) 0xbffff2a8
但是我们不访问main里的变量:
(gdb) print x
No symbol "x" in current context.
(gdb) print xptr
No symbol "xptr" in current context.
我们可以使用frame命令来改变当前栈:
(gdb) frame 1
#1 0x08048489 in main () at try1.c:10
10 display(x, xptr);
(gdb) print x
$5 = 5
(gdb) print xptr
$6 = (int *) 0xbffff2a8
(gdb) print z
No symbol "z" in current context.
(gdb) print zptr
No symbol "zptr" in current context.
顺便一提,程序的输出会和GDB的输出混在一起,容易造成混淆。需要花些时间来适应。