基本上,在这个例子中,我想在代码的特定位置获取一些变量值;并让它们输出直到程序崩溃。所以这里首先是一个小程序保证会崩溃只需几步,test.c
:
#include <stdio.h>
#include <stdlib.h>
int icount = 1; // default value
main(int argc, char *argv[])
{
int i;
if (argc == 2) {
icount = atoi(argv[1]);
}
i = icount;
while (i > -1) {
int b = 5 / i;
printf(" 5 / %d = %d \n", i, b );
i = i - 1;
}
printf("Finished\n");
return 0;
}
程序接受命令行参数的唯一原因是能够在崩溃之前选择步骤数 - 并表明gdb
忽略--args
在批处理模式下。我用这个编译:
gcc -g test.c -o test.exe
然后,我准备以下脚本 - 这里的主要技巧是分配一个command
每一个breakpoint
,最终将continue
(也可以看看自动化 gdb:在每次调用函数 put 时显示回溯)。这个脚本我称之为test.gdb
:
# http://sourceware.org/gdb/wiki/FAQ: to disable the
# "---Type <return> to continue, or q <return> to quit---"
# in batch mode:
set width 0
set height 0
set verbose off
# at entry point - cmd1
b main
commands 1
print argc
continue
end
# printf line - cmd2
b test.c:17
commands 2
p i
p b
continue
end
# int b = line - cmd3
b test.c:16
commands 3
p i
p b
continue
end
# show arguments for program
show args
printf "Note, however: in batch mode, arguments will be ignored!\n"
# note: even if arguments are shown;
# must specify cmdline arg for "run"
# when running in batch mode! (then they are ignored)
# below, we specify command line argument "2":
run 2 # run
#start # alternative to run: runs to main, and stops
#continue
请注意,如果您打算在批处理模式下使用它,则必须在最后“启动”脚本run
or start
或类似的东西。
有了这个脚本,我就可以调用gdb
在批处理模式下 - 这将在终端中生成以下输出:
$ gdb --batch --command=test.gdb --args ./test.exe 5
Breakpoint 1 at 0x804844d: file test.c, line 10.
Breakpoint 2 at 0x8048485: file test.c, line 17.
Breakpoint 3 at 0x8048473: file test.c, line 16.
Argument list to give program being debugged when it is started is "5".
Note, however: in batch mode, arguments will be ignored!
Breakpoint 1, main (argc=2, argv=0xbffff424) at test.c:10
10 if (argc == 2) {
$1 = 2
Breakpoint 3, main (argc=2, argv=0xbffff424) at test.c:16
16 int b = 5 / i;
$2 = 2
$3 = 134513899
Breakpoint 2, main (argc=2, argv=0xbffff424) at test.c:17
17 printf(" 5 / %d = %d \n", i, b );
$4 = 2
$5 = 2
5 / 2 = 2
Breakpoint 3, main (argc=2, argv=0xbffff424) at test.c:16
16 int b = 5 / i;
$6 = 1
$7 = 2
Breakpoint 2, main (argc=2, argv=0xbffff424) at test.c:17
17 printf(" 5 / %d = %d \n", i, b );
$8 = 1
$9 = 5
5 / 1 = 5
Breakpoint 3, main (argc=2, argv=0xbffff424) at test.c:16
16 int b = 5 / i;
$10 = 0
$11 = 5
Program received signal SIGFPE, Arithmetic exception.
0x0804847d in main (argc=2, argv=0xbffff424) at test.c:16
16 int b = 5 / i;
请注意,当我们指定命令行参数 5 时,循环仍然只旋转两次(正如run
in the gdb
脚本);如果run
没有任何参数,它只旋转一次(程序的默认值),确认--args ./test.exe 5
被忽略。
但是,由于现在这是在单个调用中输出,并且无需任何用户交互,因此可以使用以下命令轻松地将命令行输出捕获在文本文件中bash
重定向,说:
gdb --batch --command=test.gdb --args ./test.exe 5 > out.txt
还有一个使用 python 自动化 gdb 的示例c - GDB 自动步进 - 自动打印行,同时自由运行?