GNU Debugger
| GNU Debugger | |
|---|---|
| Developer | GNU Project |
| Initial release | 1986; 39 years ago (1986) |
| Stable release | 16.3[1] Edit this on Wikidata
/ 20 April 2025 |
| Repository | |
| Written in | C, C++, Python |
| Operating system | Unix-like, Windows |
| Type | Debugger |
| License | GPLv3 |
| Website | www |
The GNU Debugger (GDB) is a portable debugger that runs on many Unix-like systems and works for many programming languages, including Ada, Assembly, C, C++, D, Fortran, Haskell, Go, Objective-C, OpenCL C, Modula-2, Pascal, Rust,[2] and partially others.[3] It detects problems in a program while letting it run and allows users to examine different registers.
History
[edit ]GDB was first written by Richard Stallman in 1986 as part of his GNU system, after his GNU Emacs was "reasonably stable".[4] GDB is free software released under the GNU General Public License (GPL). It was modeled after the DBX debugger, which came with Berkeley Unix distributions.[4]
From 1990 to 1993 it was maintained by John Gilmore.[5] Now it is maintained by the GDB Steering Committee which is appointed by the Free Software Foundation.[6]
Technical Features
[edit ]GDB offers extensive facilities for tracing, examining and altering the execution of computer programs. The user can monitor and modify the values of programs' internal variables, and even call functions independently of the program's normal behavior.
Supported Platforms
[edit ]GDB target processors (as of 2003)[needs update ] include: Alpha, ARM, AVR, H8/300, Altera Nios/Nios II, System/370, System 390, x86 and its 64-bit extension x86-64, IA-64 "Itanium", Motorola 68000, MIPS, PA-RISC, PowerPC, RISC-V, SuperH, SPARC, and VAX. Lesser-known target processors supported in the standard release have included A29K, ARC, ETRAX CRIS, D10V, D30V, FR-30, FR-V, Intel i960, 68HC11, Motorola 88000, MCORE, MN10200, MN10300, NS32K, Stormy16, and Z8000 (newer releases will likely not support some of these). GDB has compiled-in simulators for even lesser-known target processors such like M32R or V850.[7]
Stepping through code
[edit ]Both the next n and step n command can be used to advance execution over the next n statements. If n is omitted it defaults to 1. The difference between the commands is that step will follow the flow of execution into the internals of any function call whereas next will execute the whole function and proceed to the next statement within the current routine.[8]
The jump location command is used either to skip over a section of problematic code or go back to a previous statement in order to review execution again. The location should be in the same function.[9]
Printing Values and Expressions
[edit ]When a program is halted in mid execution the print (abbreviated as p) command can be used to display the value of a variable or an expression using C or C++ syntax. The x command (meaning "examine") is similar but it's argument is an address in memory including address expressions. Both commands use flags to indicate presentation format of the output though there are some differences as x allows one to specify the number of bytes.
e.g.:
print /f myVar #Prints a double precision floating point number x /8bx &foo #Print 8 bytes in hex format starting at the memory location of foo
Additionally the call command invokes both library and user written functions and the returned value will be displayed.[10]
Values displayed are automatically assigned to special value history variables which begin with a $ sign followed by a sequence number which can then be redisplayed using print.[10] : 547 [11]
i.e.:
call getpid() 1ドル = 23995
One can also use the set command to create convenience variables for use during a gdb session.[12]
e.g.:
set $foo=i+42
If the argument of print is an array or struct all elements will be output. The following syntax can be used to show a sub range of the array:
i.e.:
print myArray[10]@10 #show 10 elements of the array starting at myArray[4][10] : 546
Breakpoints and Watchpoints
[edit ]Breakpoints and watchpoints are used when one needs to examine a program prior to a known situation where things are likely to go wrong. Both break and watchpoints issued integer identification numbers, 1, 2, 3... which can be used to enable, disable or delete them. The command info break|watch displays all breakpoints and their current status.
Breakpoints are set to halt the flow of execution either on specific line numbers in one's code or on entry to a function when run within the debugger i.e.: break sourcefile:42 will stop on line 42 of the specified file. It the file name is omitted the reference is to the current file.
A conditional breakpoint halts on a specified line when a specified expression is true, i.e.:
break sourcefile:275 if productNum=1275
The condition breakNum expression command allows one to add conditions to an established breakpoint.[13]
Watchpoints halt the flow of execution when the value of a variable or an expression changes, irrespective of where in the program it occurs. By default, where possible, gdb monitors the memory location where the change takes place, a useful feature given that multiple pointers may refer to the same address. Conversely a software watchpoint, which are slower, track just the variables.
The rwatch and awatch commands will halt the program whenever the memory location or variable is read.[14]
Another conditional feature of both watches and breakpoints is the command ignore breakNum count which disregards the halting criteria until count execution passes.[15]
The display command primes gdb to automatically out the value of an expression each time it stops. Multiple display commands are cumulative and the output can be formatted using the same flags available to the x command.[10] : 551–552
Framestacks
[edit ]When a program is halted it may be several layers deep in function calls. Each level of function call is called a frame and the collection of frames is called a frame stack. When execution is halted one can navigate either up or down to a specific frame in order to examine the value of variables or expressions at a particular level which is useful to assist debugging programs. The backtrace command will provide a list of all of the frames in the stack. The info args command displays all of the arguments passed to the current frame and the info local command displays a list of the variables available to it along with their values. [16]
Scripting Support
[edit ]GDB includes the ability to define command routines that can be used to automate frequently repeated sets of gdb instructions. These consisting of gdb commands placed between define and end statements. Parameters to these routines are not declared by name however they are passed in special variables $arg1, $arg2, $arg3... with special variable $argc representing the # of command line arguments.
Additionally gdb includes if/else and while blocks terminated by end statements as well as loop_break and loop_continue statements to manage flow of control.[17]
e.g.:
#Script to set the gdb prompt and set a breakpoint definecmd setprompt"My debugger> " setprintpretty#display structures on multiple lines if$argc==0 print"There are no arguments to the command" else break$arg0 end end
Consider that one is debugging a C program with a generic linked list a leading value and next field pointing to the next element, the following command would use a while loop to display all the elements:[18]
definep_generic_list setvar$n=$arg0 while$n print*($n) setvar$n=$n->next end end
Command definitions placed in the local file .gdbinit are automatically loaded at the beginning of the gdb session. Command definitions can also be saved in ordinary files and loaded using the source command.
As of version 7.0 new features include support for Python scripting[19] and as of version 7.8 GNU Guile scripting as well which is based on the Scheme (programming language).[20]
Reversible Debugging
[edit ]Since version 7.0, support for "reversible debugging" — allowing a debugging session to step backward, much like rewinding a crashed program to see what happened — is available. The feature is highly memory intensive and slows execution with a default limit of 20,000 instructions. The recommended procedure is to set breakpoints before and after the suspected problem, then issue the record command when the program stops at first one. Continue execution to the 2nd breakpoint. The reverse-step, reverse-next and reverse-continue commands can then be used to backtrack execution, undoing changes in variables piecemeal, However reverse debugging does not undo actions such as console output nor does it reissue external events such as interrupts or incoming network packets.[13] : 80-82 [21]
Remote debugging
[edit ]GDB offers a "remote" mode often used when debugging embedded systems. Remote operation is when GDB runs on one machine and the program being debugged runs on another. GDB can communicate to the remote "stub" that understands GDB protocol through a serial device or TCP/IP.[22] A stub program can be created by linking to the appropriate stub files provided with GDB, which implement the target side of the communication protocol.[23] Alternatively, gdbserver can be used to remotely debug the program without needing to change it in any way.
The same mode is also used by KGDB for debugging a running Linux kernel on the source level with gdb. With KGDB, kernel developers can debug a kernel in much the same way as they debug application programs. It makes it possible to place breakpoints in kernel code, step through the code, and observe variables. On architectures where hardware debugging registers are available, watchpoints can be set which trigger breakpoints when specified memory addresses are executed or accessed. KGDB requires an additional machine which is connected to the machine to be debugged using a serial cable or Ethernet. On FreeBSD, it is also possible to debug using FireWire direct memory access (DMA).[24]
Graphical user interface
[edit ]The debugger does not contain its own graphical user interface, and defaults to a command-line interface, although it does contain a text user interface. Several front-ends have been built for it, such as UltraGDB, Xxgdb, Data Display Debugger (DDD), Nemiver, KDbg, the Xcode debugger, GDBtk/Insight, Gede,[25] Seer,[26] and HP Wildebeest Debugger GUI (WDB GUI). IDEs such as Codelite, Code::Blocks, Dev-C++, Geany, GNAT Programming Studio (GPS), KDevelop, Qt Creator, Lazarus, MonoDevelop, Eclipse, NetBeans, and Visual Studio can interface with GDB. GNU Emacs has a "GUD mode" and tools for Vim exist (e.g. clewn). These offer facilities similar to debuggers found in IDEs.
Some other debugging tools have been designed to work with GDB, such as memory leak detectors.
Internals
[edit ]GDB uses a system call named ptrace (the name is an abbreviation of "process trace") to observe and control the execution of another process, and examine and change the process's memory and registers.
| Common gdb commands | Corresponding ptrace calls |
|---|---|
(gdb) start | PTRACE_TRACEME – makes parent a tracer (called by a tracee) |
(gdb) attach PID | PTRACE_ATTACH – attach to a running process |
(gdb) step | PTRACE_SINGLESTEP – advance to the next instruction |
(gdb) stop | kill(child_pid, SIGSTOP) (or PTRACE_INTERRUPT) |
(gdb) continue | PTRACE_CONT |
(gdb) info registers | PTRACE_GET(FP)REGS(ET) and PTRACE_SET(FP)REGS(ET) |
(gdb) x | PTRACE_PEEKTEXT and PTRACE_POKETEXT |
A breakpoint is implemented by replacing an instruction at a given memory address with another special instruction. Executing breakpoint instruction causes SIGTRAP.
Examples of commands
[edit ]$ gdbprogram
|
Debug "program" (from the shell) |
|---|---|
(gdb) run -v
|
Run the loaded program with the parameters |
(gdb) bt
|
Backtrace (in case the program crashed) |
(gdb) info registers
|
Dump all registers |
(gdb) disas $pc-32, $pc+32
|
Disassemble |
An example session
[edit ]Consider the following source-code written in C:
#include<stdio.h> #include<stdlib.h> #include<string.h> size_tfoo_len(constchar*s) { returnstrlen(s); } intmain(intargc,char*argv[]) { constchar*a=NULL; printf("size of a = %lu\n",foo_len(a)); exit(0); }
Using the GCC compiler on Linux, the code above must be compiled using the -g flag in order to include appropriate debug information on the binary generated, thus making it possible to inspect it using GDB. Assuming that the file containing the code above is named example.c, the command for the compilation could be:
$ gccexample.c-Og-g-oexample
And the binary can now be run:
$ ./example Segmentation fault
Since the example code, when executed, generates a segmentation fault, GDB can be used to inspect the problem.
$ gdb./example GNU gdb (GDB) Fedora (7.3.50.20110722-13.fc16) Copyright (C) 2011 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html> 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 "x86_64-redhat-linux-gnu". For bug reporting instructions, please see: <https://www.gnu.org/software/gdb/bugs/>... Reading symbols from /path/example...done. (gdb) run Starting program: /path/example Program received signal SIGSEGV, Segmentation fault. 0x0000000000400527 in foo_len (s=0x0) at example.c:7 7 return strlen (s); (gdb) print s $1=0x0
The problem is present in line 7, and occurs when calling the function strlen (because its argument, s, is NULL ). Depending on the implementation of strlen (inline or not), the output can be different, e.g.:
GNU gdb (GDB) 7.3.1 Copyright (C) 2011 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html> 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-pc-linux-gnu". For bug reporting instructions, please see: <https://www.gnu.org/software/gdb/bugs/>... Reading symbols from /tmp/gdb/example...done. (gdb) run Starting program: /tmp/gdb/example Program received signal SIGSEGV, Segmentation fault. 0xb7ee94f3 in strlen () from /lib/i686/cmov/libc.so.6 (gdb) bt #00xb7ee94f3instrlen()from/lib/i686/cmov/libc.so.6 #10x08048435infoo_len(s=0x0)atexample.c:7 #20x0804845ainmain(argc=<optimizedout>,argv=<optimizedout>)atexample.c:14
To fix the problem, the variable a (in the function main) must contain a valid string. Here is a fixed version of the code:
#include<stdio.h> #include<stdlib.h> #include<string.h> size_tfoo_len(constchar*s) { returnstrlen(s); } intmain(intargc,char*argv[]) { constchar*a="This is a test string"; printf("size of a = %lu\n",foo_len(a)); exit(0); }
Recompiling and running the executable again inside GDB now gives a correct result:
$ gdb./example GNU gdb (GDB) Fedora (7.3.50.20110722-13.fc16) Copyright (C) 2011 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html> 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 "x86_64-redhat-linux-gnu". For bug reporting instructions, please see: <https://www.gnu.org/software/gdb/bugs/>... Reading symbols from /path/example...done. (gdb) run Starting program: /path/example size of a = 21 [Inferior 1 (process 14290) exited normally]
GDB prints the output of printf in the screen, and then informs the user that the program exited normally.
See also
[edit ]References
[edit ]- ^ Joël Brobecker (20 April 2025). "GDB 16.3 released!" . Retrieved 20 April 2025.
- ^ "GDB Documentation - Supported Languages". sourceware.org. Archived from the original on 2017年12月28日. Retrieved 2025年06月16日.
- ^ "GDB Documentation - Summary". sourceware.org. Archived from the original on 2012年07月01日. Retrieved 2025年06月16日.
- ^ a b "Richard Stallman lecture at the Royal Institute of Technology, Sweden (1986年10月30日)" . Retrieved 2006年09月21日.
Then after GNU Emacs was reasonably stable, which took all in all about a year and a half, I started getting back to other parts of the system. I developed a debugger which I called GDB which is a symbolic debugger for C code, which recently entered distribution. Now this debugger is to a large extent in the spirit of DBX, which is a debugger that comes with Berkeley Unix.
- ^ "John Gilmore (activist)". hyperleap.com. Archived from the original on 2021年02月26日. Retrieved 2020年10月13日.
- ^ "GDB Steering Committee" . Retrieved 2008年05月11日.
- ^ "GDB Documentation - Summary - Contributors". Archived from the original on 2011年09月29日. Retrieved 2011年12月01日.
- ^ "Continuing and Stepping". Free Software Foundation. 2025. Retrieved June 22, 2025.
- ^ "Continuing at a Different Address". Free Software Foundation. 2025. Retrieved June 22, 2025.
- ^ a b c d Fusco, John (2007). The Linux Programmer's Toolbox. Prentice Hall. pp. 542–547. ISBN 978-0-13-219857-8.
- ^ "Convenience vars". Free Software Foundation Inc. 2025. Retrieved Sep 25, 2025.
- ^ Keren, Guy (Apr 4, 2009). "Convenience Variables" . Retrieved Sep 25, 2025.
- ^ a b Diomidis, Spinellis (2017). Effective Debugging. Pearson Education. pp. 77–79. ISBN 978-0-13-439479-4.
- ^ "Setting Watchpoints". 2025. Retrieved June 29, 2025.
- ^ "Break Conditions". 2025. Retrieved June 29, 2025.
- ^ "Debugging with GDB - Examining the Stack". web.mit.edu. Retrieved 2025年11月10日.
- ^ "Command Files". sourceware.org. Retrieved Oct 7, 2025.
- ^ Shriraman, Arrvindh; Whiller, Liz (Oct 7, 2025). "Debugging Linked Lists" . Retrieved Oct 7, 2025.
- ^ "GDB 7.0 Release Notes" . Retrieved 2011年11月28日.
- ^ Joel Brobecker (2014年07月29日). "GDB 7.8 released!" . Retrieved 2014年07月30日.
- ^ "Reverse Debugging with GDB" . Retrieved 2014年01月20日.
- ^ "Howto: GDB Remote Serial Protocol: Writing a RSP Server" (PDF).
- ^ "Implementing a remote stub".
- ^ "Kernel debugging with Dcons".
- ^ "Gede official website" . Retrieved 2025年06月07日.
- ^ "Seer - a gui frontend to gdb". Github repository of Seer.
- ^ O'Neill, Ryan (Feb 29, 2016). "3". Learning Linux Binary Analysis. Packt Publishing. ISBN 978-1-78216-710-5.
External links
[edit ]- Official website , official GDB Git repository
- UltraGDB: Visual C/C++ Debugging with GDB on Windows and Linux Archived 2017年12月12日 at the Wayback Machine
- The website for "MyGDB: GDB Frontend" in the Korean language
- A Visual Studio plugin for debugging with GDB
Documentation
[edit ]- Richard M. Stallman, Roland Pesch, Stan Shebs, et al., Debugging with GDB (Free Software Foundation, 2011) ISBN 978-0-9831592-3-0
- GDB Internals
Tutorials
[edit ]- RMS's gdb Tutorial (Ryan Michael Schmidt, not Richard Matthew Stallman)
- GDB Tutorial
- Using Eclipse as a Front-End to the GDB Debugger