第 36 / 187 篇

3.1. 用 GDB 调试

说明

本文是个人学习用的非官方中英对照译文,原文:https://diveintosystems.org/book/C3-C_debug/gdb.html。
原书采用 CC BY-NC-ND 4.0 许可(禁止演绎),请勿公开传播本译文。
标为「译注」「现代更新」的内容是译者补充,不代表原书作者观点;代码与原文逐字一致,未作改动。

3.1. Debugging with GDB

GDB 可以帮助程序员找出并修复程序中的缺陷。GDB 适用于用多种语言编译的程序,但这里我们只关注 C。调试器是一个控制另一个程序(被调试的程序)执行的程序——它让程序员在程序运行时看到程序在做什么。使用调试器可以帮助程序员发现缺陷,并确定所发现缺陷的原因。下面是 GDB 能执行的一些有用操作:

GDB can help programmers find and fix bugs in their programs. GDB works with programs compiled in a variety of languages, but we focus on C here. A debugger is a program that controls the execution of another program (the program being debugged) — it allows programmers to see what their programs are doing as they run. Using a debugger can help programmers discover bugs and determine the causes of the bugs they find. Here are some useful actions that GDB can perform:

  • 启动程序并逐行单步执行
  • Start a program and step through it line by line
  • 在程序执行到代码中的某些位置时暂停它
  • Pause the execution of a program when it reaches certain points in its code
  • 在满足用户指定的条件时暂停程序的执行
  • Pause the execution of a program on user-specified conditions
  • 在程序暂停的执行点显示变量的值
  • Show the values of variables at the point in execution that a program is paused
  • 暂停后继续执行程序
  • Continue a program’s execution after a pause
  • 在程序崩溃时检查它的执行状态
  • Examine the program’s execution state at the point when it crashes
  • 检查调用栈中任意一个栈帧的内容
  • Examine the contents of any stack frame on the call stack

GDB 用户通常会在程序中设置断点(breakpoint)。断点指定程序中的一个位置,GDB 会在那里暂停程序的执行。当正在执行的程序遇到断点时,GDB 会暂停它的执行,让用户输入 GDB 命令来检查程序变量和栈的内容、一次一行地单步执行程序、添加新的断点,以及继续执行程序直到遇到下一个断点。

GDB users typically set breakpoints in their programs. A breakpoint specifies a point in the program where GDB will pause the program’s execution. When the executing program hits a breakpoint, GDB pauses its execution and allows the user to enter GDB commands to examine program variables and stack contents, step through the execution of the program one line at a time, add new breakpoints, and continue the program’s execution until it hits the next breakpoint.

许多 Unix 系统还提供 Data Display Debugger(DDD),它是对命令行调试程序(例如 GDB)的一层易用的图形界面封装。DDD 程序接受与 GDB 相同的参数和命令,但它既提供带有调试菜单选项的图形界面,也提供 GDB 的命令行界面。

Many Unix systems also provide the Data Display Debugger (DDD), an easy-to-use GUI wrapper around a command-line debugger program (GDB, for example). The DDD program accepts the same parameters and commands as GDB, but it provides a GUI interface with debugging menu options as well as the command line interface to GDB.

在讨论了GDB 入门的一些准备知识之后,我们给出两个 GDB 调试会话示例,在查找不同类型缺陷的情境中介绍常用的 GDB 命令。第一个会话(用 GDB 调试 badprog.c)演示如何用 GDB 命令找出 C 程序中的逻辑缺陷。第二个会话(用 GDB 调试 segfaulter.c)演示如何在程序崩溃时用 GDB 命令检查程序的执行状态,从而找出崩溃的原因。

After discussing a few preliminaries about how to get started with GDB, we present two example GDB debugging sessions that introduce commonly used GDB commands in the context of finding different types of bugs. The first session (GDB on badprog.c), shows how to use GDB commands to find logic bugs in a C program. The second session (GDB on segfaulter.c) shows an example of using GDB commands to examine the program execution state at the point when a program crashes in order to discover the cause of the crash.

