说明
本文是个人学习用的非官方中英对照译文,原文: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
-goption, 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-gflag in the following sections, some users may get better results with the-g3flag, which can reveal extra debugging information.
译注
-g3 比 -g(等同于 -g2)多出的主要是宏定义信息,有了它就能在 GDB 里用 print MAX 之类的命令查看 #define 宏的值。另外 GCC 还提供 -Og:只做不影响调试体验的优化,适合「既要调试、又不想完全不优化」的场合。
下面是一条构建适合用 GDB 调试的可执行文件的 gcc 命令示例:
Here is an example
gcccommand 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 | $ gdb a.out |
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 thea.outprogram.
类似地,以可执行文件为参数调用 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 | $ gdb core a.out |
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 breakSet a breakpoint runStart program running from the beginning contContinue execution of the program until it hits a breakpoint quitQuit the GDB session nextAllow program to execute the next line of C code and then pause it stepAllow program to execute the next line of C code; if the next line contains a function call, step into the function and pause listList C source code around pause point or specified point Print out the value of a program variable (or expression) wherePrint the call stack frameMove 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
intvalues. 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:
- 循环边界错误,导致程序访问了数组边界之外的元素。
- An error with loop bounds resulting in the program accessing elements beyond the bounds of the array.
- 某个函数没有把正确的值返回给调用者。
- 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
-gto 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 | $ gdb ./a.out |
此时 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 inmain(). Thebreakcommand sets a “breakpoint” (pauses the program) at a specified location (in this case at the start of themain()function):
1 | (gdb) break main |
run 命令让 GDB 启动程序:
The
runcommand tells GDB to start the program:
1 | (gdb) run |
如果程序需要命令行参数,就把它们写在 run 命令之后(例如,run 100 200 会以命令行参数 100 和 200 运行 a.out)。
If the program takes command line arguments, provide them after the
runcommand (for example,run 100 200would runa.outwith the command line arguments100and200).
输入 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 | Breakpoint 1, main (argc=1, argv=0x7fffffffe398) at badprog.c:36 |
程序在断点处暂停时,用户往往想看看断点附近的 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
listcommand displays the code surrounding the breakpoint:
1 | (gdb) list |
之后再调用 list,会显示接下来的若干行源代码。list 也可以带上具体的行号(例如 list 11)或函数名,列出程序中指定部分的源代码。例如:
Subsequent calls to
listdisplay the next lines of source code following these.listcan 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 | (gdb) list findAndReturnMax |
遇到断点之后,用户可能想一次执行一行代码,并在每行执行后检查程序状态。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
nextcommand executes just the very next line of C code. After the program executes this line of code, GDB pauses the program again. Thenextandnexthas not yet been executed — it shows the line where the program is paused, which represents the line that will be executed next:
1 | (gdb) next |
执行到这里,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
arrandmaxand is about to make a call to thefindAndReturnMax()function. The GDBnextcommand 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 singlenextcommand. A user who wants to observe the execution of the function should issue GDB’sstepcommand instead of thenextcommand:stepsteps 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, thestepcommand will next pause the program at the start of thefindAndReturnMax()(alternately, the user could set a breakpoint atfindAndReturnMax()to pause the program’s execution at that point):
1 | (gdb) next |
程序现在暂停在 findAndReturnMax 函数内部,它的局部变量和参数现在处于作用域内。print 命令显示它们的值,list 显示暂停点附近的 C 源代码:
The program is now paused inside the
findAndReturnMaxfunction, whose local variables and parameters are now in scope. Thelistdisplays the C source code around the pause point:
1 | (gdb) print array1[0] |
由于我们认为这个函数有缺陷,可能会想在函数内部设置一个断点,以便在它执行到一半时检查运行时状态。特别是,在修改 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
maxis 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
contcommand 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 | (gdb) break 27 |
display 命令让 GDB 在每次遇到断点时自动打印同一组程序变量。例如,我们会在程序每次遇到断点时(即 findAndReturnMax() 中循环的每次迭代)显示 i、max 和 array1[i] 的值:
The
displaycommand 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 ofi,max, andarray1[i]every time the program hits a breakpoint (in each iteration of the loop infindAndReturnMax()):
1 | (gdb) display i |
我们找到了第一个缺陷!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 ofiis 5, but 5 is not a valid index into this array. Through GDB we discovered that theforloop bounds need to be fixed toi < 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 | (gdb) quit |
修复这个缺陷、重新编译并运行程序后,它仍然找不到正确的最大值(它仍然认为最大值是 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 thefindAndReturnMax()function:
1 | $ gdb ./a.out |
如果怀疑函数的参数或返回值有缺陷,检查栈的内容可能会有帮助。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(orbt, for “backtrace”) GDB command prints the current state of the stack. In this example, themain()function is on the bottom of the stack (in frame 1) and is executing a call tofindAndReturnMax()at line 40. ThefindAndReturnMax()function is on the top of the stack (in frame 0), and is currently paused at line 21:
1 | (gdb) where |
GDB 的 frame 命令可以进入栈上任意一帧的上下文。在每个栈帧的上下文中,用户可以检查该帧中的局部变量和参数。在这个例子中,我们进入栈帧 1(调用者的上下文),打印出 main() 函数传给 findAndReturnMax() 的实参的值(例如 arr 和 max):
GDB’s
framecommand 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 themain()function passes tofindAndReturnMax()(for example,arrandmax):
1 | (gdb) frame 1 |
实参的值看起来没问题,所以我们来检查 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 beforefindAndReturnMax()returns to see what value it computes for itsmax:
1 | (gdb) break 30 |
这表明函数已经找到了正确的最大值(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 | (gdb) next |
我们找到了第二个缺陷!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 themain()function. To fix this error, we need to either changefindAndReturnMax()to return its value ofmaxor add a “pass-by-pointer” parameter that the function will use to modify the value of themain()function’smaxlocal 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
segfaulterprogram in GDB and let it crash:
1 | $ gcc -g -o segfaulter segfaulter.c |
程序一崩溃,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
whereandlistcommands are particularly useful for determining where a program crashes:
1 | (gdb) where |
这一输出告诉我们,程序在 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 | (gdb) print i |
i 的值看起来没问题,但我们在试图访问 array 的下标 i 时看到了错误。我们打印出 array 的值(即数组基地址的值),看看能否发现什么:
The value of
iseems fine, but we see an error when trying to access indexiofarray. Let’s print out the value ofarray(the value of the base address of the array) to see if that tells us anything:
1 | (gdb) print array |
我们找到了崩溃的原因!数组的基地址是零(即 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 (viaarray[i]) causes programs to crash.
我们来看看调用者的栈帧,弄清 array 参数为什么是 NULL:
Let’s see if we can figure out why the
arrayparameter isNULLby looking in the caller’s stack frame:
1 | (gdb) frame 1 |
进入调用者的栈帧,打印出 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 toinitfunc()shows that themain()function passes a null pointer to theinitfunc()function. In other words, the user forgot to allocate thearrarray prior to the call toinitfunc(). The fix is to use themalloc()function to allocate some space toarrat 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.