Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

GNU Debugger

From Wikipedia, the free encyclopedia
Source-level debugger
"GDB" redirects here. For other uses, seeGDB (disambiguation).
GNU Debugger
DeveloperGNU Project
Initial release1986; 40 years ago (1986)
Stable release
17.1[1] Edit this on Wikidata / 19 December 2025
Written inC,C++,Python
Operating systemUnix-like,Windows
TypeDebugger
LicenseGPLv3
Websitewww.gnu.org/software/gdb
Repository

TheGNU Debugger (GDB) is aportabledebugger that runs on manyUnix-like systems and works for manyprogramming languages, includingAda,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 program variables and machine registers.

History

[edit]

GDB was first written byRichard Stallman in 1986 as part of hisGNU system, after hisGNU Emacs was "reasonably stable".[4] GDB isfree software released under theGNU General Public License (GPL). It was modeled after theDBX debugger, which came withBerkeley Unix distributions.[4]

From 1990 to 1993 it was maintained byJohn Gilmore.[5] Now it is maintained by the GDB Steering Committee which is appointed by theFree Software Foundation.[6]

Technical features

[edit]

GDB offers extensive facilities for tracing, examining and altering the execution ofcomputer programs. The user can monitor and modify the values of programs' internalvariables, and even callfunctions independently of the program's normal behavior.

Supported platforms

[edit]

GDB target processors (as of 2003[update])[needs update] include:Alpha,ARM,AVR,H8/300, AlteraNios/Nios II,System/370,System/390,x86 (32-bit and64-bit),IA-64 "Itanium",Motorola 68k,MIPS,PA-RISC,PowerPC,RISC-V,SuperH,SPARC, andVAX. Lesser-known target processors supported in the standard release have includedA29K,ARC,ETRAX CRIS, D10V, D30V, FR-30,FR-V,Intel i960,68HC11,Motorola 88000,MCORE, MN10200,MN10300,NS32k, Stormy16, andZ8000 (newer releases will likely not support some of these).

GDB has compiled-insimulators for most targets.[7]

Stepping through code

[edit]

Both thenextn andstepn command can be used to advance execution over the next n statements. Ifn is omitted it defaults to 1. The difference between the commands is thatstep will follow the flow of execution into the internals of any function call whereasnext will execute the whole function and proceed to the next statement within the current routine.[8]

Thejumplocation 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 specified location may correspond to different parts of the executing program, but unexpected results may occur for those not accustomed tomachine code.[9]

Printing values and expressions

[edit]

When a program is halted in mid execution theprint (abbreviated asp) command can be used to display the value of a variable or an expression using C or C++ syntax. Thex 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 asx 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 thecall command invokes both library and user written functions and the returned value will be displayed.[10]

Values displayed are automatically assigned to specialvalue history variables which begin with a $ sign followed by a sequence number which can then be redisplayed usingprint.[10]: 547 [11]

i.e.:

  call getpid()  $1  = 23995

One can also use theset command to createconvenience variables for use during a gdb session.[12]

e.g.:

  set $foo=i+42

If the argument ofprint 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 toenable,disable ordelete them. The commandinfo 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.:breaksourcefile: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.:

breaksourcefile:275if productNum=1275

TheconditionbreakNumexpression 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.

Therwatch andawatch commands will halt the program whenever the memory location or variable is read.[14]

Another conditional feature of both watches and breakpoints is the commandignorebreakNumcount which disregards the halting criteria until count execution passes.[15]

Thedisplay command primes gdb to automatically out the value of an expression each time it stops. Multipledisplay commands are cumulative and the output can be formatted using the same flags available to thex 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. Thebacktrace command will provide a list of all of the frames in the stack. Theinfo args command displays all of the arguments passed to the current frame and theinfo 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 betweendefine andend 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 includesif/else andwhile blocks terminated byend statements as well asloop_break andloop_continue statements to manage flow of control.[17]

e.g.:

#Script to set the gdb prompt and set a breakpointdefinecmdsetprompt"My debugger> "setprintpretty#display structures on multiple linesif$argc==0print"There are no arguments to the command"elsebreak$arg0endend

Consider that one is debugging a C program with a generic linked list a leading value andnext field pointing to the next element, the following command would use awhile loop to display all the elements:[18]

definep_generic_listsetvar$n=$arg0while$nprint*($n)setvar$n=$n->nextendend

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 thesource command.

As of version 7.0 new features include support forPython scripting[19] and as of version 7.8GNU Guile scripting as well which is based on theScheme (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 therecord command when the program stops at first one. Continue execution to the 2nd breakpoint. Thereverse-step,reverse-next andreverse-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 byKGDB for debugging a runningLinux 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 placebreakpoints 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 aserial cable orEthernet. OnFreeBSD, it is also possible to debug usingFireWiredirect memory access (DMA).[24]

Graphical user interface

[edit]

The debugger does not contain its owngraphical user interface, and defaults to acommand-line interface, although it does contain atext user interface. Several front-ends have been built for it, such as UltraGDB, Xxgdb,Data Display Debugger (DDD), Nemiver, KDbg, theXcode debugger, GDBtk/Insight, Gede,[25] Seer,[26] and HP Wildebeest Debugger GUI (WDB GUI).IDEs such asCodelite,Code::Blocks,Dev-C++,Geany, GNAT Programming Studio (GPS),KDevelop,Qt Creator,Lazarus,MonoDevelop,Eclipse,NetBeans, andVisual Studio can interface with GDB.GNU Emacs has a "GUD mode" and tools forVim 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 asmemory leak detectors.

Internals

[edit]

GDB uses a system call namedptrace (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)startPTRACE_TRACEME – makes parent a tracer (called by a tracee)
(gdb)attach PIDPTRACE_ATTACH – attach to a running process
(gdb)stepPTRACE_SINGLESTEP – advance to the next instruction
(gdb)stopkill(child_pid, SIGSTOP) (orPTRACE_INTERRUPT)
(gdb)continuePTRACE_CONT
(gdb)info registersPTRACE_GET(FP)REGS(ET) andPTRACE_SET(FP)REGS(ET)
(gdb)xPTRACE_PEEKTEXT andPTRACE_POKETEXT

[27]

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]
$gdbprogramDebug "program" (from the shell)
(gdb)run -vRun the loaded program with the parameters
(gdb)btBacktrace (in case the program crashed)
(gdb)info registersDump all registers
(gdb)disas $pc-32, $pc+32Disassemble