在常用 GDB 命令一节中,我们会更详细地介绍常用的 GDB 命令,并给出其中一些命令的更多示例。后面几节会讨论 GDB 的一些高级特性。

In the common GDB commands section, we describe commonly used GDB commands in more detail, showing more examples of some commands. In later sections, we discuss some advanced GDB features.

3.1.1. GDB 入门

3.1.1. Getting Started with GDB

调试程序时,用 -g 选项编译会有帮助,它会在二进制可执行文件中加入额外的调试信息。这些额外信息帮助调试器在二进制可执行文件中找到程序变量和函数,并使它能把机器码指令映射到 C 源代码行(也就是 C 程序员能看懂的程序形式)。此外,为调试而编译时,要避免编译器优化(例如,不要用 -O2 构建)。经过编译器优化的代码往往很难调试,因为优化后的机器码序列常常无法清晰地对应回 C 源代码。尽管接下来各节使用的是 -g 标志,有些用户使用 -g3 标志可能会得到更好的效果,它能提供更多的调试信息。

When debugging a program, it helps to compile it with the -g option, which adds extra debugging information to the binary executable file. This extra information helps the debugger find program variables and functions in the binary executable and enables it to map machine code instructions to lines of C source code (the form of the program that the C programmer understands). Also, when compiling for debugging, avoid compiler optimizations (for example, do not build with -O2). Compiler-optimized code is often very difficult to debug because sequences of optimized machine code often do not clearly map back to C source code. Although we cover the use of the -g flag in the following sections, some users may get better results with the -g3 flag, which can reveal extra debugging information.

译注

-g3 比 -g(等同于 -g2)多出的主要是宏定义信息,有了它就能在 GDB 里用 print MAX 之类的命令查看 #define 宏的值。另外 GCC 还提供 -Og:只做不影响调试体验的优化,适合「既要调试、又不想完全不优化」的场合。

下面是一条构建适合用 GDB 调试的可执行文件的 gcc 命令示例:

Here is an example gcc command that will build a suitable executable for debugging with GDB:

1
$ gcc -g myprog.c

要启动 GDB,就以可执行文件为参数调用它。例如:

To start GDB, invoke it on the executable file. For example:

1
2
$ gdb a.out
(gdb) # the gdb command prompt

GDB 启动后会打印 (gdb) 提示符,让用户在它开始运行 a.out 程序之前输入 GDB 命令(比如设置断点)。

When GDB starts, it prints the (gdb) prompt, which allows the user to enter GDB commands (such as setting breakpoints) before it starts running the a.out program.

类似地,以可执行文件为参数调用 DDD:

Similarly, to invoke DDD on the executable file:

1
$ ddd a.out

有时程序因出错而终止时,操作系统会转储(dump)一个 core 文件,其中包含程序崩溃时的状态信息。用 core 文件和生成它的可执行文件来运行 GDB,就可以在 GDB 中检查这个 core 文件的内容:

Sometimes, when a program terminates with an error, the operating system dumps a core file containing information about the state of the program when it crashed. The contents of this core file can be examined in GDB by running GDB with the core file and the executable that generated it:

译注 · 参数顺序

按 GDB 手册,正确的写法是可执行文件在前、core 文件在后:gdb a.out core(下面代码中写成了 gdb core a.out)。GDB 手册:Invoking GDB

另外,许多 Linux 系统默认不生成 core 文件,需要先在 shell 中执行 ulimit -c unlimited;使用 systemd 的发行版通常由 systemd-coredump 统一收集 core 文件,可以用 coredumpctl gdb 直接打开最近一次的崩溃。

1
2
$ gdb core a.out
(gdb) where # the where command shows point of crash

3.1.2. GDB 会话示例

3.1.2. Example GDB Sessions

我们通过两个用 GDB 调试程序的会话示例来演示 GDB 的常用功能。第一个例子用 GDB 找出并修复程序中的两个缺陷,第二个例子用 GDB 调试一个会崩溃的程序。这两个示例会话中演示的 GDB 命令包括:

We demonstrate common features of GDB through two example sessions of using GDB to debug programs. The first is an example of using GDB to find and fix two bugs in a program, and the second is an example of using GDB to debug a program that crashes. The set of GDB commands that we demonstrate in these two example sessions includes:

命令 说明
break 设置断点
run 从头开始运行程序
cont 继续执行程序,直到遇到断点
quit 退出 GDB 会话
next 让程序执行下一行 C 代码,然后暂停
step 让程序执行下一行 C 代码;如果下一行含有函数调用,就进入该函数并暂停
list 列出暂停点或指定位置附近的 C 源代码
print 打印程序变量(或表达式)的值
where 打印调用栈
frame 进入某个特定栈帧的上下文
Command Description
break Set a breakpoint
run Start program running from the beginning
cont Continue execution of the program until it hits a breakpoint
quit Quit the GDB session
next Allow program to execute the next line of C code and then pause it
step Allow program to execute the next line of C code; if the next line contains a function call, step into the function and pause
list List C source code around pause point or specified point
print Print out the value of a program variable (or expression)
where Print the call stack
frame Move into the context of a specific stack frame

用 GDB 调试程序的示例(badprog.c)

Example Using GDB to Debug a Program (badprog.c)

第一个 GDB 会话示例调试 badprog.c 程序。这个程序本应找出一个 int 数组中的最大值。然而运行时,它错误地认为数组中的最大值是 17,而正确的最大值是 60。这个例子展示 GDB 如何检查程序的运行时状态,以确定程序为什么没有算出预期的结果。具体来说,这个调试会话揭示了两个缺陷:

The first example GDB session debugs the badprog.c program. This program is supposed to find the largest value in an array of int values. However, when run, it incorrectly finds that 17 is the largest value in the array instead of the correct largest value, which is 60. This example shows how GDB can examine the program’s runtime state to determine why the program is not computing the expected result. In particular, this example debugging session reveals two bugs:

  1. 循环边界错误,导致程序访问了数组边界之外的元素。
  1. An error with loop bounds resulting in the program accessing elements beyond the bounds of the array.
  1. 某个函数没有把正确的值返回给调用者。
  1. An error in a function not returning the correct value to its caller.

要用 GDB 检查程序,首先用 -g 编译程序,为可执行文件加入调试信息:

To examine a program with GDB, first compile the program with -g to add debugging information to the executable:

1
$ gcc -g badprog.c

接着,对二进制可执行程序(a.out)运行 GDB。GDB 完成初始化后打印出 (gdb) 提示符,用户可以在这里输入 GDB 命令:

Next, run GDB on the binary executable program (a.out). GDB initializes and prints the (gdb) prompt, where the user can enter GDB commands:

1
2
3
4
5
6
$ gdb ./a.out

GNU gdb (Ubuntu 8.1-0ubuntu3) 8.1.0.20180409-git
Copyright (C) 2018 Free Software Foundation, Inc.
...
(gdb)

此时 GDB 还没有开始运行程序。常见的第一步调试操作是在 main() 函数中设置一个断点,让程序在执行 main() 的第一条指令之前暂停。break 命令在指定位置(这里是 main() 函数的开头)设置一个「断点」(暂停程序):

At this point GDB has not yet started running the program. A common first debugging step is to set a breakpoint in the main() function to pause the program’s execution right before it executes the first instruction in main(). The break command sets a “breakpoint” (pauses the program) at a specified location (in this case at the start of the main() function):

1
2
3
(gdb) break main

Breakpoint 1 at 0x8048436: file badprog.c, line 36.

run 命令让 GDB 启动程序:

The run command tells GDB to start the program:

1
2
(gdb) run
Starting program: ./a.out

如果程序需要命令行参数,就把它们写在 run 命令之后(例如,run 100 200 会以命令行参数 100 和 200 运行 a.out)。

If the program takes command line arguments, provide them after the run command (for example, run 100 200 would run a.out with the command line arguments 100 and 200).