An example session

[edit]

Consider the following source-code written inC:

#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 theGCC compiler onLinux, 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 namedexample.c, the command for thecompilation could be:

$gccexample.c-Og-g-oexample

And the binary can now be run:

$./exampleSegmentation fault

Since the example code, when executed, generates asegmentation fault, GDB can be used to inspect the problem.

$gdb./exampleGNU 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)runStarting program: /path/exampleProgram received signal SIGSEGV, Segmentation fault.0x0000000000400527 in foo_len (s=0x0) at example.c:77  return strlen (s);(gdb)print s$1=0x0

The problem is present in line 7, and occurs when calling the functionstrlen (because its argument,s, isNULL). Depending on the implementation of strlen (inline or not), the output can be different, e.g.:

GNU gdb (GDB) 7.3.1Copyright (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)runStarting program: /tmp/gdb/exampleProgram 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 variablea (in the functionmain) 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./exampleGNU 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)runStarting program: /path/examplesize of a = 21[Inferior 1 (process 14290) exited normally]

GDB prints the output ofprintf in the screen, and then informs the user that the program exited normally.

See also

[edit]

References

[edit]
  1. ^Joël Brobecker (20 December 2025)."GDB 17.1 released!". Retrieved20 December 2025.
  2. ^"GDB Documentation - Supported Languages".sourceware.org.Archived from the original on 2017-12-28. Retrieved2025-06-16.
  3. ^"GDB Documentation - Summary".sourceware.org.Archived from the original on 2012-07-01. Retrieved2025-06-16.
  4. ^ab"Richard Stallman lecture at the Royal Institute of Technology, Sweden (1986-10-30)". Retrieved2006-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.
  5. ^"John Gilmore (activist)".hyperleap.com. Archived fromthe original on 2021-02-26. Retrieved2020-10-13.
  6. ^"GDB Steering Committee". Retrieved2008-05-11.
  7. ^"19.2 Commands for Managing Targets".Debugging with GDB. Free Software Foundation, Inc. 2026. Retrieved2026-01-07.GDB includes simulators for most architectures.
  8. ^"Continuing and Stepping". Free Software Foundation. 2025. RetrievedJune 22, 2025.
  9. ^"Continuing at a Different Address". Free Software Foundation. 2025. RetrievedJune 22, 2025.
  10. ^abcdFusco, John (2007).The Linux Programmer's Toolbox. Prentice Hall. pp. 542–547.ISBN 978-0-13-219857-8.
  11. ^"Convenience vars". Free Software Foundation Inc. 2025. RetrievedSep 25, 2025.
  12. ^Keren, Guy (Apr 4, 2009)."Convenience Variables". RetrievedSep 25, 2025.
  13. ^abDiomidis, Spinellis (2017).Effective Debugging. Pearson Education. pp. 77–79.ISBN 978-0-13-439479-4.
  14. ^"Setting Watchpoints". 2025. RetrievedJune 29, 2025.
  15. ^"Break Conditions". 2025. RetrievedJune 29, 2025.
  16. ^"Debugging with GDB - Examining the Stack".web.mit.edu. Retrieved2025-11-10.
  17. ^"Command Files".sourceware.org. RetrievedOct 7, 2025.
  18. ^Shriraman, Arrvindh; Whiller, Liz (Oct 7, 2025)."Debugging Linked Lists". RetrievedOct 7, 2025.
  19. ^"GDB 7.0 Release Notes". Retrieved2011-11-28.
  20. ^Joel Brobecker (2014-07-29)."GDB 7.8 released!". Retrieved2014-07-30.
  21. ^"Reverse Debugging with GDB". Retrieved2014-01-20.
  22. ^"Howto: GDB Remote Serial Protocol: Writing a RSP Server"(PDF).
  23. ^"Implementing a remote stub".
  24. ^"Kernel debugging with Dcons".
  25. ^"Gede official website". Retrieved2025-06-07.
  26. ^"Seer - a gui frontend to gdb".Github repository of Seer.
  27. ^O'Neill, Ryan (Feb 29, 2016). "3".Learning Linux Binary Analysis. Packt Publishing.ISBN 978-1-78216-710-5.

External links

[edit]

Documentation

[edit]

Tutorials

[edit]
History
Licenses
Software
Contributors
Other topics
Authority control databasesEdit this at Wikidata
Retrieved from "https://en.wikipedia.org/w/index.php?title=GNU_Debugger&oldid=1337212489"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2026 Movatter.jp