输入 run 之后,GDB 从头开始执行程序,一直运行到遇到断点为止。到达断点时,GDB 在执行断点处那行代码之前暂停程序,并打印出断点编号和与断点对应的源代码行。在这个例子中,GDB 在执行程序第 36 行之前暂停了程序。然后它打印出 (gdb) 提示符,等待进一步的指令:

After entering run, GDB starts the program’s execution at its beginning, and it runs until it hits a breakpoint. Upon reaching a breakpoint, GDB pauses the program before executing the line of code at the breakpoint, and prints out the breakpoint number and source code line associated with the breakpoint. In this example, GDB pauses the program just before executing line 36 of the program. It then prints out the (gdb) prompt and waits for further instructions:

1
2
3
4
Breakpoint 1, main (argc=1, argv=0x7fffffffe398) at badprog.c:36
36 int main(int argc, char *argv[]) {

(gdb)

程序在断点处暂停时,用户往往想看看断点附近的 C 源代码。GDB 的 list 命令会显示断点周围的代码:

Often when a program pauses at a breakpoint, the user wants to see the C source code around the breakpoint. The GDB list command displays the code surrounding the breakpoint:

1
2
3
4
5
6
7
8
9
10
11
(gdb) list
29 }
30 return 0;
31 }
32
33 /***************************************/
34 int main(int argc, char *argv[]) {
35
36 int arr[5] = { 17, 21, 44, 2, 60 };
37
38 int max = arr[0];

之后再调用 list,会显示接下来的若干行源代码。list 也可以带上具体的行号(例如 list 11)或函数名,列出程序中指定部分的源代码。例如:

Subsequent calls to list display the next lines of source code following these. list can also be used with a specific line number (for example, list 11) or with a function name to list the source code at a specified part of the program. For example:

1
2
3
4
5
6
7
8
9
10
11
(gdb) list findAndReturnMax
12 * array: array of integer values
13 * len: size of the array
14 * max: set to the largest value in the array
15 * returns: 0 on success and non-zero on an error
16 */
17 int findAndReturnMax(int *array1, int len, int max) {
18
19 int i;
20
21 if (!array1 || (len <=0) ) {

遇到断点之后,用户可能想一次执行一行代码,并在每行执行后检查程序状态。GDB 的 next 命令只执行紧接着的下一行 C 代码。程序执行完这行代码后,GDB 会再次暂停程序。print 命令打印程序变量的值。下面是几次调用 next 和 print,展示它们对接下来两行执行的效果。注意,next 之后列出的那一行源代码还没有执行——它显示的是程序暂停的那一行,也就是下一步将要执行的那一行:

The user may want to execute one line of code at a time after hitting a breakpoint, examining program state after each line is executed. The GDB next command executes just the very next line of C code. After the program executes this line of code, GDB pauses the program again. The print command prints the values of program variables. Here are a few calls to next and print to show their effects on the next two lines of execution. Note that the source code line listed after a next has not yet been executed — it shows the line where the program is paused, which represents the line that will be executed next:

1
2
3
4
5
6
7
8
9
10
11
12
13
(gdb) next
36 int arr[5] = { 17, 21, 44, 2, 60 };
(gdb) next
38 int max = arr[0];
(gdb) print max
$3 = 0
(gdb) print arr[3]
$4 = 2
(gdb) next
40 if ( findAndReturnMax(arr, 5, max) != 0 ) {
(gdb) print max
$5 = 17
(gdb)

执行到这里,main 函数已经初始化了它的局部变量 arr 和 max,即将调用 findAndReturnMax() 函数。GDB 的 next 命令执行下一整行 C 源代码。如果这一行含有函数调用,那么该函数调用的完整执行及其返回都会作为一次 next 命令的一部分执行完。想要观察函数执行过程的用户,应当使用 GDB 的 step 命令而不是 next 命令:step 会进入函数调用内部,在执行函数的第一行之前暂停程序。

At this point in the program’s execution, the main function has initialized its local variables arr and max and is about to make a call to the findAndReturnMax() function. The GDB next command executes the next full line of C source code. If that line includes a function call, the full execution of that function call and its return is executed as part of a single next command. A user who wants to observe the execution of the function should issue GDB’s step command instead of the next command: step steps into a function call, pausing the program before the first line of the function is executed.

由于我们怀疑这个程序的缺陷与 findAndReturnMax() 函数有关,我们想进入这个函数的执行过程,而不是跳过它。因此,在第 40 行暂停时,step 命令接下来会让程序在 findAndReturnMax() 的开头暂停(用户也可以在 findAndReturnMax() 处设置断点,让程序的执行在那里暂停):

Because we suspect that the bug in this program is related to the findAndReturnMax() function, we want to step into the function’s execution rather than past it. So, when paused at line 40, the step command will next pause the program at the start of the findAndReturnMax() (alternately, the user could set a breakpoint at findAndReturnMax() to pause the program’s execution at that point):

1
2
3
4
5
6
(gdb) next
40 if ( findAndReturnMax(arr, 5, max) != 0 ) {
(gdb) step
findAndReturnMax (array1=0x7fffffffe290, len=5, max=17) at badprog.c:21
21 if (!array1 || (len <=0) ) {
(gdb)

程序现在暂停在 findAndReturnMax 函数内部,它的局部变量和参数现在处于作用域内。print 命令显示它们的值,list 显示暂停点附近的 C 源代码:

The program is now paused inside the findAndReturnMax function, whose local variables and parameters are now in scope. The print command shows their values, and list displays the C source code around the pause point:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
(gdb) print array1[0]
$6 = 17
(gdb) print max
$7 = 17
(gdb) list
16 */
17 int findAndReturnMax(int *array1, int len, int max) {
18
19 int i;
20
21 if (!array1 || (len <=0) ) {
22 return -1;
23 }
24 max = array1[0];
25 for (i=1; i <= len; i++) {
(gdb) list
26 if(max < array1[i]) {
27 max = array1[i];
28 }
29 }
30 return 0;
31 }
32
33 /***************************************/
34 int main(int argc, char *argv[]) {
35

由于我们认为这个函数有缺陷,可能会想在函数内部设置一个断点,以便在它执行到一半时检查运行时状态。特别是,在修改 max 的那一行设置断点,可能有助于我们看清这个函数在做什么。

Because we think there is a bug related to this function, we may want to set a breakpoint inside the function so that we can examine the runtime state part way through its execution. In particular, setting a breakpoint on the line when max is changed may help us see what this function is doing.

我们可以在程序中的特定行号(第 27 行)设置断点,并用 cont 命令让 GDB 从暂停点继续执行应用程序。只有当程序遇到断点时,GDB 才会暂停程序并再次取得控制权,让用户输入其他 GDB 命令。

We can set a breakpoint at a specific line number in the program (line 27) and use the cont command to tell GDB to let the application’s execution continue from its paused point. Only when the program hits a breakpoint will GDB pause the program and grab control again, allowing the user to enter other GDB commands.

1
2
3
4
5
6
7
8
9
10
11
12
(gdb) break 27
Breakpoint 2 at 0x555555554789: file badprog.c, line 27.

(gdb) cont
Continuing.

Breakpoint 2, findAndReturnMax (array1=0x...e290,len=5,max=17) at badprog.c:27
27 max = array1[i];
(gdb) print max
$10 = 17
(gdb) print i
$11 = 1

display 命令让 GDB 在每次遇到断点时自动打印同一组程序变量。例如,我们会在程序每次遇到断点时(即 findAndReturnMax() 中循环的每次迭代)显示 i、max 和 array1[i] 的值:

The display command asks GDB to automatically print out the same set of program variables every time a breakpoint is hit. For example, we will display the values of i, max, and array1[i] every time the program hits a breakpoint (in each iteration of the loop in findAndReturnMax()):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
(gdb) display i
1: i = 1
(gdb) display max
2: max = 17
(gdb) display array1[i]
3: array1[i] = 21

(gdb) cont
Continuing.

Breakpoint 2, findAndReturnMax (array1=0x7fffffffe290, len=5, max=21)
at badprog.c:27
27 max = array1[i];
1: i = 2
2: max = 21
3: array1[i] = 44

(gdb) cont
Continuing.

Breakpoint 2, findAndReturnMax (array1=0x7fffffffe290, len=5, max=21)
at badprog.c:27
27 max = array1[i];
1: i = 3
2: max = 44
3: array1[i] = 2

(gdb) cont

Breakpoint 2, findAndReturnMax (array1=0x7fffffffe290, len=5, max=44)
at badprog.c:27
27 max = array1[i];
1: i = 4
2: max = 44
3: array1[i] = 60

(gdb) cont
Breakpoint 2, findAndReturnMax (array1=0x7fffffffe290, len=5, max=60)
at badprog.c:27
27 max = array1[i];
1: i = 5
2: max = 60
3: array1[i] = 32767

(gdb)

我们找到了第一个缺陷!array1[i] 的值是 32767,这个值并不在传入的数组中;而 i 的值是 5,但 5 并不是这个数组的有效下标。通过 GDB,我们发现 for 循环的边界需要改为 i < len。

We found our first bug! The value of array1[i] is 32767, a value not in the passed array, and the value of i is 5, but 5 is not a valid index into this array. Through GDB we discovered that the for loop bounds need to be fixed to i < len.

这时,我们可以退出 GDB 会话,到代码中修复这个缺陷。要退出 GDB 会话,输入 quit:

At this point, we could exit the GDB session and fix this bug in the code. To quit a GDB session, type quit:

1
2
3
(gdb) quit
The program is running. Exit anyway? (y or n) y
$

修复这个缺陷、重新编译并运行程序后,它仍然找不到正确的最大值(它仍然认为最大值是 17 而不是 60)。根据之前的 GDB 运行情况,我们可能会怀疑在调用 findAndReturnMax() 函数或从中返回时存在错误。我们在 GDB 中重新运行新版本的程序,这次在 findAndReturnMax() 函数的入口处设置一个断点:

After fixing this bug, recompiling, and running the program, it still does not find the correct max value (it still finds that 17 is the max value and not 60). Based on our previous GDB run, we may suspect that there is an error in calling or returning from the findAndReturnMax() function. We re-run the new version of our program in GDB, this time setting a breakpoint at the entry to the findAndReturnMax() function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
$ gdb ./a.out
...
(gdb) break main
Breakpoint 1 at 0x7c4: file badprog.c, line 36.

(gdb) break findAndReturnMax
Breakpoint 2 at 0x748: file badprog.c, line 21.

(gdb) run
Starting program: ./a.out

Breakpoint 1, main (argc=1, argv=0x7fffffffe398) at badprog.c:36
36 int main(int argc, char *argv[]) {
(gdb) cont
Continuing.

Breakpoint 2, findAndReturnMax (array1=0x7fffffffe290, len=5, max=17)
at badprog.c:21
21 if (!array1 || (len <=0) ) {
(gdb)

如果怀疑函数的参数或返回值有缺陷,检查栈的内容可能会有帮助。GDB 的 where(或 bt,即 “backtrace”,回溯)命令会打印栈的当前状态。在这个例子中,main() 函数位于栈底(在第 1 帧),正在第 40 行执行对 findAndReturnMax() 的调用。findAndReturnMax() 函数位于栈顶(在第 0 帧),当前暂停在第 21 行:

If we suspect a bug in the arguments or return value of a function, it may be helpful to examine the contents of the stack. The where (or bt, for “backtrace”) GDB command prints the current state of the stack. In this example, the main() function is on the bottom of the stack (in frame 1) and is executing a call to findAndReturnMax() at line 40. The findAndReturnMax() function is on the top of the stack (in frame 0), and is currently paused at line 21:

1
2
3
(gdb) where
#0 findAndReturnMax (array1=0x7fffffffe290, len=5, max=17) at badprog.c:21
#1 0x0000555555554810 in main (argc=1, argv=0x7fffffffe398) at badprog.c:40

GDB 的 frame 命令可以进入栈上任意一帧的上下文。在每个栈帧的上下文中,用户可以检查该帧中的局部变量和参数。在这个例子中,我们进入栈帧 1(调用者的上下文),打印出 main() 函数传给 findAndReturnMax() 的实参的值(例如 arr 和 max):

GDB’s frame command moves into the context of any frame on the stack. Within each stack frame context, a user can examine the local variables and parameters in that frame. In this example, we move into stack frame 1 (the caller’s context) and print out the values of the arguments that the main() function passes to findAndReturnMax() (for example, arr and max):

1
2
3
4
5
6
7
8
(gdb) frame 1
#1 0x0000555555554810 in main (argc=1, argv=0x7fffffffe398) at badprog.c:40
40 if ( findAndReturnMax(arr, 5, max) != 0 ) {
(gdb) print arr
$1 = {17, 21, 44, 2, 60}
(gdb) print max
$2 = 17
(gdb)

实参的值看起来没问题,所以我们来检查 findAndReturnMax() 函数的返回值。为此,我们在 findAndReturnMax() 即将返回之前加一个断点,看看它为 max 算出了什么值:

The argument values look fine, so let’s check the findAndReturnMax() function’s return value. To do this, we add a breakpoint right before findAndReturnMax() returns to see what value it computes for its max:

1
2
3
4
5
6
7
8
9
10
11
(gdb) break 30
Breakpoint 3 at 0x5555555547ae: file badprog.c, line 30.
(gdb) cont
Continuing.

Breakpoint 3, findAndReturnMax (array1=0x7fffffffe290, len=5, max=60)
at badprog.c:30
30 return 0;

(gdb) print max
$3 = 60

这表明函数已经找到了正确的最大值(60)。我们再执行接下来的几行代码,看看 main() 函数收到的是什么值:

This shows that the function has found the correct max value (60). Let’s execute the next few lines of code and see what value the main() function receives:

1
2
3
4
5
6
7
8
9
10
11
(gdb) next
31 }
(gdb) next
main (argc=1, argv=0x7fffffffe398) at badprog.c:44
44 printf("max value in the array is %d\n", max);

(gdb) where
#0 main (argc=1, argv=0x7fffffffe398) at badprog.c:44

(gdb) print max
$4 = 17

我们找到了第二个缺陷!findAndReturnMax() 函数找出了传入数组中正确的最大值(60),但没有把这个值返回给 main() 函数。要修复这个错误,要么修改 findAndReturnMax(),让它返回 max 的值,要么加一个「按指针传递」的参数,让函数通过它修改 main() 函数的局部变量 max 的值。

We found the second bug! The findAndReturnMax() function identifies the correct largest value in the passed array (60), but it doesn’t return that value back to the main() function. To fix this error, we need to either change findAndReturnMax() to return its value of max or add a “pass-by-pointer” parameter that the function will use to modify the value of the main() function’s max local variable.

用 GDB 调试会崩溃的程序的示例(segfaulter.c)

Example Using GDB to Debug a Program That Crashes (segfaulter.c)

第二个 GDB 会话示例(在 segfaulter.c 程序上运行)演示程序崩溃时 GDB 的行为,以及如何用 GDB 帮助找出崩溃的原因。

The second example GDB session (run on the segfaulter.c program) demonstrates how GDB behaves when a program crashes and how we can use GDB to help discover why the crash occurs.

在这个例子中,我们直接在 GDB 中运行 segfaulter 程序,让它崩溃:

In this example, we just run the segfaulter program in GDB and let it crash:

1
2
3
4
5
6
7
8
9
$ gcc -g -o segfaulter segfaulter.c
$ gdb ./segfaulter

(gdb) run
Starting program: ./segfaulter

Program received signal SIGSEGV, Segmentation fault.
0x00005555555546f5 in initfunc (array=0x0, len=100) at segfaulter.c:14
14 array[i] = i;

程序一崩溃,GDB 就会在崩溃点暂停程序的执行并取得控制权。GDB 允许用户发出命令,检查程序崩溃时的运行时状态,这往往能帮助发现程序崩溃的原因以及如何修复。GDB 的 where 和 list 命令对于确定程序在哪里崩溃特别有用:

As soon as the program crashes, GDB pauses the program’s execution at the point it crashes and grabs control. GDB allows a user to issue commands to examine the program’s runtime state at the point of the program crash, often leading to discovering why the program crashed and how to fix the cause of the crash. The GDB where and list commands are particularly useful for determining where a program crashes:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
(gdb) where
#0 0x00005555555546f5 in initfunc (array=0x0, len=100) at segfaulter.c:14
#1 0x00005555555547a0 in main (argc=1, argv=0x7fffffffe378) at segfaulter.c:37

(gdb) list
9 int initfunc(int *array, int len) {
10
11 int i;
12
13 for(i=1; i <= len; i++) {
14 array[i] = i;
15 }
16 return 0;
17 }
18

这一输出告诉我们,程序在 initfunc() 函数的第 14 行崩溃。检查第 14 行处参数和局部变量的值,也许能告诉我们它为什么崩溃:

This output tells us that the program crashes on line 14, in the initfunc() function. Examining the values of the parameters and local variables on line 14 may tell us why it crashes:

1
2
3
4
(gdb) print i
$2 = 1
(gdb) print array[i]
Cannot access memory at address 0x4

i 的值看起来没问题,但我们在试图访问 array 的下标 i 时看到了错误。我们打印出 array 的值(即数组基地址的值),看看能否发现什么:

The value of i seems fine, but we see an error when trying to access index i of array. Let’s print out the value of array (the value of the base address of the array) to see if that tells us anything:

1
2
(gdb) print array
$3 = (int *) 0x0

我们找到了崩溃的原因!数组的基地址是零(即 NULL),而我们知道,(通过 array[i])对空指针解引用会导致程序崩溃。

We have found the cause of the crash! The base address of the array is zero (or NULL), and we know that dereferencing a null pointer (via array[i]) causes programs to crash.

我们来看看调用者的栈帧,弄清 array 参数为什么是 NULL:

Let’s see if we can figure out why the array parameter is NULL by looking in the caller’s stack frame:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
(gdb) frame 1
#1 0x00005555555547a0 in main (argc=1, argv=0x7fffffffe378) at segfaulter.c:37
37 if(initfunc(arr, 100) != 0 ) {
(gdb) list
32 int main(int argc, char *argv[]) {
33
34 int *arr = NULL;
35 int max = 6;
36
37 if(initfunc(arr, 100) != 0 ) {
38 printf("init error\n");
39 exit(1);
40 }
41
(gdb) print arr
$4 = (int *) 0x0
(gdb)

进入调用者的栈帧,打印出 main() 传给 initfunc() 的实参的值,可以看出 main() 函数向 initfunc() 函数传入了一个空指针。换句话说,用户忘了在调用 initfunc() 之前分配 arr 数组。修复方法是在第 34 行用 malloc() 函数为 arr 分配一些空间。

Moving into the caller’s stack frame and printing out the value of the arguments main() passes to initfunc() shows that the main() function passes a null pointer to the initfunc() function. In other words, the user forgot to allocate the arr array prior to the call to initfunc(). The fix is to use the malloc() function to allocate some space to arr at line 34.

译注

仔细看第 13 行的循环 for(i=1; i <= len; i++):即使分配了 100 个 int,i 等于 100 时 array[100] 仍然越界一个元素——这正是上一个例子里出现过的同类缺陷。修好空指针后,还应把循环改成 for (i = 0; i < len; i++)。

这两个 GDB 会话示例展示了查找程序缺陷时的常用命令。下一节我们会更详细地讨论这些以及其他 GDB 命令。

These two example GDB sessions illustrate commonly used commands for finding bugs in programs. In the next section, we discuss these and other GDB commands in more detail.