HP 5992-4701 User Manual

Page 1

Debugging with GDB Manual

The GNU Source-Level Debugger
HP Part Number: 5992-4701 Published: February 2009 Edition: 19
Page 2
© Copyright 2009 Hewlett-Packard Development Company, L.P.
Confidential computer software. Valid license from HP required for possession, use or copying. Consistent with FAR 12.211 and
12.212, Commercial Computer Software, Computer Software Documentation, and Technical Data for Commercial Items are
The information contained herein is subject to change without notice. The only warranties for HP products and services are set
forth in the express warranty statements accompanying such products and services. Nothing herein should be construed as
constituting an additional warranty. HP shall not be liable for technical or editorial errors or omissions contained herein.
UNIX is a registered trademark of The Open Group.
Java is a registered trademark of Sun Microsystems, Inc.
Page 3

Table of Contents

Summary of GDB........................................................................................................................15
Free Software......................................................................................................................15
Contributors to GDB...........................................................................................................15
1 A Sample GDB Session.............................................................................................................19
1.1 Loading the Executable.................................................................................................19
1.2 Setting Display width....................................................................................................20
1.3 Setting Breakpoints.......................................................................................................20
1.4 Running the executable under GDB.............................................................................20
1.5 Stepping to the next line in the source program...........................................................20
1.6 Stepping into a subroutine............................................................................................21
1.7 Examining the Stack......................................................................................................21
1.8 Printing Variable Values................................................................................................21
1.9 Listing Source Code......................................................................................................22
1.10 Setting Variable Values During a Session....................................................................22
2 Getting In and Out of GDB.......................................................................................................25
2.1 Invoking GDB................................................................................................................25
2.1.1 Choosing files........................................................................................................26
2.1.2 Choosing modes....................................................................................................27
2.1.3 Redirecting WDB input and output to a file.........................................................30
2.2 Quitting GDB................................................................................................................30
2.3 Shell commands............................................................................................................31
3 GDB Commands......................................................................................................................33
3.1 Command syntax..........................................................................................................33
3.2 Command completion...................................................................................................33
3.3 Getting help...................................................................................................................35
4 Running Programs Under GDB...................................................................................................39
4.1 Compiling for debugging..............................................................................................39
4.2 Starting your program..................................................................................................39
4.3 Arguments To Your Program........................................................................................41
4.4 Program Environment..................................................................................................41
4.5 Working directory.........................................................................................................43
4.6 Program Input and Output...........................................................................................43
4.7 Debugging a Running Process......................................................................................44
4.8 Killing the child process................................................................................................45
Table of Contents 3
Page 4
4.9 Debugging programs with multiple threads................................................................46
4.10 Debugging programs with multiple processes...........................................................49
5 Stopping and Continuing..........................................................................................................51
5.1 Breakpoints....................................................................................................................51
5.1.1 Setting breakpoints...............................................................................................52
5.1.2 Setting catchpoints................................................................................................56
5.1.3 Deleting breakpoints.............................................................................................58
5.1.4 Disabling breakpoints...........................................................................................58
5.1.5 Break conditions....................................................................................................59
5.1.6 Breakpoint command lists....................................................................................61
5.1.7 Breakpoint menus.................................................................................................62
5.1.8 “Cannot insert breakpoints”.................................................................................63
5.2 Continuing and stepping..............................................................................................64
5.3 Signals...........................................................................................................................67
5.4 Stopping and starting multi-thread programs..............................................................69
6 Examining the Stack.................................................................................................................71
6.1 Stack frames..................................................................................................................71
6.2 Stacks Without frames...................................................................................................72
6.3 Commands for Examining the Stack.............................................................................72
6.4 Backtraces......................................................................................................................72
6.5 Selecting a frame...........................................................................................................73
6.6 Information about a frame............................................................................................74
7 Examining Source Files.............................................................................................................77
7.1 Printing source lines......................................................................................................77
7.2 Searching source files....................................................................................................78
7.3 Specifying source directories........................................................................................79
7.4 Source and machine code..............................................................................................80
8 Examining Data.......................................................................................................................83
8.1 Expressions....................................................................................................................83
8.2 Program variables.........................................................................................................84
8.3 Artificial arrays.............................................................................................................85
8.4 Output formats..............................................................................................................86
8.5 Examining memory.......................................................................................................87
8.6 Automatic display.........................................................................................................89
8.7 Print settings..................................................................................................................90
8.8 Value history.................................................................................................................95
8.9 Convenience variables...................................................................................................96
8.10 Registers......................................................................................................................98
4 Table of Contents
Page 5
8.11 Printing Floating Point Values....................................................................................99
8.12 Floating point hardware..............................................................................................99
9 Using GDB with Different Languages........................................................................................101
9.1 Switching between source languages..........................................................................101
9.1.1 List of filename extensions and languages.........................................................101
9.1.2 Setting the working language.............................................................................102
9.1.3 Having GDB infer the source language..............................................................102
9.2 Displaying the language..............................................................................................103
9.3 Type and range checking.............................................................................................103
9.3.1 An overview of type checking............................................................................103
9.3.2 An overview of range checking..........................................................................104
9.4 Supported languages...................................................................................................105
9.4.1 C and C++............................................................................................................106
9.4.1.1 C and C++ operators....................................................................................106
9.4.1.2 C and C++ constants....................................................................................108
9.4.1.3 C++ expressions...........................................................................................109
9.4.1.4 C and C++ defaults......................................................................................110
9.4.1.5 C and C++ type and range checks...............................................................110
9.4.1.6 GDB and C..................................................................................................111
9.4.1.7 GDB features for C++..................................................................................111
9.4.2 Fortran.................................................................................................................112
9.4.2.1 Fortran types...............................................................................................112
9.4.2.2 Fortran operators.........................................................................................113
9.4.2.3 Fortran special issues..................................................................................114
10 Examining the Symbol Table..................................................................................................115
11 Altering Execution.................................................................................................................119
11.1 Assignment to variables............................................................................................119
11.2 Continuing at a different address..............................................................................120
11.3 Giving your program a signal...................................................................................121
11.4 Returning from a function.........................................................................................121
11.5 Calling program functions........................................................................................122
11.6 Patching programs.....................................................................................................122
12 GDB Files.............................................................................................................................125
12.1 Commands to specify files........................................................................................125
12.2 Specifying shared library locations...........................................................................130
12.3 Errors reading symbol files.......................................................................................131
Table of Contents 5
Page 6
13 Specifying a Debugging Target..............................................................................................133
13.1 Active targets.............................................................................................................133
13.2 Commands for managing targets..............................................................................133
13.3 Choosing target byte order........................................................................................135
14 HP-UX Configuration-Specific Information.................................................................................137
14.1 Summary of HP Enhancements to GDB....................................................................137
14.2 HP-UX dependencies................................................................................................140
14.2.1 Linker Dependencies.........................................................................................140
14.2.2 Dependent Standard Library Routines for Run Time Checking......................140
14.3 Supported Platforms and Modes..............................................................................142
14.4 HP-UX targets............................................................................................................143
14.5 Support for Alternate root.........................................................................................143
14.6 Specifying object file directories................................................................................144
14.7 Fix and continue debugging......................................................................................145
14.7.1 Fix and Continue compiler dependencies.........................................................146
14.7.2 Fix and Continue restrictions............................................................................146
14.7.3 Using Fix and Continue.....................................................................................147
14.7.4 Example Fix and Continue session...................................................................148
14.8 Inline Support............................................................................................................150
14.8.1 Inline Debugging in HP 9000 Systems..............................................................150
14.8.2 Inline Debugging in Integrity Systems.............................................................151
14.8.2.1 Debugging Inline Functions in Integrity Systems.....................................152
14.9 Debugging Macros....................................................................................................153
14.9.1 Viewing and Evaluating Macro Definitions......................................................153
14.9.1.1 Compiler Options to Enable Macro Debugging.......................................154
14.9.2 Examples for Macro Debugging........................................................................155
14.10 Debugging Memory Problems................................................................................157
14.10.1 When to suspect a memory leak......................................................................158
14.10.2 Memory debugging restrictions......................................................................158
14.10.3 Memory Debugging Methodologies...............................................................158
14.10.4 Debugging Memory in Interactive Mode........................................................159
14.10.4.1 Commands for interactive memory debugging......................................159
14.10.4.2 Example for interactive debugging session.............................................163
14.10.5 Debugging Memory in Batch Mode................................................................164
14.10.5.1 Setting Configuration Options for Batch Mode......................................164
14.10.5.2 Environment variable setting for Batch mode debugging......................167
14.10.5.3 Example for Batch Mode RTC.................................................................169
14.10.6 Debugging Memory Interactively After Attaching to a Running Process......171
14.10.7 Configuring memory debugging settings.......................................................173
14.10.7.1 Specifying the stack depth.......................................................................173
14.10.7.2 Specifying minimum leak size................................................................173
14.10.7.3 Specifying minimum block size..............................................................174
6 Table of Contents
Page 7
14.10.8 Scenarios in memory debugging.....................................................................174
14.10.8.1 Stop when freeing unallocated or deallocated blocks.............................174
14.10.8.2 Stop when freeing a block if bad writes occurred outside block
boundary................................................................................................................174
14.10.8.3 Stop when a specified block address is allocated or deallocated............175
14.10.8.4 Scramble previous memory contents at malloc/free calls.......................175
14.10.8.5 Detect dangling pointers and dangling blocks.......................................175
14.10.8.6 Detect in-block corruption of freed blocks..............................................176
14.10.8.7 Specify the amount of guard bytes for every block of allocated
memory..................................................................................................................176
14.10.9 Comparison of Memory Debugging Commands in Interactive Mode and
Batch Mode..................................................................................................................176
14.10.10 Heap Profiling................................................................................................178
14.10.10.1 Commands for heap profiling...............................................................178
14.10.10.2 info heap arena...............................................................................179
14.10.10.3 info heap arena [0 |1|2|..] blocks stacks..............................179
14.10.10.4 info module ADDRESS.....................................................................179
14.10.10.5 info heap process..........................................................................179
14.10.10.6 Example for heap profiling....................................................................179
14.10.11 Memory Checking Analysis for User Defined Memory Management
Routines.......................................................................................................................180
14.10.12 Commands to track the change in data segment value.................................180
14.11 Thread Debugging Support.....................................................................................181
14.11.1 Support for Enabling and Disabling Specific Threads....................................181
14.11.2 Backtrace Support for Thread Debugging.......................................................182
14.11.3 Advanced Thread Debugging Support...........................................................182
14.11.3.1 Pre-requisites for Advanced Thread Debugging....................................183
14.11.3.2 Enabling and Disabling Advanced Thread Debugging Features...........183
14.11.3.3 Commands to view information on pthread primitives.........................187
14.11.4 Debugging Threads Interactively After Attaching to a Process......................187
14.11.5 Thread Debugging in Batch Mode..................................................................189
14.11.5.1 Pre-requisites for Batch mode of Thread Debugging..............................190
14.11.5.2 Limitations in Batch mode of thread debugging....................................193
14.11.6 Thread Debugging in +check Mode..............................................................193
14.11.7 Known issues with Thread Debugging for Interactive and Batch mode........194
14.12 Debugging MPI Programs.......................................................................................194
14.13 Debugging multiple processes ( programs with fork and vfork calls)...............195
14.13.1 Ask mode for set follow-fork-mode......................................................195
14.13.2 Serial mode for set follow-fork-mode....................................................195
14.13.3 Support for showing unwind info...................................................................195
14.13.4 Printing CFM and PFS registers......................................................................196
14.14 Command to Search for a Pattern in the Memory Address Space..........................196
14.15 Debugging Core Files..............................................................................................200
14.15.1 Generating core files with packcore /unpackcore/getcore....................200
Table of Contents 7
Page 8
14.15.2 Support for the info target Command.....................................................201
14.15.3 Support for the dumpcore command.............................................................202
14.15.3.1 Enhancements to the dumpcore command............................................202
14.15.4 Support for display of run time type information..........................................203
14.16 Printing the Execution Path Entries for the Current Frame or Thread...................203
14.16.1 Compiler Dependencies for Printing the Execution Path Entries...................204
14.16.2 Example Illustrating Execution Path Recovery...............................................205
14.17 Command to Unwind Beyond 10000 Frames..........................................................206
14.18 Invoking GDB Before a Program Aborts.................................................................207
14.19 Aborting a Command Line Call..............................................................................207
14.20 Instruction Level Stepping.......................................................................................208
14.21 Enhanced support for watchpoints and breakpoints..............................................208
14.21.1 Deferred watchpoints......................................................................................208
14.21.2 Hardware watchpoints....................................................................................208
14.21.3 Hardware breakpoints.....................................................................................208
14.21.3.1 Setting breakpoints in unstripped shared library...................................209
14.21.4 Support for procedural breakpoints................................................................209
14.21.5 Support for template breakpoints...................................................................209
14.22 Debugging support for shared libraries..................................................................210
14.22.1 Using shared library as main program...........................................................210
14.22.2 Setting Deferred Breakpoints in Shared Library.............................................211
14.22.3 Using catch load..............................................................................................211
14.22.4 Privately mapping shared libraries.................................................................211
14.22.5 Selectively Mapping Shared Libraries As Private...........................................212
14.22.6 Setting breakpoints in shared library..............................................................213
14.22.7 Enhancement to the info shared Command..............................................213
14.23 Debugging support for Decimal Floating Point data type......................................213
14.23.1 Printing Decimal Floating point data types....................................................213
14.23.1.1 Printing Decimal floating point constant................................................214
14.23.1.2 Printing Decimal floating point variable.................................................214
14.23.2 Printing NaT Registers....................................................................................214
14.23.3 Handling Decimal Floating Point Data types..................................................214
14.23.4 Evaluating Decimal Floating Point data types................................................214
14.23.4.1 Printing type of Decimal Floating Point variable....................................215
14.24 Additional Support for binary floating point data type..........................................216
14.24.1 Support for Binary Floating Point constants f, l..............................................216
14.24.2 Support Binary Floating Point variables with format specifier.......................216
14.25 Language support....................................................................................................217
14.25.1 Enhanced Java Debugging Support................................................................217
14.25.1.1 Java Stack Unwind Features....................................................................217
14.25.1.2 gdb Subcommands for Java VM Debugging...........................................218
14.25.1.3 Java corefile debugging support.............................................................220
14.25.1.4 Java attach mode debugging support.....................................................220
14.25.2 Enhanced support for C++ templates..............................................................221
8 Table of Contents
Page 9
14.25.3 Support for _ _fpreg data type on IPF.........................................................222
14.25.4 Support for _Complex variables in HP C........................................................222
14.25.5 Support for debugging namespaces................................................................222
14.25.6 Command for evaluating the address of an expression..................................223
14.26 Viewing Wide Character Strings.............................................................................223
14.27 Support for output logging......................................................................................224
14.27.1 Support for dumping array in an ASCII file...................................................224
14.27.2 Support for Fortran array slices.......................................................................225
14.27.3 Displaying enumerators..................................................................................225
14.27.4 Support for debugging typedefs.....................................................................225
14.27.5 Support for steplast command for C and C++.................................................225
14.28 Getting information from a non-debug executable.................................................226
14.29 Debugging optimized code.....................................................................................227
14.29.1 Debugging Optimized Code at Various Optimization Levels........................229
14.29.1.1 +O0 and +O1............................................................................................229
14.29.1.2 +O2/+O3/+O4/-ipo..............................................................................229
14.30 Debugging with ARIES...........................................................................................230
14.30.1 Debugging the application using GDB under ARIES.....................................231
14.30.1.1 Limitations of GDB Support under ARIES.............................................231
14.30.2 Attaching GDB to an already running emulated process...............................232
14.30.3 Detecting memory leaks using GDB under ARIES.........................................232
14.31 Visual Interface for WDB.........................................................................................233
14.31.1 Starting and stopping Visual Interface for WDB.............................................233
14.31.2 Navigating the Visual Interface for WDB display...........................................234
14.31.3 Specifying foreground and background colors...............................................235
14.31.4 Using the X-window graphical interface.........................................................235
14.31.5 Using the TUI mode........................................................................................236
14.31.6 Changing the size of the source or debugger pane.........................................236
14.31.7 Using commands to browse through source files...........................................237
14.31.8 Loading source files.........................................................................................237
14.31.9 Editing source files..........................................................................................237
14.31.10 Editing the command line and command-line history..................................237
14.31.11 Saving the contents of a debugging session to a file.....................................237
14.32 Support for ddd.......................................................................................................238
14.33 Support for XDB commands....................................................................................238
14.33.1 stop in/at dbx commands........................................................................238
14.34 GNU GDB Logging Commands..............................................................................238
14.35 Support for command line calls in a stripped executable.......................................238
14.35.1 Support for command line calls in a stripped executable on PA-RISC
systems........................................................................................................................239
14.35.2 Additional support for command line calls in a stripped executable.............239
14.35.2.1 For 32-bit applications:............................................................................239
14.35.2.2 For 64-bit applications.............................................................................240
14.35.3 Support for debugging stripped binaries........................................................240
Table of Contents 9
Page 10
14.35.3.1 Printing of locals and globals in a stripped module...............................240
14.35.3.2 Backtrace on stripped frames..................................................................240
14.35.3.3 Command line calls to non-stripped library...........................................240
14.35.3.4 Setting breakpoints in unstripped shared library...................................240
14.36 Displaying the current block scope information.....................................................241
14.37 Linux support..........................................................................................................241
15 The HP-UX Terminal User Interface..........................................................................................243
15.1 Starting the TUI.........................................................................................................243
15.2 Automatically running a program at startup............................................................244
15.3 Screen Layouts...........................................................................................................244
15.3.1 Source pane.......................................................................................................245
15.3.2 Disassembly pane..............................................................................................245
15.3.3 Source/Disassembly pane..................................................................................246
15.3.4 Disassembly/Register pane...............................................................................246
15.3.5 Source/Register pane.........................................................................................247
15.4 Cycling through the panes........................................................................................248
15.5 Changing pane focus.................................................................................................248
15.6 Scrolling panes...........................................................................................................250
15.7 Changing the register display...................................................................................250
15.8 Changing the pane size.............................................................................................251
15.9 Refreshing and updating the window......................................................................252
16 XDB to WDB Transition Guide................................................................................................253
16.1 By-function lists of XDB commands and HP WDB equivalents...............................253
16.1.1 Invocation commands.......................................................................................254
16.1.2 Window mode commands................................................................................254
16.1.3 File viewing commands....................................................................................255
16.1.4 Source directory mapping commands..............................................................256
16.1.5 Data Viewing and modification commands.....................................................256
16.1.6 Stack viewing commands..................................................................................258
16.1.7 Status-viewing command..................................................................................259
16.1.8 Job control commands.......................................................................................259
16.2 Overall breakpoint commands..................................................................................260
16.2.1 Auxiliary breakpoint commands......................................................................260
16.2.2 Breakpoint creation commands.........................................................................261
16.2.3 Breakpoint status commands............................................................................262
16.2.4 All-procedures breakpoint commands.............................................................263
16.2.5 Global breakpoint commands...........................................................................263
16.2.6 Assertion control commands.............................................................................264
16.2.7 Record and playback commands......................................................................264
16.2.8 Macro facility commands..................................................................................264
16.2.9 Signal control commands..................................................................................265
10 Table of Contents
Page 11
16.2.10 Miscellaneous commands................................................................................265
16.3 XDB data formats and HP WDB equivalents............................................................266
16.4 XDB location syntax and HP WDB equivalents........................................................268
16.5 XDB special language operators and HP WDB equivalents.....................................268
16.6 XDB special variables and HP WDB equivalents......................................................269
16.7 XDB variable identifiers and HP WDB equivalents..................................................270
16.8 Alphabetical lists of XDB commands and HP WDB equivalents..............................270
16.8.1 A........................................................................................................................270
16.8.2 B.........................................................................................................................271
16.8.3 C through D.......................................................................................................272
16.8.4 F through K........................................................................................................273
16.8.5 L.........................................................................................................................273
16.8.6 M through P.......................................................................................................274
16.8.7 Q through S.......................................................................................................275
16.8.8 T.........................................................................................................................275
16.8.9 U through Z.......................................................................................................276
16.8.10 Symbols............................................................................................................277
17 Controlling GDB...................................................................................................................281
17.1 Setting the GDB Prompt............................................................................................281
17.2 Setting Command Editing Options in GDB..............................................................281
17.3 Setting Command History Feature in GDB...............................................................281
17.4 Setting the GDB Screen Size......................................................................................283
17.5 Supported Number Formats.....................................................................................283
17.6 Optional warnings and messages..............................................................................284
17.7 Optional messages about internal happenings.........................................................285
18 Canned Sequences of Commands..........................................................................................287
18.1 User-defined commands...........................................................................................287
18.2 User-defined command hooks..................................................................................288
18.3 Command files..........................................................................................................289
18.4 Commands for controlled output..............................................................................290
19 Using GDB under gnu Emacs.................................................................................................293
20 GDB Annotations.................................................................................................................297
20.1 What is an annotation?..............................................................................................297
20.2 The server prefix........................................................................................................297
20.3 Values.........................................................................................................................298
20.4 Frames.......................................................................................................................299
20.5 Displays.....................................................................................................................301
20.6 Annotation for GDB input.........................................................................................301
Table of Contents 11
Page 12
20.7 Errors.........................................................................................................................302
20.8 Information on breakpoints.......................................................................................302
20.9 Invalidation notices...................................................................................................303
20.10 Running the program..............................................................................................303
20.11 Displaying source....................................................................................................304
20.12 Annotations We Might Want in the Future.............................................................305
21 The GDB/MI Interface...........................................................................................................307
21.1 GDB/MI Command Syntax........................................................................................307
21.1.1 GDB/MI Input syntax.........................................................................................307
21.1.2 GDB/MI Output syntax......................................................................................308
21.1.3 Simple examples of GDB/MI interaction...........................................................310
21.2 GDB/MI compatibility with CLI................................................................................310
21.3 GDB/MI output records.............................................................................................311
21.3.1 GDB/MI result records.......................................................................................311
21.3.2 GDB/MI stream records.....................................................................................311
21.3.3 GDB/MI out-of-band records.............................................................................311
21.4 GDB/MI command description format......................................................................311
21.5 GDB/MI breakpoint table commands........................................................................312
21.6 GDB/MI Data manipulation.......................................................................................320
21.7 GDB/MI program control...........................................................................................330
21.8 Miscellaneous GDB commands in GDB/MI..............................................................339
21.9 GDB/MI Stack Manipulation Commands..................................................................341
21.10 GDB/MI Symbol query commands..........................................................................346
21.11 GDB/MI Target Manipulation Commands..............................................................349
21.12 GDB/MI thread commands......................................................................................353
21.13 GDB/MI tracepoint commands................................................................................355
21.14 GDB/MI variable objects..........................................................................................355
22 Reporting Bugs in GDB.........................................................................................................361
22.1 Have you found a bug?.............................................................................................361
22.2 How to report bugs...................................................................................................361
A Installing GDB.......................................................................................................................365
A.1 Compiling GDB in another directory.........................................................................366
A.2 Specifying names for hosts and targets......................................................................367
A.3 configure options...................................................................................................368
12 Table of Contents
Page 13
List of Tables
14-1 Memory Debugging Commands in Interactive and Batch Mode.............................177
16-1 Invocation commands...............................................................................................254
16-2 Window mode commands........................................................................................254
16-3 File viewing commands............................................................................................255
16-4 Data viewing and modification commands..............................................................257
16-5 Stack viewing commands..........................................................................................258
16-6 Status viewing commands........................................................................................259
16-7 Job control commands...............................................................................................259
16-8 Overall breakpoint commands..................................................................................260
16-9 Auxillary breakpoint commands..............................................................................261
16-10 Breakpoint creation commands.................................................................................261
16-11 Overall breakpoint commands..................................................................................262
16-12 Global breakpoint commands...................................................................................263
16-13 Macro facility commands..........................................................................................265
16-14 Signal control commands..........................................................................................265
16-15 Miscellaneous commands.........................................................................................265
16-16 Data format commands.............................................................................................266
16-17 Macro facility commands..........................................................................................268
16-18 Special language operators........................................................................................269
16-19 Special variables........................................................................................................269
16-20 Variable Identifiers....................................................................................................270
16-21 A................................................................................................................................270
16-22 B.................................................................................................................................271
16-23 C through D...............................................................................................................272
16-24 F through K...............................................................................................................273
16-25 L.................................................................................................................................273
16-26 M through P..............................................................................................................274
16-27 Q through S...............................................................................................................275
16-28 T.................................................................................................................................275
16-29 U through Z...............................................................................................................276
16-30 Symbols.....................................................................................................................277
21-1 GDB/MI Operations...................................................................................................356
13
Page 14
List of Examples
14-1 Sample Output for the find command....................................................................198
14-2 Sample Commands to Print NaT Registers...............................................................214
14 List of Examples
Page 15

Summary of GDB

The purpose of a debugger such as GDB is to allow you to see whatis going on “inside” another programwhile it executes―or what another program was doing at the moment it crashed.
GDB allows you to do the following:
Load the executable along with any required arguments.
Stop your program on specified blocks of code.
Examine your program when it has stopped running due to an error.
Change things in your program, so you can experiment with correcting the effects of one bug and go on to learn about another.
You can use GDB to debug programs written in C, C++, and Fortran. For more information, refer to the “Supported languages” (page 105). For more information on supported languages, refer to the “C and C++” (page 106).
GDB can be used to debug programs written in Fortran, although it may be necessary to refer to some variables with a trailing underscore. See “Fortran” (page 112).
This version of the manual documents WDB, implemented on HP 9000 or HP Integrity systems running Release 11.x of the HP-UX operating system. WDB can be used to debug code generated by the HP ANSI C, HP ANSI aC++ and HP Fortran compilers as well as the GNU C and C++ compilers. It does not support the debugging of Pascal, Modula-2 or Chill programs.

Free Software

GDB is free software, protected by the GNU General Public License (GPL). The GPL gives you the freedom to copy or adapt a licensed program―but every person getting a copy also gets with it the freedom to modify that copy (which means that they must get access to the source code), and the freedom to distribute further copies. Typical software companies use copyrights to limit your freedoms; the Free Software Foundation uses the GPL to preserve these freedoms.
Fundamentally, the General Public License is a license which says that you have these freedoms and that you cannot take these freedoms away from anyone else.

Contributors to GDB

Richard Stallman was the original author of GDB, and of many other GNU programs. Many others have contributed to its development. This section attempts to credit major contributors. One of the virtues of free software is that everyone is free to contribute to it; with regret, we cannot actually acknowledge everyone here. The file 'ChangeLog' in the GDB distribution approximates a blow-by-blow account.
Changes much prior to version 2.0 are lost in the mists of time.
Free Software 15
Page 16
Plea: Additions to this section are particularly welcome. If you or your friends (or enemies, to be evenhanded) have been unfairly omitted from this list, we would like to add your names!
So that they may not regard their many labors as thankless, we particularly thank those who shepherdedGDB through major releases: Andrew Cagney (release 5.0); Jim Blandy (release 4.18); Jason Molenda (release 4.17); Stan Shebs (release 4.14); Fred Fish (releases
4.16, 4.15, 4.13, 4.12, 4.11, 4.10, and 4.9); Stu Grossman and John Gilmore (releases 4.8,
4.7, 4.6, 4.5, and 4.4); John Gilmore (releases 4.3, 4.2, 4.1, 4.0, and 3.9); Jim Kingdon (releases 3.5, 3.4, and 3.3); and Randy Smith (releases 3.2, 3.1, and 3.0).
Richard Stallman,assisted at various times by Peter TerMaat, Chris Hanson, and Richard Mlynarik, handled releases through 2.8.
Michael Tiemann is the author of most of the GNU C++ support in GDB, with significant additional contributions from Per Bothner. James Clark wrote the GNU C++ demangler. Early work on C++ was by Peter TerMaat (who also did much general update work leading to release 3.0).
GDB 4 uses the BFD subroutine library to examine multiple object-file formats; BFD was a joint project of David V. Henkel-Wallace, Rich Pixley, Steve Chamberlain, and John Gilmore.
David Johnson wrote the original COFF support; Pace Willison did the original support for encapsulated COFF.
Brent Benson of Harris Computer Systems contributed DWARF 2 support.
Adam de Boor andBradley Daviscontributed theISI OptimumV support.Per Bothner, Noboyuki Hikichi,and Alessandro Forin contributedMIPS support. Jean-Daniel Fekete contributed Sun 386i support. Chris Hanson improved the HP 9000 support. Noboyuki Hikichi and Tomoyuki Hasei contributed Sony/News OS 3 support. David Johnson contributed Encore Umaxsupport. Jyrki Kuoppala contributed Altos 3068 support. Jeff Law contributed HP PA and SOM support. Keith Packard contributed NS32K support. Doug Rabson contributed Acorn Risc Machine support. Bob Rusk contributed Harris Nighthawk CX-UX support. Chris Smith contributed Convex support (and Fortran debugging). JonathanStone contributed Pyramid support. Michael Tiemann contributed SPARC support. Tim Tucker contributed support for the Gould NP1 and Gould Powernode. Pace Willison contributed Intel 386 support. Jay Vosburgh contributed Symmetry support.
Andreas Schwab contributed M68K Linux support.
Rich Schaefer and Peter Schauer helped with support of SunOS shared libraries.
Jay Fenlason and Roland McGrath ensured that GDB and GAS agree about several machine instruction sets.
Patrick Duval, Ted Goldstein, Vikram Koka and Glenn Engel helped develop remote debugging. IntelCorporation, WindRiver Systems, AMD, and ARM contributed remote debugging modules for the i960, VxWorks, A29K UDI, and RDI targets, respectively.
16
Page 17
Brian Fox is the author of the readline libraries providing command-line editing and command history.
Andrew Beers of SUNY Buffalo wrote the language-switching code, the Modula-2 support, and contributed the Languages chapter of this manual.
Fred Fish wrote most of the support for Unix System Vr4. He also enhanced the command-completion support to cover C++ overloaded symbols.
Hitachi America, Ltd. sponsored the support for H8/300, H8/500, and Super-H processors.
NEC sponsored the support for the v850, Vr4xxx, and Vr5xxx processors.
Mitsubishi sponsored the support for D10V, D30V, and M32R/D processors.
Toshiba sponsored the support for the TX39 Mips processor.
Matsushita sponsored the support for the MN10200 and MN10300 processors.
Fujitsu sponsored the support for SPARClite and FR30 processors.
Kung Hsu, Je Law, and Rick Sladkey added support for hardware watchpoints.
Michael Snyder added support for tracepoints.
Stu Grossman wrote gdbserver.
Jim Kingdon, Peter Schauer, Ian Taylor, and Stu Grossman made nearly innumerable bug fixes and cleanups throughout GDB.
The following people at the Hewlett-Packard Company contributed support for the PA-RISC 2.0 architecture, HP-UX 10.20, 10.30, and 11.x (narrow mode), HP's implementation of kernel threads, HP's aC++ compiler, and the terminal user interface: Ben Krepp, Richard Title, John Bishop, Susan Macchia, Kathy Mann, Satish Pai, India Paul, Steve Rehrauer, and Elena Zannoni. Kim Haase, Rosario de la Torre, Alex McKale, Michael Coulter, Carl Burch, Bharath Chndramohan, Diwakar Nag, Muthuswami, Dennis Handly, Subash Babu and Dipshikha Basu provided HP-specific information in this manual.
Cygnus Solutions has sponsored GDB maintenance and much of its development since
1991. Cygnus engineers who have worked on GDB full time include Mark Alexander,
Jim Blandy, Per Bothner, Kevin Buettner, Edith Epstein, Chris Faylor, Fred Fish, Martin Hunt, Jim Ingham, John Gilmore, Stu Grossman, Kung Hsu, Jim Kingdon, John Metzler, Fernando Nasser, Georey Noer, Dawn Perchik, Rich Pixley, Zdenek Radouch, Keith Seitz, Stan Shebs, David Taylor, and Elena Zannoni. In addition, Dave Brolley, Ian Carmichael, Steve Chamberlain, Nick Clifton, JT Conklin, Stan Cox, DJ Delorie, Ulrich Drepper, Frank Eigler, Doug Evans, Sean Fagan, David Henkel-Wallace, Richard Henderson, Jeff Holcomb, Jeff Law, Jim Lemke, Tom Lord, Bob Manson, Michael Meissner, Jason Merrill, Catherine Moore, Drew Moseley, Ken Raeburn, Gavin Romig-Koch, Rob Savoye, Jamie Smith, Mike Stump, Ian Taylor, Angela Thomas, Michael Tiemann, Tom Tromey, Ron Unrau, Jim Wilson, and David Zuhn have made contributions both large and small.
Contributors to GDB 17
Page 18
18
Page 19

1 A Sample GDB Session

This chapter describes the most common GDB commands with the help of an example.
The following topics are discussed:
Loading the Executable
Setting the Display Width
Setting Breakpoints
Running the Executable under GDB
Stepping to the next line
Stepping into a Subroutine
Examining the Stack
Printing Variable Values
Listing the Source Code
Setting Variable Values During a Debug Session
In this sample session, we emphasize user input like this: input, to make it easier to pick out from the surrounding output.
One of the preliminary versions of GNU m4 (a generic macro processor) exhibits the following bug: sometimes, when we change its quote strings from the default, the commands used to capture one macro definition within another stop working. In the following short m4 session, we define a macro foo which expands to 0000; we then use the m4 built-in defn to define bar as the same thing. However, when we change the open quote string to <QUOTE> and the close quote string to <UNQUOTE>, the same procedure fails to define a new synonym baz:
$ cd gnu/m4 //change your current directory to the location where the m4 executable is stored. $ ./m4 //run the m4 application define(foo,0000)
foo 0000 define (bar,defn('foo'))
bar 0000 changequote(<QUOTE>,<UNQUOTE>)
define(baz,defn(<QUOTE>foo<UNQUOTE>)) baz C-d
m4: End of input: 0: fatal error: EOF in string

1.1 Loading the Executable

Let us use GDB to try to see what is going on.
1.1 Loading the Executable 19
Page 20
$ (gdb) m4
HP gdb 3.0 for PA-RISC 1.1 or 2.0 (narrow), HP-UX 11.00. Copyright 1986 - 2001 Free Software Foundation, Inc. Hewlett-Packard Wildebeest 3.0 (based on GDB ) is covered by the GNU General Public License. Type "show copying" to see the conditions to change it and/or distribute copies. Type "show warranty" for warranty/support.
GDB reads only enough symbol data to know where to find the rest when needed; as a result, the first prompt comes up very quickly.

1.2 Setting Display width

We now tell GDB to use a narrower display width than usual, so that examples fit in this manual.
((gdb)) set width 70
We need to see how the m4 built-in changequote works. Having looked at the source, we know the relevant subroutine is m4_changequote, so we set a breakpoint there with the GDB break command.

1.3 Setting Breakpoints

Here we describe how to set a breakpoint.
((gdb)) break m4 changequote Breakpoint 1 at 0x62f4: file builtin.c, line 879.

1.4 Running the executable under GDB

Using the run command, we start m4 under GDB control. As long as the control does not reach the m4_changequote subroutine, the program runs as usual.
((gdb)) run Starting program: /work/Editorial/gdb/gnu/m4/m4
define(foo,0000) foo
0000
To trigger the breakpoint, we call changequote. GDB suspends execution of m4, displaying information about the context where it stops.
changequote(<QUOTE>,<UNQUOTE>)
Breakpoint 1, m4_changequote (argc=3, argv=0x33c70) at builtin.c:879 879 if (bad_argc(TOKEN_DATA_TEXT(argv[0]),argc,1,3))

1.5 Stepping to the next line in the source program

Now we use the command n (next) to advance execution to the next line of the current function.
20 A Sample GDB Session
Page 21
((gdb)) n 882 set_quotes((argc >= 2) ? TOKEN_DATA_TEXT(argv[1])\
: nil,

1.6 Stepping into a subroutine

The set_quotes looks like a promising subroutine. We can go into it by using the command s (step) instead of next. step goes to the next line to be executed in any subroutine, so it steps into set_quotes.
((gdb)) s set_quotes (lq=0x34c78 "<QUOTE>", rq=0x34c88 "<UNQUOTE>") at input.c:530 530 if (lquote != def_lquote)

1.7 Examining the Stack

The display that shows the subroutine where m4 is now suspended (and its arguments) is called a stack frame display. It shows a summary of the stack. We can use the backtrace command (which can also be spelled bt), to see where we are in the stack as a whole: the backtrace command displays a stack frame for each active subroutine.
((gdb)) bt #0 set_quotes (lq=0x34c78 "<QUOTE>", rq=0x34c88 "<UNQUOTE>") at input.c:530 #1 0x6344 in m4_changequote (argc=3, argv=0x33c70) at builtin.c:882 #2 0x8174 in expand_macro (sym=0x33320) at macro.c:242 #3 0x7a88 in expand_token (obs=0x0, t=209696, td=0xf7fffa30) at macro.c:71 #4 0x79dc in expand_input () at macro.c:40 #5 0x2930 in main (argc=0, argv=0xf7fffb20) at m4.c:195
We step through a few more lines to see what happens. The first two times, we can use 's'; the next two times we use n to avoid falling into the xstrdup subroutine.
((gdb)) s 0x3b5c 532 if (rquote != def_rquote) ((gdb)) s 0x3b80 535 lquote = (lq == nil || *lq == '\0') ? \ def_lquote : xstrdup(lq); ((gdb)) n 536 rquote = (rq == nil || *rq == '\0') ? def_rquote\ : xstrdup(rq); ((gdb)) n 538 len_lquote = strlen(rquote);

1.8 Printing Variable Values

The last line displayed looks a little odd in the listing above; we can examine the variables lquote and rquote to see if they are in fact the new left and right quotes we specified. We use the command p (print) to view their values.
1.6 Stepping into a subroutine 21
Page 22
((gdb)) p lquote $1 = 0x35d40 "<QUOTE>" ((gdb)) p rquote $2 = 0x35d50 "<UNQUOTE>"

1.9 Listing Source Code

lquote and rquote are indeed the new left and right quotes. To look at some context, we can display ten lines of source surrounding the current line with the l (list) command.
((gdb)) l 533 xfree(rquote); 534 535 lquote = (lq == nil || *lq == '\0') ? def_lquote\ : xstrdup (lq); 536 rquote = (rq == nil || *rq == '\0') ? def_rquote\ : xstrdup (rq); 537 538 len_lquote = strlen(rquote); 539 len_rquote = strlen(lquote); 540 } 541 542 void
Let usstep past the two lines that set len_lquote and len_rquote, and then examine the values of those variables.
((gdb)) n 539 len_rquote = strlen(lquote); ((gdb)) n 540 } ((gdb)) p len_lquote $3 = 9 ((gdb)) p len_rquote $4 = 7

1.10 Setting Variable Values During a Session

That certainly looks wrong, assuming len_lquote and len_rquote are meant to be the lengths of lquote and rquote respectively. We can set them to better values using the p command, since it can print the value of any expression―and that expression can include subroutine calls and assignments.
((gdb)) p len_lquote=strlen(lquote) $5 = 7 ((gdb)) p len_rquote=strlen(rquote) $6 = 9
Is that enough to fix the problem of using the new quotes with the m4 built-in defn? We can allow m4 to continue executing with the c (continue) command, and
then try the example that caused trouble initially:
22 A Sample GDB Session
Page 23
((gdb)) c Continuing.
define(baz,defn(<QUOTE>foo<UNQUOTE>))
baz 0000
Success! The new quotes now work just as well as the default ones. The problem seems to have been just the two typos defining the wrong lengths. We allow m4 to exit by giving it an EOF as input:
C-d Program exited normally.
The message`Program exited normally.' is from GDB;it indicates m4 has finished executing. We can end our GDB session with the GDB quit command.
((gdb)) quit
1.10 Setting Variable Values During a Session 23
Page 24
24
Page 25

2 Getting In and Out of GDB

This chapter discusses how to start GDB, and exit out of it. The essentials are:
type '(gdb)' to start GDB.
type quit or C-d to exit.

2.1 Invoking GDB

Invoke GDB by running the program (gdb). Once started, GDB reads commands from the terminal until you tell it to exit.
You can also run (gdb) with a variety of arguments and options, to specify more of your debugging environment at the outset.
The command-line options described here are designed to cover a variety of situations; in some environments, some of these options may effectively be unavailable.
The most usual way to start GDB is with one argument, specifying an executable program:
(gdb) program
You can also start with both an executable program and a core file specified:
(gdb) program core
You can, instead, specify a process ID as a second argument, if you want to debug a running process:
(gdb) program 1234
would attach GDB to process 1234 (unless you also have a file named '1234'; GDB does check for a core file first).
Taking advantage of the second command-line argument requires a fairly complete operating system; when you use GDB as a remote debugger attached to a bare board, there may not be any notion of “process”, and there is often no way to get a core dump. GDB will warn you if it is unable to attach or to read core dumps.
You can run (gdb) without printing the front material, which describes GDB's non-warranty, by specifying -silent:
gdb -silent
You can further control how GDB starts up by using command-line options. GDB itself can remind you of the options available.
Type
(gdb) -help
to display all available options and briefly describe their use ('(gdb)-h' is a shorter equivalent).
2.1 Invoking GDB 25
Page 26
All options and command-line arguments you give are processed in sequential order. The order makes a difference when the `-x' option is used.

2.1.1 Choosing files

When GDB starts, it reads any arguments other than options as specifying an executable file and core file (or process ID). This is the same as if the arguments were specified by the '-se' and '-c' options respectively. (GDB reads the first argument that does not have an associated option flag as equivalent to the '-se' option followed by that argument; and the second argument that does not have an associated option flag, if any, as equivalent to the '-c' option followed by that argument.)
If GDB has not been configured to included core file support, such as for most embedded targets, then it will complain about a second argument and ignore it.
Many options have both long and short forms; both are shown in the following list. GDB also recognizes the long forms if you truncate them, so long as enough of the option is present to be unambiguous. (If you prefer, you can flag option arguments with `--' rather than `-', though we illustrate the more usual convention.)
-symbols file
-s file
-exec file
-e file
-se file
Read symbol table from file file.
Use file file as the executable file to execute when appropriate, and for examining pure data in conjunction with a core dump.
Read symbol table from file file and use it as the executable file.
-core file
-c file
-c number Connect to process ID number, as with the attach
-command file
-x file
-directory directory
-d directory
26 Getting In and Out of GDB
Use file file as a core dump to examine.
command (unless there is a file in core-dump format named number, in which case `-c' specifies that file as a core dump to read).
Execute GDB commands from file file. See “Command
files” (page 289).
Add directory to the path to search for source files.
Page 27
-m, -mapped
Warning: this option depends on operating system facilities that are not supported on all systems.
If memory-mapped files are available on your system through the mmap system call, you can use this option to have GDB write the symbols from your program into a reusable file in the current directory. If the program you are debugging is called '/tmp/fred', the mapped symbol file is '/tmp/fred.syms'. Future GDB debugging sessions notice the presence of this file, and can quickly map in symbol information from it, rather than reading the symbol table from the executable program.
The '.syms' file is specific to the host machine where GDB is run. It holds an exact image of the internal GDB symbol table. It cannot be shared across multiple host platforms.
-r, -readnow
You typically combine the -mapped and -readnow options in order to build a '.syms' file that contains complete symbol information. (See “Commands to specify files”
(page 125), for information on '.syms' files.) A simple GDB invocation to do nothing
but build a '.syms' file for future use is:
gdb -batch -nx -mapped -readnow programname

2.1.2 Choosing modes

You can run GDB in various alternative modes―for example, in batch mode or quiet mode.
-nx, -n
-quiet, -silent, -q
Read each symbol file's entire symbol table immediately, rather than the default, which is to read it incrementally as it is needed. This makes startup slower, but makes future operations faster.
Do not execute commands found in any initialization files (normally called '.gdbinit', or 'gdb.ini' on PCs). Normally, GDB executes the commands in these files after all thecommand optionsand argumentshave been processed. See “Command files” (page 289).
“Quiet”. Do not print the introductory and copyright messages. These messages are also suppressed in batch mode.
-batch Run in batch mode. Exit with status 0 after processing
all the command files specified with '-x' (and all commands from initialization files, if not inhibited with
2.1 Invoking GDB 27
Page 28
'-n'). Exit with nonzero status if an error occurs in executing the GDB commands in the command files.
Batch mode may be useful for running GDB as a filter, for example to download and run a program on another computer; inorder to make this more useful, the message
Program exited normally.
(which isordinarily issued whenever a program running under GDB control terminates) is not issued when running in batch mode.
-nowindows, -nw
“No windows”. If GDB comes with a graphical user interface (GUI) built in, then this option tells GDB to only use the command-line interface. If no GUI is available, this option has no effect.
-windows, -w
If GDB includes a GUI, then this option requires it to be used if possible.
-cd directory
Run GDB using directory as its working directory, instead of the current directory.
-dbx Support additional dbx commands, including:
use
status (in dbx mode, status has a different
meaning than in default GDB mode.)
whereis
func
file
assign
call
stop
-fullname, -f GNU Emacs sets this option when it runs GDB as a
subprocess. It tells GDB to output the full file name and line number in a standard, recognizable fashion each time a stack frame is displayed (which includes each time your program stops). This recognizable formatlooks like two `\032' characters, followed by the file name, line number, and character position separated by colons, and a newline. The Emacs-to-GDB interface program uses the two '\032' characters as a signal to display the source code for the frame.
-epoch
The Epoch Emacs-GDB interface sets this option when it runs GDB as a subprocess. It tells GDB to modify its
28 Getting In and Out of GDB
Page 29
-annotate level
-async
print routines so as to allow Epoch to display values of expressions in a separate window.
This option sets the annotation level inside GDB. Its effect is identicalto using `set annotate level' (see “GDB
Annotations” (page297)). Annotation level controls how
much information does GDB print together with its prompt, values of expressions, source lines, and other types of output. Level 0 is the normal, level 1 is for use when GDB is run as a subprocess of GNU Emacs, level 2 is the maximum annotation suitable for programs that control GDB.
Use the asynchronous event loop for the command-line interface. GDB processes all events, such as user
1
keyboard input, via a special event loop. This allows GDB to accept and process user commands in parallel with the debugged process being run1, so you do not need to wait for control to return to GDB before you type the next command.
NOTE: As of version 5.0, the target side of the asynchronous operation is not yet in place, so '-async' does not work fully yet.
When the standard input is connected to a terminal device, GDB uses the asynchronous event loop by default, unless disabled by the '-noasync' option.
-noasync
Disable the asynchronous event loop for the command-line interface.
-baud bps, -b bps
Set the line speed (baud rate or bits per second) of any serial interface used by GDB for remote debugging.
-tty device, -t device
Run using device for your program's standard input and output.
-tui
Use a Terminal User Interface. For information, use your Web browser to read the file 'tui.html', which is usually installed in the directory /opt/langtools/ wdb/doc on HP-UX systems. Do not use this option if you run GDB from Emacs (see “Using GDB under gnu
Emacs” (page 293)).
-xdb
Run in XDB compatibility mode, allowing the use of certain XDB commands. For information, see the file
1. GDB built with DJGPP tools for MS-DOS/MS-Windows supports this mode of operation, but the event
loop is suspended when the debug target runs.
2.1 Invoking GDB 29
Page 30
-interpreter interp
-write
-statistics
-version
-pid
-inline
-src_no_g
'xdb_trans.html', which is usually installed in the directory /opt/langtools/wdb/doc on HP-UX systems.
Use the interpreter interp for interface with the controlling program or device. This option is meant to be set by programs which communicate with GDB using it as a back end. For example, '--interpreter=mi' causes GDB to use the gdbmi interface (see “The GDB/MI
Interface” (page 307)).
Open the executable and core files for both reading and writing. This is equivalent to the 'set write on' command inside GDB (see “Patching programs”
(page 122)).
This option causes GDB to print statistics about time and memory usage after it completes each command and returns to the prompt.
This option causes GDB to print its version number and no-warranty blurb, and exit.
This option causes GDB to attach to a running process.
This option causes the debugger to start with the inline debugging on.
This option is used to set the limited source level debugging without compiling.

2.1.3 Redirecting WDB input and output to a file

To redirect WDB input and output to a file, use either of these commands to start the debugger:
$ script log1 $ gdb
or
$ gdb | tee log1

2.2 Quitting GDB

quit [expression], q To exit GDB, use the quit command (abbreviated q), or
type an end-of-file character (usually C-d). If you do not supply expression, GDB will terminate normally; otherwise it will terminate using the result of expression as the error code.
An interrupt (often C-c) does not exit from GDB, but rather terminates the action of any GDB command that is in progress and returns to GDB command level. It is safe to
30 Getting In and Out of GDB
Page 31
type the interrupt character at any time because GDB does not allow it to take effect until a time when it is safe.
You can use the detach command to release an attached process or device.

2.3 Shell commands

If you need to execute occasional shell commands during your debugging session, there is no need to leave or suspend GDB; you can just use the shell command.
shell command string
The utility make is often needed in development environments. You do not have to use the shell command for this purpose in GDB:
make make-args Execute the make program with the specified arguments. This
Invoke a standard shell to execute command string. If it exists, the environment variable SHELL determines which shell to run. Otherwise GDB uses the default shell ('/bin/sh' on UNIX systems, 'COMMAND.COM' on MS-DOS, and so on.).
is equivalent to 'shell make make-args'.
2.3 Shell commands 31
Page 32
32
Page 33

3 GDB Commands

You can abbreviate a GDB command to the first few letters of the command name, if that abbreviation is unambiguous; and you can repeat certain GDB commands by typing just RET ). You can also use the TAB key to get GDB to fill out the rest of a word in a command (or to show you the alternatives available, if there is more than one possibility).

3.1 Command syntax

A GDB command is a single line of input. There is no limit on how long it can be.
It starts with a command name, and is followed by arguments whose meaning depends on the command name.
GDB command names can be truncated if that abbreviation is unambiguous. The possible command abbreviations are listed in the documentation for individual commands. In some cases, even ambiguous abbreviations are allowed; for example, s is specially defined as equivalent to step even though there are other commands whose names start with s. You can test abbreviations by using them as arguments to the help command.
A blank line as input to GDB (typing just RET) means to repeat the previous command. Some commands (for example, run) do not repeat this way. These are commands whose unintentional repetition might cause troubleand which you are unlikely to want to repeat. The list and x commands, when you repeat them with RET, construct new arguments rather than repeating exactly as typed. This permits easy scanning of source or memory.
GDB can also use RET in another way: to partition lengthy output, in a way similar to the common utility more (see “Setting the GDB Screen Size” (page 283)). Since it is easy to press one RET too many in this situation, GDB disables command repetition after any command that generates this sort of display.
Any text from a # to the end of the line is a comment; it does nothing. This is useful mainly in command files (see “Command files” (page 289)).

3.2 Command completion

GDB can fill in the rest of a word in a command for you, if there is only one possibility; it can also show you what the valid possibilities are for the next word in a command, at any time. This works for GDB commands, GDB subcommands, and the names of symbols in your program.
Press the TAB key whenever you want GDB to fill out the rest of a word. If there is only one possibility, GDB fills in the word, and waits for you to finish the command (or press RET to enter it). For example, if you type
((gdb)) info bre TAB
3.1 Command syntax 33
Page 34
GDB fills in the rest of the word 'breakpoints', since that is the only info subcommand beginning with 'bre':
((gdb)) info breakpoints
You can either press RET at this point, to run the info breakpoints command, or backspace and enter something else, if 'breakpoints' does not look like the command you expected. (If you were sure you wanted info breakpoints in the first place, you might as well just type RET immediately after 'info bre', to exploit command abbreviations rather than command completion.)
If there is more than one possibility for the next word when you press TAB , GDB sounds a bell. You can either supply more characters and try again, or just press TAB a second time; GDB displays all the possible completions for that word. For example, you might want to set a breakpoint on a subroutine whose name begins with 'make_', but when you type b make_TAB GDB just sounds the bell. Typing TAB again displays all the function names in your program that begin with those characters, for example:
((gdb)) b make_TAB
GDB sounds bell; press TAB again, to see:
make_a_section_from_file make_environ make_abs_section make_function_type make_blockvector make_pointer_type make_cleanup make_reference_type make_command make_symbol_completion_list
((gdb)) b make_
After displaying the available possibilities, GDB copies your partial input ('b make_' in the example) so you can finish the command.
If you just want to see the list of alternatives in the first place, you can press M-? rather than pressing TAB twice. M-? means META?. You can type this either by holding down a key designated as the META shift on your keyboard (if there is one) while typing ?, or as ESC followed by ?.
Sometimes the string you need, while logically a “word”, may contain parentheses or other characters that GDB normally excludes from its notion of a word. To permit word completion to work in this situation, you may enclose words in ' (single quote marks) in GDB commands.
The most likely situation where you might need this is in typing the name of a C++ function. This is because C++ allows function overloading (multiple definitions of the same function, distinguished by argument type). For example, when you want to set a breakpoint you may need to distinguish whether you mean the version of name that takes an int parameter, name(int), or the version that takes a float parameter, name(float). To use the word-completion facilities in this situation, type a single quote ' at the beginning of the function name. This alerts GDB that it may need to consider more information than usual when you press TAB or M-? to request word completion:
((gdb)) b 'bubble( M-?
34 GDB Commands
Page 35
bubble(double,double) bubble(int,int) ((gdb)) b 'bubble(
In some cases, GDB can tell that completing a name requires using quotes. When this happens, GDB inserts the quote for you (while completing as much as it can) if you do not type the quote in the first place:
((gdb)) b bub TAB
GDB alters your input line to the following, and rings a bell:
((gdb)) b 'bubble(
In general, GDB can tell that a quote isneeded (and inserts it) if you have not yet started typing the argument list when you ask for completion on an overloaded symbol.
For more information about overloaded functions, see “C++ expressions” (page 109). You can use the command set overload-resolution off to disable overload resolution; see “GDB features for C++” (page 111).

3.3 Getting help

You can always ask GDB itself for information on its commands, using the command
help.
help, h You can use help (abbreviated h) with no arguments to display
a short list of named classes of commands:
((gdb)) help List of classes of commands:
aliases -- Aliases of other commands breakpoints -- Making program stop at certain points data -- Examining data files -- Specifying and examining files internals -- Maintenance commands obscure -- Obscure features running -- Running the program stack -- Examining the stack status -- Status inquiries support -- Support facilities tracepoints -- Tracing of program execution without stopping the program user-defined -- User-defined commands
Type "help" followed by a class name for a list of commands in that class. Type "help" followed by command name for full documentation. Command name abbreviations are allowed if unambiguous. ((gdb))
3.3 Getting help 35
Page 36
help class
Using one of the general help classes as an argument, you can get a list of the individual commands in that class. For example, here is the help display for the class status:
((gdb)) help status Status inquiries.
List of commands:
info -- Generic command for showing things about the program being debugged show -- Generic command for showing things about the debugger
Type "help" followed by command name for full documentation. Command name abbreviations are allowed if unambiguous. ((gdb))
help command With a command name as help argument, GDB displays a short
paragraph on how to use that command.
apropos args The apropos args command searches through all of the GDB
commands, and their documentation, for the regular expression specified in args. It prints out all matches found. For example:
apropos reload
results in:
set symbol-reloading -- Set dynamic symbol table reloading multiple times in one run show symbol-reloading -- Show dynamic symbol table reloading multiple times in one run
complete args The complete args command lists all the possible completions
In addition to help, you can use the GDB commands info and show to inquire about the state of your program, or the state of GDB itself. Each command supports many topics of inquiry; this manual introduces each of them in the appropriate context. The
36 GDB Commands
for the beginning of a command. Use args to specify the beginning of the command you want completed. For example:
complete i
results in:
if ignore info inspect
This is intended for use by GNU Emacs.
Page 37
listings under info and under show in the Index point to all the sub-commands. See ???.
info This command (abbreviated i) is for describing the state of your program. For
example, you can list the arguments given to your program with info args, list the registers currently in use with info registers, or list the breakpoints you have set with info breakpoints. You can get a complete list of the
info sub-commands with help info.
set
You can assign the result of an expression to an environment variable with
set. For example, you can setthe GDBprompt toa $-signwith set prompt $.
show In contrast to info, show is for describing the state of GDB itself. You can
change most of the things you can show, by using the related command set; for example, you can control what number system is used for displays with set radix, or simply inquire which is currently in use with show radix.
To display all the settable parameters and their current values, you can use show with no arguments; you may also use info set. Both commands produce the same display.
Here are three miscellaneous show subcommands, all of which are exceptional in lacking corresponding set commands:
show version
Show what version of GDB is running. You should include this information in GDB bug-reports. If multiple versions of GDB are in use at your site, you may need to determine which version of GDB you are running; as GDB evolves, new commands are introduced, and old ones may wither away. Also, many system vendors ship variant versions of GDB, and there are variant versions of GDB in GNU/Linux distributions as well. The version number is the same as the one announced when you start GDB.
show copying
show warranty
Display information about permission for copying GDB.
Display the GNU “NO WARRANTY” statement, or a warranty, if your version of GDB comes with one.
3.3 Getting help 37
Page 38
38
Page 39

4 Running Programs Under GDB

When you run a program under GDB, you must first generate debugging information when you compile it using compiler option cc -g -O.
You may start GDB with its arguments, if any, in an environment of your choice. If you are doing native debugging, you may redirect your program's input and output, debug an already running process, or kill a child process.

4.1 Compiling for debugging

Following points are noteable while compiling programs for debugging:
Compile your program with the -g-O option to generate debugging information.
The -g-O option is supported by HP ANSI C and HP aC++ compilers and GNU gcc compiler.
Some compilers do not support the -g-O options together.
The -g-O options do not work on machines with instruction scheduling.
NOTE: Older versions of the GNU C compiler permitted a variant option '-gg' for debugging information. GDB no longer supports this format; if your GNU C compiler has this option, do not use it.

4.2 Starting your program

run,rUse the run command to start your program under GDB. You must first specify
the programname (except on VxWorks) with an argument to GDB (see Chapter 2
(page 25)), or by using the file or exec-file command (see “Commands to specify files” (page 125)).
NOTE: If you are running your program in an execution environment that supports processes, run creates an inferior process and makes that process run your program. (In environments without processes, run jumps to the start of your program.)
The execution of a program is affected by the information it receives from the parent process. You must provide GDB the information before starting the program. (You can change the information after starting your program, but such changes only affect your program the next time you start it.) The information that must be passed to GDB can be categorized into four categories:
arguments.
Specify the arguments to give your program as the arguments of the run command. If a shell is available on your target, the shell is used to pass the arguments, so that you may use normal conventions (such as wildcard expansion or
4.1 Compiling for debugging 39
Page 40
environment.
working directory.
standard input and output.
variable substitution) in describing the arguments. On Unix systems, you can control which shell is used with the SHELLenvironment variable. GDB usesthe C shell (/usr/bin/csh). See “Arguments To Your Program” (page 41).
Your program inherits its environment from GDB. However,you can usethe GDBcommands set environment and unset environment to change parts of the environment that affect your program. See“Program Environment”
(page 41).
Your program inherits its working directory from GDB. You can set the GDB working directory with the cd command in GDB. See“Working
directory” (page 43).
Your program as default uses the same device for standard input and standard output as GDB is using. You can redirect input and output in the run command line, or you can use the tty command to set a different device for your
40 Running Programs Under GDB
Page 41
NOTE:
When you issue the run command, your program begins to execute immediately. See Chapter 5 (page 51), for discussion of how to arrange for your program to stop. Once your program has stopped, you may call functions in your program, using the print or call commands. See Chapter 8 (page 83).
If the modification time of your symbol file has changed since the last time GDB read its symbols, GDB discards its symbol table, and reads it again. When it does this, GDB tries to retain your current breakpoints.

4.3 Arguments To Your Program

The argumentsto your program can be specified by the arguments of the run command. On HP-UX, they are passed to the C shell (/usr/bin/csh), which expands wildcard characters and performs redirection of I/O, and then to your program.
On non-Unix systems, the program is usually invoked directly by GDB, which emulates I/O redirection via the appropriate system calls, and the wildcard characters are expanded by the startup code of the program, not by the shell.
program. See “Program Input and Output”
(page 43).
WARNING! You can redirect input and output, but you cannot use pipes to pass the output of the program you are debugging to another program; if you attempt this, GDB is likely to wind up debugging the wrong program.
The run command used with no arguments uses the same arguments used by the previous run, or those set by the set args command.
Following commands are used to pass the argument values to your program:
set args
show args
Specify the arguments to be used the next time your program is run. If set args has no arguments, run executes your program with no arguments. Once you have run your program with arguments, using set args before the next run is the only way to run it again without arguments.
Show the arguments to give your program when it is started.

4.4 Program Environment

The environment consists of a set of environment variables and their values. Environment variables conventionally record information such as your user name, your home directory, your terminal type, and your search path for programs to run. Usually you set up environment variables with the shell and they are inherited by all the other
4.3 Arguments To Your Program 41
Page 42
programs you run. When debugging, it can be useful to try running your program with a modified environment without having to start GDB over again.
show envvar
show paths
List all the environment variables used by GDB.
Display the list of search paths for executables (the PATH environment variable).
show environment [varname] Print the value of environment variable varname
to be given to your program when it starts. If you do not supply varname, print the names and values of all environment variables to be given to your program. You can abbreviate
environment as env.
set environment varname
[=value]
Set environment variable varname to value. The value changes for your program only, not for GDB itself. The value may be any string; the values of environment variables are just strings, and any interpretation is supplied by your program itself. The value parameter is optional; if it is eliminated, the variable is set to a null value.
For example, this command:
set env USER = foo
tells the debugged program, when subsequently run, that its user is named 'foo'. (The spaces around '=' are used for clarity here; they are not actually required.)
unset environment varname Remove variable varname from theenvironment
to be passed to your program. This is different from 'set env varname ='; unset environment removes the variable from the environment, rather than assigning it an empty value.
path directory Add directory to the front of the PATH
environment variable (the search path for executables), for both GDB and your program. You may specify several directory names, separated by whitespace or by a system-dependent separator character (`:' on Unix, `;' on MS-DOS and MS-Windows). If directory is already in the path, it is moved to the front, so it is searched sooner.
42 Running Programs Under GDB
Page 43
You can use the string '$cwd' to refer to whatever is the current working directory at the time GDB searches the path. If you use '.' instead, it refers to the directory where you executed the path command. GDB replaces '.' in the directory argument (with the current path) before adding directory to the search path.

4.5 Working directory

Each time you start your program with run, it inherits its working directory from the current working directory of GDB. The GDB working directory is initially whatever it inherited from its parent process (typically the shell), but you can specify a new working directory in GDB with the cd command.
The GDB working directory also serves as a default for the commands that specify files for GDB to operate on. See “Commands to specify files” (page 125).
Following commands are used to set the working directory for your program:
cd directory Set the GDB working directory to directory.
pwd
Print the GDB working directory.

4.6 Program Input and Output

By default, the program you run under GDB does input and output to the same terminal that GDB uses. GDB switches the terminal to its own terminal modes to interact with you, but it records the terminal modes your program was using and switches back to them when you continue running your program.
Following commands are used for redirecting the input and output:
info terminal
tty
Displays information recorded by GDB about the terminal modes your program is using.
Another way to specify where your program should do input and output is with the tty command. This command accepts a file name as argument, and causes this file to be the default for future run commands. It also resets the controlling terminal for the child process, for future run commands. For example,
tty /dev/ttyb
directs that processes started with subsequent run commands default to do input and output on the terminal '/dev/ttyb' and have that as their controlling terminal.
4.5 Working directory 43
Page 44
NOTE:
You can redirect your program input and output using shell redirection with the
run command. For example,
run > outfile
starts your program, diverting its output to the file 'outfile'.
An explicit redirection in run overrides the tty command's effect on the
input/output device, but not its effect on the controlling terminal.
When you use the tty command or redirect input in the run command, only the
input for your program is affected. The input for GDB still comes from your terminal.

4.7 Debugging a Running Process

You can use GDB to debug a running process by specifying the process ID. Following commands are used to debug a running process:
attach process-id
This command attaches to a running process―one that was started outside GDB. (info files shows your active targets.) The command takes as argument a process ID. The usual way to find out the process-id of a Unix process is with the ps utility, or with the 'jobs -l' shell command.
attach does not repeat if you press RET a second time after executing the command.
44 Running Programs Under GDB
Page 45
NOTE:
To use attach, your programmust berunning inan environmentwhich supports processes; for example, attach does not work for programs on bare-board targets that lack an operating system.
You must also have permission to send the process a signal.
When you use attach, the debugger finds the program running in the process first by looking in the current working directory, then (if the program is not found) by using the source file search path (see “Specifying source directories” (page 79)). You can also use the file command to load the program. See “Commands to
specify files” (page 125).
GDB stops the process being attached for debugging. You can examine and modify an attached process with the GDB commands that are available when you start processes with run. You can insert breakpoints; you can step and continue; you can modify storage. See “Breakpoints” (page 51). If you want the process to continue running, you can use the continue command after attaching GDB to the process.
detach
If you exit GDB or use the run command while you have an attached process, you kill that process. By default, GDB asks for confirmation if you try to do either of these things; you cancontrol whether or not you need toconfirm by using the set confirm command (see “Optional warnings and messages” (page 284)).
NOTE: When GDB attaches to a running program you may get a message saying "Attaching to process #nnnnn failed."
The most likely cause for this message is that you have attached to a process that was started across an NFS mount. Versions of the HP-UX kernel before 11.x have a restriction that prevents a debugger from attaching to a process started from an NFS mount, unless the mount was made non-interruptible with the -nointr flag, see mount(1).
When you have finished debugging the attached process, you can use the detach command to release it from GDB control. The process continues its execution after being detached. After the detach command, that process and GDB become completely independent once more, and you are ready to attach another process or start one with run. detach does not repeat if you press RET again after executing the command.

4.8 Killing the child process

Following command is used to kill the child process:
kill
Kill the child process in which your program is running under GDB.
The kill command is useful if you wish to debug a core dump instead of a running process. GDB ignores any core dump file while your program is running.
4.8 Killing the child process 45
Page 46
On some operating systems, a program cannot be executed outside GDB while you have breakpoints set on it inside GDB. You can use the kill command in this situation to permit running your program outside the debugger.
The kill command is also useful if you wish to recompile and relink your program, since on many systems it is impossible to modify an executable file while it is running in a process. In this case, when you next type run, GDB notices that the file has changed, and reads the symbol table again (while trying to preserve your current breakpoint settings).

4.9 Debugging programs with multiple threads

In some operating systems, such as HP-UX and Solaris, a single program may have more than one thread of execution. The precise semantics of threads differ from one operating system to another, but in general the threads of a single program are akin to multiple processes―except that they share one address space (that is, they can all examine and modify the same variables). On the other hand, each thread has its own registers and execution stack, and private memory.
GDB provides these facilities for debugging multi-thread programs:
automatic notification of new threads
thread-specific breakpoints
WARNING! These facilities are not yet available on every GDB configuration where the operating system supports threads. If your GDB does not support threads, these commands have no effect. For example, a system without thread support shows no output from 'info threads', and always rejects the thread command, like this:
((gdb)) info threads ((gdb)) thread 1 Thread ID 1 not known. Use the "info threads" command to see the IDs of currently known threads.
Following commands are used to debug multi-threaded programs:
'thread threadno', a command to switch among threads
'info threads', a command to inquire about existing threads
'thread apply [threadno] [all] args', a command to apply a command
to a list of threads
The GDB thread debugging facility allows you to observe all threads while your program runs―but whenever GDB takes control, one thread in particular is always the focus of debugging. This thread is called the current thread. Debugging commands show program information from the perspective of the current thread.
Whenever GDB detects a new thread in your program, it displays the target system's identification for the thread with a message in the form '[New systag]'. systag is a
46 Running Programs Under GDB
Page 47
thread identifier whose form varies depending on the particular system. For example, on LynxOS, you might see
[New process 35 thread 27]
when GDB notices a new thread. In contrast, on an SGI system, the systag is simply something like 'process 368', with no further qualifier.
For debugging purposes, GDB associates its own thread number―always a single integer―with each thread in your program.
info threads
Display a summary of all threads currently in your program. GDB displays for each thread (in this order):
1. the thread number assigned by GDB
2. the target system's thread identifier (systag)
3. the current stack frame summary for that thread
An asterisk '*' to the left of the GDB thread number indicates the current thread.
For example,
((gdb)) info threads 3 process 35 thread 27 0x34e5 in sigpause () 2 process 35 thread 23 0x34e5 in sigpause () * 1 process 35 thread 13 main (argc=1, argv=0x7ffffff8)
at threadtest.c:68
On HP-UX systems:
For debugging purposes, GDB associates its own thread number―a small integer assigned in thread-creation order―with each thread in your program.
Whenever GDB detects a new thread in your program, it displays both GDB's thread number and the target system's identification for the thread with a message in the form '[New systag]'. systag is a thread identifier whose form varies depending on the particular system. For example, on HP-UX, you see
[New thread 2 (system thread 26594)]
when GDB notices a new thread.
On HP-UX systems, you can control the display of thread creation messages. Following commands are used to control the display of thread creation:
set threadverbose on
Enable the output of informational messages regarding thread creation. The default setting is on. You can set it to off to stop displaying of messages.
set threadverbose off
Disable the output of informational messages regarding thread creation. The default setting is on. You can set it to on to display messages.
4.9 Debugging programs with multiple threads 47
Page 48
show threadverbose Display whether set threadverbose is on or
off.
Here are commands to get more information about threads:
info threads
Display a summary of all threads currently in your program. GDB displays for each thread (in this order):
1. the thread number assigned by GDB
2. the target system's thread identifier (systag)
3. the current stack frame summary for that
thread
4. the priority of a thread
An asterisk '*' to the left of the GDB thread number indicates the current thread.
For example,
((gdb)) info threads * 3 system thread 26607 worker (wptr=0x7b09c318 "@") \ at quicksort.c:137 2 system thread 26606 0x7b0030d8 in __ksleep () \ from /usr/lib/libc.2 1 system thread 27905 0x7b003498 in _brk () \ from /usr/lib/libc.2
thread threadno Make thread number threadno the current
thread apply [threadno] [all] args
48 Running Programs Under GDB
thread. The command argument threadno is the internal GDB thread number, as shown in the first field of the 'info threads' display. GDB respondsby displaying the system identifier of the thread you selected, and its current stack frame summary:
((gdb)) thread 2 [Switching to thread 2 (system thread
26594)] 0x34e5 in sigpause ()
As with the '[New ...]' message, the form of the text after 'Switching to' depends on your system's conventions for identifying threads.
The thread apply command allows you to apply acommand to one or morethreads. Specify the numbers of the threads that you want affected with the command argument threadno.
Page 49
threadno is the internal GDB thread number, as shown in the first field of the 'info threads' display. To apply a command to all threads, use thread apply all args.
Whenever GDB stops your program, due to a breakpoint or a signal, it automatically selects the thread where that breakpoint or signal happened. GDB alerts you to the context switch with a message of the form '[Switching to systag]' to identify the thread.
See “Stopping and starting multi-thread programs” (page 69), for more information about how GDB behaves when you stop and start programs with multiple threads.
See “Killing the child process” (page 45), for information about watchpoints in programs with multiple threads.
NOTE: On HP-UX 11.x, debugging a multi-thread process can cause a deadlock if the process is waiting for an NFS-server response. A thread can be stopped while asleep in this state, and NFS holds a lock on the rnode while asleep.
To prevent the thread from being interrupted while holding the rnode lock, make the NFS mount non-interruptible with the '-nointr' flag. See mount(1).

4.10 Debugging programs with multiple processes

On most systems, GDB has no special support for debugging programs which create additional processesusing the fork function. When a program forks,GDB will continue to debug the parent process and the child process will run unimpeded. If you have set a breakpoint in any code which the child then executes, the child will get a SIGTRAP signal which (unless it catches the signal) will cause it to terminate.
However, if you want to debug the child process there is a workaround which isn't too painful. Put a call to sleep in the code which the child process executes after the fork. It may be useful to sleep only if a certain environment variable is set, or a certain file exists, so that the delay need not occur when you do not want to run GDB on the child. While the child is sleeping, use the ps program to get its process ID. Then tell GDB (a new invocation of GDB if you are also debugging the parent process) to attach to the child process (see “Debugging a Running Process” (page 44)). From that point on you can debug the child process just like any other process which you attached to.
On HP-UX (11.x and later only), GDB provides support for debugging programs that create additional processes using the fork or vfork function.
By default, when a program forks, GDB will continue to debug the parent process and the child process will run unimpeded.
If you want to follow the child process instead of the parent process, use the command set follow-fork-mode.
4.10 Debugging programs with multiple processes 49
Page 50
set follow-fork-mode mode
Set the debugger response to a program call of fork or vfork. A call to fork or vfork creates a new process. The mode can be:
parent
The original process is debugged after a fork. The child process runs unimpeded. This is the default.
child
The new process is debugged after a fork. The parent process runs unimpeded.
show follow-fork-mode Display the current debugger response to a fork
or vfork call.
If you ask to debug a child process and a vfork is followed by an exec, GDB executes the new target up to the first breakpoint in the new target. If you have a breakpoint set on main in your original program, the breakpoint will also be set on the child process's main.
When a child process is spawned by vfork, you cannot debug the child or parent until an exec call completes.
If you issue a run command to GDB after an exec call executes,the new target restarts. To restart the parent process, use the file command with the parent executable name as its argument.
You can use the catch command to make GDB stop whenever a fork, vfork, or exec call is made. See “Setting catchpoints” (page 56).
50 Running Programs Under GDB
Page 51

5 Stopping and Continuing

The principal purpose of a debugger is to let you stop your program before it terminates abnormally or runs into trouble, so that you can investigate and determine the reason.
Inside GDB, your program can stop for several reasons, such as a signal, a breakpoint, or reaching a new line after a GDB command such as step. You can then examine and change variables, set new breakpoints or remove old ones, and then continue execution. Usually, the messages shown by GDB provide information on the status of your program―but you can also explicitly request this information at any time.
info program

5.1 Breakpoints

A breakpoint makes your program stop whenever a certain point in the program is reached. For each breakpoint, you can add conditions to control in finer detail whether your program stops. You can set breakpointswith the break command and its variants. (see “Setting breakpoints” (page 52)) You can stop your program by line number, function name or an address in the program.
You can arrange to have values from your program displayed automatically whenever GDB stops at a breakpoint. See “Automatic display” (page 89).
In HP-UX, SunOS 4.x, SVR4, and Alpha OSF/1 configurations, you can set breakpoints in shared libraries before the executable is run. See “Debugging support for shared
libraries” (page 210).
A catchpoint is another special breakpoint that stops your program when a certain kind of event occurs, such as the throwing of a C++ exception or the loading of a library. As with watchpoints, you use a different command to set a catchpoint (see “Setting
catchpoints” (page 56)), but apart from that, you can manage a catchpoint like any
other breakpoint. (To stop when your program receives a signal, use the handle command; see “Signals” (page 67).)
GDB assigns a number to each breakpoint, watchpoint, or catchpoint when you create it; these numbers are successive integers starting with one. In many of the commands for controlling various features of breakpoints you use the breakpoint number to say which breakpoint you want to change. Each breakpoint may be enabled or disabled; if disabled, it has no effect on your program until you enable it again.
Some GDB commands accept a range of breakpoints on which to operate. A breakpoint range is either a single breakpoint number, like '5', or two such numbers, in increasing order, separated by a hyphen, like '5-7'. When a breakpoint range is given to a command, all breakpoint in that range are operated on.
Display information about the status of your program: whether it is running or not, what process it is, and why it stopped.
5.1 Breakpoints 51
Page 52

5.1.1 Setting breakpoints

Breakpoints are set with the break command (abbreviated b). The debugger convenience variable '$bpnum' records the number of the breakpoint you have set most recently; see “Convenience variables” (page 96), for a discussion of what you can do with convenience variables.
You have several ways to say where the breakpoint should go.
break function
break +offset, break
-offset
break linenum Set a breakpoint at line linenum in the current
Set a breakpoint at entry to function function. When using source languages that permit overloading of symbols, such as C++, function may refer to more than one possible place to break. See “Breakpoint
menus” (page 62), for a discussion of that
situation.
Set a breakpoint some number of lines forward or back from the position at which execution stopped in the currently selected stack frame. (See “Stack
frames” (page 71), for a description of stack
frames.)
source file. The current source file is the last file whose source text was printed. The breakpoint will stop your program just before it executes any of the code on that line.
break filename:linenum Set a breakpoint at line linenum in source file
break filename:function Set a breakpoint at entry to function function
break *address
break When called without any arguments, break sets
52 Stopping and Continuing
filename.
found in file filename. Specifying a fie name as well as a function name is superfluous except when multiple files contain similarly named functions.
Set a breakpoint at address address. You can use this to set breakpoints in parts of your program which do not have debugging information or source files.
a breakpoint at the next instruction to be executed in the selected stack frame (see Chapter 6
(page 71)). In any selected frame but the
innermost, this makes your program stop as soon as control returns to that frame. This is similar to the effect of a finish command in the frame inside the selected frame―except that finish
Page 53
does not leave an active breakpoint. If you use break without an argument in the innermost frame, GDB stops the next time it reaches the current location; this may be useful inside loops.
GDB normally ignores breakpoints when it resumes execution, until at least one instruction has been executed. If it did not do this, you would be unable to proceed past a breakpoint without first disabling the breakpoint. This rule applies whether or not the breakpoint already existed when your program stopped.
break ... if cond Set a breakpoint with condition cond; evaluate
the expression cond each time the breakpoint is reached, and stop only if the value is nonzero―that is, if cond evaluates as true. '...' stands for one of the possible arguments described above (or no argument) specifying where to break. See “Break conditions” (page 59), for more information on breakpoint conditions.
tbreak args Set a breakpoint enabled only for one stop. args
are the same as for the break command, and the breakpoint is set in the same way, but the breakpoint is automatically deleted after the first time your program stops there. See “Disabling
breakpoints” (page 58).
hbreak args Set a hardware-assisted breakpoint. args are the
same as for the break command and the breakpoint is set in the same way, but the breakpoint requires hardware support and some target hardware may not have this support. The main purpose of this is EPROM/ROM code debugging, so you can set a breakpoint at an instruction without changing the instruction. This can beused with the new trap-generationprovided by SPARClite DSU and some x86-based targets. These targets will generate traps when a program accesses some data or instruction address that is assigned to the debug registers. However, the hardware breakpoint registers can take a limited number of breakpoints. For example, on the DSU, only two data breakpoints can be set at a time, and GDB will reject this command if more than two
5.1 Breakpoints 53
Page 54
thbreak args
rbreak regex
are used. Delete or disable unused hardware breakpoints before setting new ones (see
“Disabling breakpoints” (page 58)). See “Break conditions” (page 59).
Set a hardware-assisted breakpoint enabled only for one stop. args are the same as for the hbreak command and the breakpoint is set in the same way. However, like the tbreak command, the breakpoint is automatically deleted after the first time your program stops there. Also, like the hbreak command, the breakpoint requires hardware support and some target hardware may not have this support. See “Disabling breakpoints”
(page 58). See also “Break conditions” (page 59).
Set breakpoints on all functions matching the regular expression regex. This command sets an unconditional breakpoint on all matches, printing a list of all breakpoints it set. Once these breakpoints are set, they are treated just like the breakpoints set with the break command. You can delete them, disable them, or make them conditional the same way as any other breakpoint.
The syntax of the regular expression is the standard one used with tools like 'grep'. Note that this is different from the syntax used by shells, so for instance foo* matches all functions that include an fofollowed by zeroor more os. There is an implicit .* leading and trailing the regular expression you supply, so to match only functions that begin with foo, use ^foo.
info breakpoints [n], info break [n], info watchpoints [n]
54 Stopping and Continuing
When debugging C++ programs, rbreak is useful for setting breakpoints on overloaded functions that are not members of any special classes.
Print a table of all breakpoints, watchpoints, and catchpoints set and not deleted, with the following columns for each breakpoint:
Breakpoint Numbers, Type
Breakpoint, watchpoint, or catchpoint.
Disposition
Whether the breakpoint is
Page 55
marked to be disabled or deleted when hit.
Enabled or Disabled
Enabled breakpoints are marked with 'y'. 'n' marks breakpoints that are not enabled.
Address
Where the breakpoint is in your program, as a memory address.
What
Where the breakpoint is inthe source for your program, as a file and line number.
If a breakpoint is conditional, info break shows the condition on the line following the affected breakpoint; breakpoint commands, if any, are listed after that.
info break with a breakpoint number n as argument lists only that breakpoint. The convenience variable $_ and the default examining-address for the x command are set to the address of the last breakpoint listed (see
“Examining memory” (page 87)).
info break displays a count of the number of times the breakpoint has been hit. This is especially useful in conjunction with the ignore command. You can ignore a large number of breakpoint hits, look at the breakpoint info to see how many times the breakpoint was hit, and then run again, ignoring one less than that number. This will get you quickly to the last hit of that breakpoint.
GDB allows you to set any number of breakpoints at the same place in your program. There is nothing silly or meaningless about this. When the breakpoints are conditional, this is even useful (see “Break conditions” (page 59).
5.1 Breakpoints 55
Page 56
GDB itself sometimes sets breakpoints in your program for special purposes, such as proper handling of longjmp (in C programs). These internal breakpoints are assigned negative numbers, starting with -1; 'info breakpoints' does not display them.
You can see these breakpoints with the GDB maintenance command 'maint info
breakpoints'.
maint info breakpoints Using the same format as 'info breakpoints',
display both the breakpoints you have set explicitly, and those GDB is using for internal purposes. Internal breakpoints are shown with negative breakpoint numbers. The type column identifies what kind of breakpoint is shown:
breakpoint
Normal, explicitly set breakpoint.
watchpoint
Normal, explicitly set watchpoint.
longjmp
Internal breakpoint, used to handle correctly stepping through longjmp calls.
longjmp resume
Internal breakpoint at the target of a longjmp.
until
Temporary internal breakpoint used by the GDB
until command.
finish
Temporary internal breakpoint used by the GDB
finish command.
shlib events
Shared library events.

5.1.2 Setting catchpoints

You can use catchpoints to cause the debugger to stop for certain kinds of program events, such as C++ exceptions or the loading of a shared library. Use the catch command to set a catchpoint.
catch event Stop when event occurs. event can be any of the following:
56 Stopping and Continuing
throw
catch
The throwing of a C++ exception.
The catching of a C++ exception.
exec A call to exec. This is currently only
available for HP-UX.
fork A call to fork. This is currently only
available for HP-UX.
Page 57
vfork A call to vfork. This is currently only
available for HP-UX.
load, load
libname
The dynamic loading of any shared library, or the loading of the library libname. This is currently only available for HP-UX.
unload, unload
libname
The unloading of any dynamically loaded shared library, or the unloading of the library libname. This is currently only available for HP-UX.
tcatch event
Set a catchpoint that is enabled only for one stop. The catchpoint is automatically deleted after the first time the event is caught.
Use the info break command to list the current catchpoints.
There are currently some limitations to C++ exception handling (catch throw and catch catch) in GDB:
If you call a function interactively, GDB normally returns control to you when the function has finished executing. If the call raises an exception, however, the call may bypass the mechanism that returns control to you and cause your program either to abort or to simply continue running until it hits a breakpoint, catches a signal that GDB is listening for, or exits. This is the case even if you set a catchpoint for the exception; catchpoints on exceptions are disabled within interactive calls.
You cannot raise an exception interactively.
You cannot install an exception handler interactively.
Sometimes catch is not the best way to debug exception handling: if you need to know exactly where an exception is raised, it is better to stop before the exception handler is called, since that way you can see the stack before any unwinding takes place. If you set a breakpoint in an exception handler instead, it may not be easy to find out where the exception was raised.
To stop just before an exception handler is called, you need some knowledge of the implementation. In the case of GNU C++, exceptions are raised by calling a library function named _ _raise_exception which has the following ANSI C interface:
/* addr is where the exception identifier is stored. id is the exception identifier. */ void __raise_exception (void **addr, void *id);
To make the debugger catch all exceptions before any stack unwinding takes place, set a breakpoint on __raise_exception (see “Breakpoints” (page 51)).
With a conditional breakpoint (see “Break conditions” (page 59)) that depends on the value of id, you can stop your program when a specific exception is raised. You can use multiple conditional breakpoints to stop your program when any of a number of exceptions are raised.
5.1 Breakpoints 57
Page 58

5.1.3 Deleting breakpoints

It is often necessary to eliminate a breakpoint, watchpoint, or catchpoint once it has done its job and you no longer want your program to stop there. This is called deleting the breakpoint. A breakpoint that has been deleted no longer exists; it is forgotten.
With the clear command you can delete breakpoints according to where they are in your program. With the delete command you can delete individual breakpoints, watchpoints, or catchpoints by specifying their breakpoint numbers.
It is not necessary to delete a breakpoint to proceed past it. GDB automatically ignores breakpoints on the first instruction to be executed when you continue execution without changing the execution address.
clear
clear function, clear
filename:function
clear linenum, clear filename:linenum
delete [breakpoints] [range...]
Delete any breakpoints at the next instruction to be executed in the selected stack frame (see
“Selecting a frame” (page 73)). When the
innermost frame is selected, this is a good way to delete a breakpoint where your program just stopped.
Delete any breakpoints set at entry to the function function.
Delete any breakpoints set at or within the code of the specified line.
Delete the breakpoints, watchpoints, or catchpoints of thebreakpoint ranges specified as arguments. If no argument is specified, delete all breakpoints (GDB asks confirmation, unless you have set confirm off). You can abbreviate this command as d.

5.1.4 Disabling breakpoints

Rather than deleting a breakpoint, watchpoint, or catchpoint, you might prefer to disable it. This makes the breakpoint inoperative as if it had been deleted, but remembers the information on the breakpoint so that you can enable it again later.
You disable and enable breakpoints, watchpoints, and catchpoints with the enable and disable commands, optionally specifying one or more breakpoint numbers as arguments. Use info break or info watch to print a list of breakpoints, watchpoints, and catchpoints if you do not know which numbers to use.
A breakpoint, watchpoint, or catchpoint can have any of four different states of enablement:
Enabled. The breakpoint stops your program. A breakpoint set with the break
command starts out in this state.
Disabled. The breakpoint has no effect on your program.
58 Stopping and Continuing
Page 59
Enabled once. The breakpoint stops your program, but then becomes disabled.
Enabled for deletion. The breakpoint stops your program, but immediately after it does so it is deleted permanently. A breakpoint set with the tbreak command starts out in this state.
You can use the following commands to enable or disable breakpoints, watchpoints, and catchpoints:
disable [breakpoints] [range...]
Disable the specified breakpoints―or all breakpoints, if none are listed. A disabled breakpoint has no effect but is not forgotten. All options such as ignore-counts, conditions, and commands are remembered in case the breakpoint is enabled again later. You may abbreviate disable as dis.
enable [breakpoints] [range...]
Enable the specified breakpoints (or all defined breakpoints). They become effective once again in stopping your program.
enable [breakpoints] once range...
Enable the specified breakpoints temporarily. GDB disables any of these breakpoints immediately after stopping your program.
enable [breakpoints] delete range...
Enable the specified breakpoints to work once, then die. GDB deletes any of these breakpoints as soon as your program stops there.
Except for a breakpoint set with tbreak (see “Setting breakpoints” (page 52)), breakpoints that you set are initially enabled; subsequently, they become disabled or enabled only when you use one of the commands above. (The command until can set and delete a breakpoint of its own, but it does not change the state of your other breakpoints; see “Continuing and stepping” (page 64).)

5.1.5 Break conditions

The simplest sort of breakpoint breaks every time your program reaches a specified place. You can also specify a condition for a breakpoint. A condition is just a Boolean expression in your programming language (see “Expressions” (page 83)). A breakpoint with a condition evaluates the expression each time your program reaches it, and your program stops only if the condition is true.
This is the converse of using assertions for program validation; in that situation, you want to stop when the assertion is violated―that is, when the condition is false. In C, if you want to test an assertion expressed by the condition assert, you should set the condition '! assert' on the appropriate breakpoint.
Conditions are also accepted for watchpoints; you may not need them, since a watchpoint is inspecting the value of an expression anyhow―but it might be simpler,
5.1 Breakpoints 59
Page 60
say, to just set a watchpoint on a variable name, and specify a condition that tests whether the new value is an interesting one.
Break conditions can have side effects, and may even call functions in your program. This can be useful, for example, to activate functions that log program progress, or to use your own print functions to format special data structures. The effects are completely predictable unless there is another enabled breakpoint at the same address. (In that case, GDB might see the other breakpoint first and stop your program without checking the condition of this one.) Note that breakpoint commands are usually more convenient and flexible than break conditions for the purpose of performing side effects when a breakpoint is reached (see “Breakpoint command lists” (page 61)).
Break conditions can be specified when a breakpoint is set, by using 'if' in the arguments to the break command. See “Setting breakpoints” (page 52). They can also be changed at any time with the condition command.
You can also use the if keyword with the watch command. The catch command does not recognize the if keyword; condition is the only way to impose a further condition on a catchpoint.
condition bnum expression Specify expression as the break condition for
breakpoint, watchpoint, or catchpoint number bnum. After you set a condition, breakpoint bnum stops your program only if the value of expression is true (nonzero, in C). When you use condition, GDB checks expression immediately for syntactic correctness, and to determine whether symbols in it have referents in the context of your breakpoint. If expression uses symbols not referenced in the context of the breakpoint, GDB prints an error message:
No symbol "foo" in current context.
GDB does not actually evaluate expression at the time the condition command (or a command that sets a breakpoint with a condition, like break if ...) is given, however. See “Expressions”
(page 83).
condition bnum
A special case of a breakpoint condition is to stop only when the breakpoint has been reached a certain number of times. This is so useful that there is a special way to do it, using the ignore count of the breakpoint. Every breakpoint has an ignore count, which is an integer. Most of the time, the ignore count is zero, and therefore has no effect. But if your program reaches a breakpoint whose ignore count is positive, then
60 Stopping and Continuing
Remove the condition from breakpoint number bnum. It becomes an ordinary unconditional breakpoint.
Page 61
instead of stopping, it just decrements the ignore count by one and continues. As a result, if the ignore count value is n, the breakpoint does not stop the next n times your program reaches it.
ignore bnum count Set the ignore count of breakpoint number bnum to count.
The next count times the breakpoint is reached, your program's execution does not stop; other than to decrement the ignore count, GDB takes no action.
To make the breakpoint stop the next time it is reached, specify a count of zero.
When you use continue to resume execution of your program froma breakpoint, you can specify an ignore count directly as an argument to continue, rather than using ignore. See “Continuing and stepping” (page 64).
If a breakpoint has a positive ignore count and a condition, the condition is not checked. Once the ignore count reaches zero, GDB resumes checking the condition.
You could achieve the effect of the ignore count with a condition such as '$foo-- <= 0' using a debugger convenience variable that is decremented each time. See
“Convenience variables” (page 96).
Ignore counts apply to breakpoints, watchpoints, and catchpoints.

5.1.6 Breakpoint command lists

You can give any breakpoint (or watchpoint or catchpoint) a series of commands to execute when your program stops due to that breakpoint. For example, you might want to print the values of certain expressions, or enable other breakpoints.
commands [bnum], ... command-list ..., end
Pressing RET as a means of repeating the last GDB command is disabled within a command-list.
Specify a list of commands for breakpoint number bnum. The commands themselves appear on the following lines. Type a line containing just end to terminate the commands.
To remove all commands from a breakpoint, type commands and follow it immediately with end; that is, give no commands.
With no bnum argument, commands refers to the last breakpoint, watchpoint, or catchpoint set (not to the breakpoint most recently encountered).
5.1 Breakpoints 61
Page 62
You can use breakpoint commands to start your program up again. Simply use the continue command, or step, or any other command that resumes execution.
Any other commands in the command list, after a command that resumes execution, are ignored. This is because any time you resume execution (even with a simple next or step), you may encounter another breakpoint―whichcould have its own command list, leading to ambiguities about which list to execute.
If the first command you specify in a command list is silent, the usual message about stopping at a breakpoint is not printed. This may be desirable for breakpoints that are to print a specific message and then continue. If none of the remaining commands print anything, you see no sign that the breakpoint was reached. silent is meaningful only at the beginning of a breakpoint command list.
The commands echo, output, and printf allow you to print precisely controlled output, and are often useful in silent breakpoints. See “Commands for controlled
output” (page 290).
For example, here is how you could use breakpoint commands to print the value of
x at entry to foo whenever x is positive.
break foo if x>0 commands silent printf "x is %d\n",x cont end
One application for breakpoint commands is to compensate for one bug so you can test for another. Put a breakpoint just after the erroneous line of code, give it a condition to detect the case in which something erroneous has been done, and give it commands to assign correct values to any variables that need them. End with the continue command so that your program does not stop, and start with the silent command so that no output is produced. Here is an example:
break 403 commands silent set x = y + 4 cont end

5.1.7 Breakpoint menus

Some programming languages (notably C++) permit a single function name to be defined several times, for application in different contexts. This is called overloading. When a function name is overloaded, 'break function' is not enough to tell GDB where you want a breakpoint. If you realize this is a problem, you can use something like 'break function(types)' to specify which particular version of the function you want. Otherwise, GDB offers you a menu of numbered choices for different possible breakpoints, and waits for your selection with the prompt '>'. The first two options are
62 Stopping and Continuing
Page 63
always '[0] cancel' and '[1] all'. Typing 1 sets a breakpoint at each definition of function, andtyping 0 aborts the break command without setting any new breakpoints.
For example, the following session excerpt shows an attempt to set a breakpoint at the overloaded symbol String::after. We choose three particular definitions of that function name:
((gdb)) b String::after [0] cancel [1] all [2] file:String.cc; line number:867 [3] file:String.cc; line number:860 [4] file:String.cc; line number:875 [5] file:String.cc; line number:853 [6] file:String.cc; line number:846 [7] file:String.cc; line number:735 > 2 4 6 Breakpoint 1 at 0xb26c: file String.cc, line 867. Breakpoint 2 at 0xb344: file String.cc, line 875. Breakpoint 3 at 0xafcc: file String.cc, line 846. Multiple breakpoints were set. Use the "delete" command to delete unwanted breakpoints. ((gdb))

5.1.8 “Cannot insert breakpoints”

Under some operating systems, breakpoints cannot be used in a program if any other process is running that program. In this situation, attempting to run or continue a program with a breakpoint causes GDB to print an error message:
Cannot insert breakpoints. The same program may be running in another process.
When this happens, you have three ways to proceed:
1. Remove or disable the breakpoints, then continue.
2. Suspend GDB, and copy the file containing your program to a new name. Resume
GDB and use the exec-file command to specify that GDB should run your program under that name. Then start your program again.
3. Relink your program so that the text segment is nonsharable, using the linker option '-N'. The operating system limitation may not apply to nonsharable executables.
A similar message can be printed if you request too many active hardware-assisted breakpoints and watchpoints:
Stopped; cannot insert breakpoints. You may have requested too many hardware breakpoints and watchpoints.
This message is printed when you attempt to resume the program, since only then GDB knows exactly how many hardware breakpoints and watchpoints it needs to insert.
5.1 Breakpoints 63
Page 64
When this message is printed, you need to disable or remove some of the hardware-assisted breakpoints and watchpoints, and then continue.

5.2 Continuing and stepping

Continuing means resuming program execution until yourprogram completes normally. In contrast, stepping means executing just one more “step” of your program, where “step” may meaneither one line of source code, or one machine instruction (depending on what particularcommand you use).Either when continuing or when stepping, your program may stop even sooner, due to a breakpoint or a signal. (If it stops due to a signal, you may want to use handle, or use 'signal 0' to resume execution. See
“Signals” (page 67).)
continue [ignore-count], c [ignore-count], fg [ignore-count]
Resume program execution, at the address where your program last stopped; any breakpoints set at that address arebypassed. The optional argument ignore-count allows you to specify a further number of times to ignore a breakpoint at this location; its effect is like that of ignore (see “Break
conditions” (page 59)).
The argument ignore-count is meaningful only when your program stopped due to a breakpoint. At other times, the argument to continue is ignored.
To resume execution at a different place, you can use return (see “Returning from a
function” (page 121)) to go back to the calling function; or jump (see “Continuing at a different address” (page 120)) to go to an arbitrary location in your program.
A typical technique for using stepping is to set a breakpoint (see “Breakpoints”
(page 51)) at the beginning of the function or the section of your program where a
problem is believed to lie, run your program until it stops at that breakpoint, and then step through the suspect area, examining the variables that are interesting, until you see the problem happen.
64 Stopping and Continuing
The synonyms c and fg (for foreground, as the debugged program is deemed to be theforeground program) are provided purely for convenience, and have exactly thesame behavioras continue.
Page 65
step
Continue running your program until control reaches a different source line, then stop it and return control to GDB. This command is abbreviated s.
WARNING! If you use the step command while control is within a function that was compiled without debugging information, execution proceeds until control reaches a function that does have debugging information. Likewise, it will not step into a function which is compiled without debugging information. To step through functions without debugging information, use the stepi command, described below.
The step command only stops at the first instruction of a source line. This prevents the multiple stops that could otherwise occur in switch statements, for loops, and so on. step continues to stop if a function that has debugging information is called within the line. In other words, step steps inside any functions called within the line.
Also, the step command only enters a function if there is line number information for the function. Otherwise it acts like the next command. This avoids problems when using cc -gl on MIPS machines. Previously, step entered subroutines if there was any debugging information about the routine.
step count Continue running as in step, but do so count times. If a
breakpoint is reached, or a signal not related to stepping occurs before count steps, stepping stops right away.
next [count]
Continue to the next source line in the current (innermost) stack frame. This is similar to step, but function calls that appear within the line of code are executed without stopping. Execution stops when control reaches a different line of code at the original stack level that was executing when you gave the next command. This command is abbreviated n.
An argument count is a repeat count, as for step.
The next command only stops at the first instruction of a source line. This prevents multiple stops that could otherwise occur in switch statements, for loops, and so on.
finish
Continue running until just after function in the selected stack frame returns. Print the returned value (if any).
Contrast this with the return command (see “Returning from
a function” (page 121)).
5.2 Continuing and stepping 65
Page 66
until, u
Continue running until a source line past the current line, in the current stack frame, is reached. This command is used to avoid single stepping through a loop more than once. It is like the next command, except that when until encounters a jump, it automatically continues execution until the program counter is greater than the address of the jump.
This means that when you reach the end of a loop after single stepping though it, until makes your program continue execution until it exits the loop. In contrast, a next command at the end of a loop simply steps back to the beginning of the loop, which forces you to step through the next iteration.
until always stops your program if it attempts to exit the current stack frame.
until may produce somewhat counterintuitive results if the order of machine code does not match the order of the source lines. For example, in the following excerpt from a debugging session, thef (frame) command shows that execution is stopped at line 206; yet when we use until, we get to line 195:
((gdb)) f #0 main (argc=4, argv=0xf7fffae8) at m4.c:206 206 expand_input(); ((gdb)) until 195 for ( ; argc > 0; NEXTARG) {
This happened because, for execution efficiency, the compiler had generated code for the loop closure test at the end, rather than the start, of the loop―even though the test in a C for-loop is written before the body of the loop. The until command appeared to step back to the beginning of the loop when it advanced to this expression; however, it has not really gone to an earlier statement―not in terms of the actual machine code.
until location, u location
66 Stopping and Continuing
until with no argument works by means of single instruction stepping, and hence is slower than until with an argument.
Continue running your program until either the specified location is reached, or the current stack frame returns. location is any of the forms of argument acceptable to break (see
“Setting breakpoints” (page 52)). This form of the command
uses breakpoints, and hence is quicker than until without an argument.
Page 67
stepi, stepi arg, si
Execute one machine instruction, then stop and return to the debugger.
It is often useful to do 'display/i $pc' when stepping by machine instructions. This makes GDB automatically display the next instruction to be executed, each time your program stops. See “Automatic display” (page 89).
An argument is a repeat count, as in step.
nexti, nexti arg, ni

5.3 Signals

A signal is an asynchronous event that can happen in a program. The operating system defines the possible kinds of signals, and gives each kind a name and a number. For example, in Unix SIGINT is the signal a program gets when you type an interrupt character (often C- c); SIGSEGV is the signal a program gets from referencing a place in memory far away from all the areas in use; SIGALRM occurs when the alarm clock timer goes off (which happens only if your program has requested an alarm).
Some signals, including SIGALRM, are a normal part of the functioning of your program. Others, such as SIGSEGV, indicate errors; these signals are fatal (they kill your program immediately) if the program has not specified in advance some other way to handle the signal. SIGINT does not indicate an error in your program, but it is normally fatal so it can carry out the purpose of the interrupt: to kill the program.
GDB has the ability to detect any occurrence of a signal in your program. You can tell GDB in advance what to do for each kind of signal.
Normally, GDB is set up to ignore non-erroneous signals like SIGALRM (so as not to interfere with their role in the functioning of your program) but to stop your program immediately whenever an error signal happens. You can change these settings with the handle command.
Execute one machine instruction, but if it is a function call, proceed until the function returns.
An argument is a repeat count, as in next.
5.3 Signals 67
Page 68
NOTE: Use caution if you disable all signals from certain processes. Disabling 'SIGTRAP' in your program may cause your program to hang.
HP-UX uses 'SIGTRAP' to communicate with the debugger. If you disable all signals from certain processes so that signals will be delivered to the right process, your program may hang when you try to debug it. This behavior occurs because if you disable 'SIGTRAP', the debugger no longer receives notification of events such as breakpoint hits and loading or unloading of shared libraries.
To prevent this problem:
Make certain you set this flag:
(gdb) set complain-if-sigtrap-disabled on
Also make certain the following warning was not emitted by the debugger before your program hung:
Warning: Thread %d (in process %d) has disabled SIGTRAPs. Debugging this thread is probably impossible. If you do not want to see this message again, use: "set complain-if-sigtrap-disabled 0"
info signals, info handle
Print a table of all the kinds of signals and how GDB has been told to handle each one. You can use this to see the signal numbers of all the defined types of signals.
info handle is an alias for info signals.
handle signal keywords... Change the way GDB handles signal signal.
signal can be the number of a signal or its name (with or without the 'SIG' at the beginning). The keywords say what change to make.
The keywords allowed by the handle command can be abbreviated. Their full names are:
nostop
GDB should not stop your program when this signal happens. It may still print a message telling you that the signal has come in.
stop
GDB should stop your program when this signal happens. This implies the print keyword as well.
print
noprint
GDB should print a message when this signal happens.
GDB should not mention the occurrence of the signal at all. This implies the nostop keyword as well.
68 Stopping and Continuing
Page 69
pass
GDB should allow your program to see this signal; your program can handle the signal, or else it may terminate if the signal is fatal and not handled.
nopass
GDB should not allow your program to see this signal.
When a signal stops your program, the signal is not visible to the program until you continue. Your program sees the signal then, if pass is in effect for the signal in question at that time. In other words, after GDB reports a signal, you can use the handle command with pass or nopass to control whether your program sees that signal when you continue.
You can also use the signal command to prevent your program from seeing a signal, or cause it to see a signal it normally would not see, or to give it any signal at any time. For example, if your program stopped due to some sort of memory reference error, you might store correct values into the erroneous variables and continue, hoping to see more execution; but your program would probably terminate immediately as a result of the fatal signal once it saw the signal. To prevent this, you can continue with 'signal 0'. See “Giving your program a signal” (page 121).

5.4 Stopping and starting multi-thread programs

When your program has multiple threads (see “Debugging programs with multiple
threads” (page 46)), you can choose whether to set breakpoints on all threads, or on a
particular thread.
break linespec thread threadno, break linespec thread threadno if ...
linespec specifies source lines; there are several
ways of writing them, but the effect is always to specify some source line.
Use the qualifier 'thread threadno' with a breakpoint command to specify that you only want GDB to stop the program when a particular thread reaches this breakpoint. threadno is one of the numeric thread identifiers assigned by GDB, shown in the first column of the 'info threads' display.
If you do not specify 'thread threadno' when you set a breakpoint, the breakpoint applies to all threads of your program.
You can use the thread qualifier on conditional breakpoints as well; in this case, place 'thread threadno' before the breakpoint condition, like this:
((gdb)) break frik.c:13 thread 28 if bartab > lim
5.4 Stopping and starting multi-thread programs 69
Page 70
Whenever your program stops under GDB for any reason, all threads ofexecution stop, not just the current thread. This allows you to examine the overall state of the program, including switching between threads, without worrying that things may change underfoot.
Conversely, whenever you restart the program, all threads start executing. This is true even when single-stepping with commands like step or next.
In particular, GDB cannot single-step all threads in lockstep. Since thread scheduling is up to your debugging target's operating system (not controlled by GDB), other threads may execute more than one statement while the current thread completes a single step. Moreover, in general other threads stop in the middle of a statement, rather than at a clean statement boundary, when the program stops.
You might even find your program stopped in another thread after continuing or even single-stepping. This happens whenever some other thread runs into a breakpoint, a signal, or an exception before the first thread completes whatever you requested.
On some OSes, you can lock the OS scheduler and thus allow only a single thread to run.
set scheduler-locking mode Set the scheduler locking mode. If it is off, then
there is no locking and any thread may run at any time. If on, then only the current thread may run when the inferior is resumed. The step mode optimizesfor single-stepping. It stops other threads from “seizing the prompt” by preempting the current thread while you are stepping. Other threads will only rarely (or never) get a chance to run when you step. They are more likely to run when you 'next' over a function call, and they are completely free to run when you use commands like 'continue', 'until', or 'finish'. However, unless another thread hits a breakpoint during its timeslice, they will never steal the GDB prompt away from the thread that you are debugging.
show scheduler-locking
Display the current scheduler locking mode.
70 Stopping and Continuing
Page 71

6 Examining the Stack

When your program has stopped, the first thing you need to know is where it stopped and how it got there.
Each time your program performs a functioncall, information about the call is generated. The information includes the location of the call in your program, the arguments of the call, and the local variables of the function being called. The information is saved in a block of data called a stack frame. The stack frames are allocated in a region of memory called the call stack.
The GDB commands for examining the stack allow you to view all of this information.

6.1 Stack frames

The call stack is divided up into contiguous pieces called stack frames, or frames for short; each frame is the data associated with one call to one function. The frame contains the arguments given to the function, the local variables, and the address at which the function is executing.
When your program is started, the stack has only one frame, that of the function main. This is called the initial frame or the outermost frame. Each time a function is called, a new frame is made. Each time a function returns, the frame for that function invocation is eliminated. If a function is recursive, there can be many frames for the same function. The frame for the function in which execution is actually occurring is called the innermost frame. This is the most recently created of all the stack frames that still exist.
Inside your program, stack frames are identified by their addresses. A stack frame consists of many bytes, each of which has its own address; each kind of computer has a convention for choosing one byte whose address serves as the address of the frame. Usually this address is kept in a register called the frame pointer register while execution is going on in that frame.
GDB assigns numbers to all existing stack frames, starting with zero for the innermost frame, one for the frame that called it, and so on upward. These numbers do not really exist in your program; they are assigned by GDB to give you a way of designating stack frames in GDB commands.
One of the stack frames is selected by GDB and the GDB commands refer implicitly to the selected frame. In particular, whenever you ask GDB for the value of a variable in your program, the value is found in the selected frame. There are special GDB commands to select whichever frame you are interested in. See “Selecting a frame”
(page 73).
When your program stops, GDB automatically selects the currently executing frame and describes it briefly, similar to the frame command (see “Information about a
frame” (page 74).
6.1 Stack frames 71
Page 72

6.2 Stacks Without frames

Some compilers provide a way to compile functions so that they operate without stack frames. (For example, the gcc option
'-fomit-frame-pointer'
generates functions without a frame.) This is occasionally done with heavily used library functions to save the frame setup time. GDB has limited facilities for dealing with these function invocations. If the innermost function invocation has no stack frame, GDB nevertheless regards it as though it had a separate frame, which is numbered zero as usual, allowing correct tracing of the function call chain. However, GDB has no provision for frameless functions elsewhere in the stack.

6.3 Commands for Examining the Stack

The following commands are used for examining the stack:
frame args
select-frame The select-frame command allows you to move from one stack
Select and print a stack frame. With no argument, prints the selected stack frame. An argument specifies the frame to select. It can be a stack frame number or the address of the frame. With argument, nothing is printed if input is coming from a command file or a user-defined command.
frame to another without printing the frame. This is the silent version of frame.

6.4 Backtraces

A backtrace is a report of the active stack frames instantiated by the execution of a program. It shows one line per frame, for all the active frames, starting with the currently executing frame (frame zero), followed by its caller (frame one), and on up the stack.
The following commands are used for backtrace:
backtrace, bt
backtrace n, bt n Similar, but print only the innermost n frames.
backtrace -n, bt -n Similar, but print only the outermost n frames.
backtrace-other-thread
72 Examining the Stack
Print a backtrace of the entire stack: one line per frame for all frames in the stack.
You can stop the backtrace at any time by typing the system interrupt character, normally C-c.
Print backtrace of all stack frames for a thread with stack pointer SP and program counter PC. This command is useful in cases where the debugger does not support a user thread package fully.
Page 73
The names where and info stack (abbreviated info s) are additional aliases for backtrace.
Each line in the backtrace shows the frame number and the function name. The program counter value is also shown―unless you use set print address off. The backtrace also shows the source file name and line number, as well as the arguments to the function. The program counter value is omitted if it is at the beginning of the code for that line number.
Here is an example of a backtrace. It was made with the command 'bt 3', so it shows the innermost three frames.
#0 m4_traceon (obs=0x24eb0, argc=1, argv=0x2b8c8) at builtin.c:993 #1 0x6e38 in expand_macro (sym=0x2b600) at macro.c:242 #2 0x6840 in expand_token (obs=0x0, t=177664, td=0xf7fffb08) at macro.c:71 (More stack frames follow...)
The display for frame zero does not begin with a program counter value, indicating that your program has stopped at the beginning of the code for line 993 of builtin.c.

6.5 Selecting a frame

Most commands for examining the stack and other data in your program work on whichever stack frame is selected at the moment.
The following commands are used for selecting a stack frame; all of them finish by printing a brief description of the stack frame selected.
frame n, f n Select frame number n. Recall that frame zero is the innermost
(currently executing) frame, frame one is the frame that called the innermost one, and so on. The highest-numbered frame is the one for
main.
frame addr, f addr
Select the frame at address addr. This is useful mainly if the chaining of stack frames has been damaged by a bug, making it impossible for GDB to assign numbers properly to all frames. In addition, this can be useful when your program has multiple stacks and switches between them.
6.5 Selecting a frame 73
Page 74
NOTE:
On the SPARC architecture, frame needs two addresses to select
an arbitrary frame: a frame pointer and a stack pointer.
On the MIPS and Alpha architecture, it needs two addresses: a stack pointer and a program counter.
On the 29k architecture, it needs three addresses: a register stack pointer, a program counter, and a memory stack pointer.
up n Move n frames up the stack. For positive numbers n, this advances
toward the outermost frame, to higher frame numbers, to frames that have existed longer. n defaults to one.
down n Move n frames down the stack. For positive numbers n, this advances
toward the innermost frame, to lower frame numbers, to frames that were created more recently. n defaults to one. You may abbreviate down as do.
All of these commands end by printing two lines of output describing the frame. The first line shows the frame number, the function name, the arguments, and the source file and line number of execution in that frame. The second line shows the text of that source line.
For example:
((gdb)) up #1 0x22f0 in main (argc=1, argv=0xf7fffbf4, env=0xf7fffbfc) at env.c:10 10 read_input_file (argv[i]);
After such a printout, the list command with no arguments prints ten lines centered on the point of execution in the frame. See “Printing source lines” (page 77).
up-silently n, down-silently n
These two commands are variants of up and down, respectively; they differ in that they do their work silently, without causing display of the new frame. They are intended primarily for use in GDB command scripts, where the output might be unnecessary and distracting.

6.6 Information about a frame

The following commands are used to print information about the selected stack frame:
frame, f
74 Examining the Stack
When used without any argument, this command does not change which frame is selected, but prints a brief description of the currently selected stack frame. It can be abbreviated f. With an argument, this command is used to select a stack frame. See “Selecting a frame” (page 73).
Page 75
info frame, info f
This command prints a verbose description of the selected stack frame, including:
the address of the frame
the address of the next frame down (called by this frame)
the address of the next frame up (caller of this frame)
the language in which the source code corresponding to this frame is written
the address of the frame's arguments
the address of the frame's local variables
the program counter saved in it (the address of execution in the caller frame)
which registers were saved in the frame
The verbose description is useful when something has gone wrong that has made the stack format fail to fit the usual conventions.
info frame addr, info f addr
info args
info locals
info catch
Print a verbose description of the frame at address addr, without selecting that frame. The selected frame remains unchanged by this command. This requires the same kind of address (morethan one for some architectures) that you specify in the frame command. See “Selecting a frame” (page 73).
Print the arguments of the selected frame, each on a separate line.
Print the local variables of the selected frame, each on a separate line. These are all variables (declared either static or automatic) accessible at the point of execution of the selected frame.
Print a list of all the exception handlers that are active in the current stack frame at the current point of execution. To see other exception handlers, visit the associated frame (using the up, down, or frame commands); then type info catch. See
“Setting catchpoints” (page 56).
6.6 Information about a frame 75
Page 76
76
Page 77

7 Examining Source Files

GDB can print parts of the source code of your program, since the debugging information recorded in the program tells GDB what source files were used to build it. When your program stops, GDB spontaneously prints the line where it stopped. Likewise, when you select a stack frame (see “Selecting a frame” (page 73)), GDB prints the line where execution in that frame has stopped. You can print other portions of source files by explicit command.
You can invoke GDB from its GNU Emacs interface to view the source code see
Chapter 19 (page 293).

7.1 Printing source lines

To print lines from a source file, use the list command (abbreviated l). By default, ten lines are printed. There are several ways to specify what part of the file you want to print.
The following forms of the list command are used:
list linenum Prints lines centered around line number linenumin the current
source file.
list function Prints lines centered around the beginning offunction function.
list Prints more lines. The list command prints lines following the
lines printed by a previously executed list command. If the command prior to executing a list just printed the stack frame, then the list command only prints the lines around that line.
list-
Prints lines just before the lines last printed.
By default, GDB prints ten source lines with any of these forms of the list command.
The number of lines printed by GDB can be set by the set listsize command. The following two forms are supported:
set listsize count Makes the list command display count source lines
(unless the list argument explicitly specifies some other number).
show listsize Displays the number of lines that list prints.
Repeating a list command with RET discards the argument, so it is equivalent to typing just list. This is more useful than listing the same lines again. An exception is made for an argument of '-'; that argument is preserved in repetition so that each repetition moves up in the source file.
In general, the list command expects you to supply zero, one or two linespecs.
Linespecs specify source lines. There are several ways of writing them, but the most common way is to specify some source line.
7.1 Printing source lines 77
Page 78
The following arguments can be given to the list command:
list linespec Print lines centered around the line specified by linespec.
list first,last Print lines from first to last. Both arguments must be
linespecs.
list, last Print lines ending with last.
list first, Print lines starting with first.
list +
list -
list
A single source line can be specified in the following ways:
number Specifies line number of the current source file. When a
+offset Specifies the line offset lines after the last line printed.
-offset Specifies the line offset lines before the last line printed.
filename:number Specifies line number in the source file filename.
function
filename:function
Print lines just after the lines last printed.
Print lines just before the lines last printed.
As described in the preceding table.
list command has two linespecs, this refers to the same source file as the first linespec.
When used as the second linespec in a list command that has two, this specifies the line offset lines down from the first linespec.
Specifies the line that begins the body of the function function. For example: in C, this is the line with the open brace.
Specifies the line of the open-brace that begins the body of the function function in the file filename. You only need the file name with a function name to avoid ambiguity when there are identically named functions in different source files.
*address Specifies theline containing the program address address.

7.2 Searching source files

There are two commands for searching through the current source file for a regular expression.
forward-search regexp, search regexp
78 Examining Source Files
address may be any expression.
The command 'forward-search regexp' checks each line, starting with one of the following in the last line listed, for a match of the regexp. It lists the line that is found. You can use the synonym 'search
regexp' or abbreviate the command name as fo.
Page 79
reverse-search regexp The command 'reverse-search regexp' checks

7.3 Specifying source directories

Executable programs sometimes do not record the directories of the source files from which they were compiled. Even when they do, the directories can be moved between the compilation and your debugging session. GDB has a list of directories to search for source files; this is called the source path. Each time GDB looks for a source file, it tries all the directories in the list, in the order they are present in the list, until it finds a file with the desired name. Note that the executable search path is not used for this purpose. Neither is the current working directory, unless it happens to be in the source path.
If GDB cannot find a source file in the source path, and the object program records a directory, GDB tries that directory too. If the source path is empty, and there is no record of the compilation directory, GDB looks in the current directory as a last resort.
Whenever you reset or rearrange the source path, GDB clears out any information it has cached about where the source files are located and where each line is in the respective file.
When you start GDB, its source path includes only 'cdir' and 'cwd', in that order.
each line, starting with the one before the last line listed and going backward, for a match for the regexp. It lists the line(s) that is found. You can abbreviate this command as rev.
To add other directories, you can use the directory command.
directory dirname ..., dir dirname ...
directory
Add directory dirname to the front of the source path. Several directory names may be given to this command, separated by ':' (';' on MS-DOS and MS-Windows, where ':' usually appears as part of absolute file names) or a whitespace. You can specify a directory that is already in the source path; this moves it forward, so GDB searches it sooner.
You can use the string '$cdir' to refer to the compilation directory (if one is recorded), and '$cwd' to refer to the current working directory. '$cwd' is not the same as '.'. The former tracks the current working directory as it changes during your GDB session, while the latter is immediately expanded to the current directory at the time you add an entry to the source path.
Reset the source path to empty again. This requires confirmation from the user.
7.3 Specifying source directories 79
Page 80
show directories
If your source path is cluttered with directories that are no longer of interest, GDB can end up detecting the wrong version of the source. To correct this situation, follow these steps:
1. Use directory with no arguments to reset the source path to empty.
2. Use directory with suitable arguments to reinstall the directories you want in
the source path. You can add all the directories in one command.

7.4 Source and machine code

You can use the command info line to map source lines to program addresses (and vice versa), andthe command disassemble to display a range of addresses as machine instructions. When run under GNU Emacs mode, the info line command causes the arrow to point to the line specified. Also, info line prints addresses in symbolic form as well as hex.
info line linespec
For example, we can use info line to discover the location of the object code for the first line of function.
m4_changequote:
Print the source path and display the directories it contains.
Print the starting and ending addresses of the compiled code for source line linespec. You can specify source lines inany of the ways understood by the list command (see “Printing source lines” (page 77)).
((gdb)) info line m4_changequote
Line 895 of "builtin.c" starts at pc 0x634c and ends at 0x6350.
We can also inquire (using *addr as the form for linespec) what source line covers a particular address. For example,
((gdb)) info line *0x63ff Line 926 of "builtin.c" starts at pc 0x63e4 and ends at 0x6404.
After info line, the default address for the x command is changed to the starting address of the line, so that 'x/i' is sufficient to begin examining the machine code (see
Section 8.5 (page 87)). Also, this address is saved as the value of the convenience
variable $_ (see Section 8.9 (page 96)).
disassemble
80 Examining Source Files
This specialized command dumps a range of memory as machine instructions. The default memory range is the function surrounding the program counter of the selected frame. A single argument to this command is a program counter value; GDB dumps the function surrounding this value. Two argumentsspecify a range of addresses (first inclusive, second exclusive) to dump.
Page 81
The following example shows the disassembly of a range of addresses of HP PA-RISC
2.0 code:
((gdb)) disas 0x32c4 0x32e4 Dump of assembler code from 0x32c4 to 0x32e4: 0x32c4 <main+204>: addil 0,dp 0x32c8 <main+208>: ldw 0x22c(sr0,r1),r26 0x32cc <main+212>: ldil 0x3000,r31 0x32d0 <main+216>: ble 0x3f8(sr4,r31) 0x32d4 <main+220>: ldo 0(r31),rp 0x32d8 <main+224>: addil -0x800,dp 0x32dc <main+228>: ldo 0x588(r1),r26 0x32e0 <main+232>: ldil 0x3000,r31 End of assembler dump.
Some architectures have more than one commonly-used set of instruction mnemonics or other syntax.
set disassembly-flavor
instruction-set
Select the instruction set to use when disassembling the program via the disassemble or x/i commands.
Currently this command is only defined for the Intel x86 family. You can set instruction-set to either intel or att. The default is att, the AT&T flavor used bydefault by Unix assemblers for x86-based targets.
7.4 Source and machine code 81
Page 82
82
Page 83

8 Examining Data

The usual way to examine data in your program is with the print command (abbreviated p), or its synonym inspect. It evaluates and prints the value of an expression of the language your program is written in (see Chapter 9 (page 101)).
The following forms of print command are supported:
print expr, print /f expr
print, print /f If you omit expr, GDB displays the last value again (from the
A more low-level way of examining data is with the x command. It examines data in memory at a specified address and prints it in a specified format. See “Examining
memory” (page 87).
If you are interested in information about types, or about how the fields of a struct or a class are declared, use the ptype exp command rather than print. See Chapter 10
(page 115).

8.1 Expressions

print and many other GDB commands accept an expression and compute its value. Any kind of constant, variable or operator defined by the programming language you are using is valid in an expression in GDB. This includes conditional expressions, function calls, casts, and string constants. It unfortunately does not include symbols defined by preprocessor #define commands.
GDB supports array constants in expressions input by the user. The syntax is
{element, element. . .}. For example, you can use the command print {1, 2, 3} to build up an array in memory that calls malloc in the target program.
Because C is so widespread, most of the expressions shown in examples in this manual are in C. See Chapter 9 (page 101), for information on how to use expressions in other languages.
In this section, we discuss operators that you can use in GDB expressions regardless of your programming language.
Casts are supported in all languages, not just in C, because it is so useful to cast a number into a pointer in order to examine a structure at that address in memory.
GDB supportsthese operators, in addition to those common to programming languages:
expr is an expression (in the source language). By default, the value of expr is printed in a format appropriate to its data type; you can choose a different format by specifying '/f', where f is a letter specifying the format; see “Output formats” (page 86).
value history; see “Value history” (page 95)). This allows you to conveniently inspect the same value in an alternative format.
@ '@' is a binary operator for treating parts of memory as arrays. Refer
to See “Artificial arrays” (page 85), for more information.
8.1 Expressions 83
Page 84
:: '::' allows you to specify a variable in terms of the file or function
where it is defined. See “Program variables” (page 84).
{type} addr Refers to an object of type type stored at address addr in memory.
addr may be any expression whose value is an integer or pointer
(but parentheses are required around binary operators, just as in a cast). This construct is allowed regardless of what kind of data is normally supposed to reside at addr.

8.2 Program variables

The most common kind of expression to use is the name of a variable in your program.
Variables in expressions are understood in the selected stack frame (see “Selecting a
frame” (page 73); they must be either:
global (or file-static)
or
visible according to the scope rules of the programming language from the point of execution in that frame
This means that in the function
foo (a) int a; { bar (a); { int b = test (); bar (b); } }
you can examine and use the variable a whenever your program is executing within the function foo, but you can only use or examine the variable b while your program is executing inside the block where b is declared.
However, you can refer to a variable or function whose scope is a single source file even if the current execution point is not in this file. But it is possible to have more than one such variable or function with the same name (in different source files). If that happens, referring to that name has unpredictable effects. If you wish, you can specify a static variable in a particular function or file, using the colon-colon notation:
file::variable function::variable
Here file or function is the name of the context for the static variable. In the case of file names, you can use quotes to make sure GDB parses the file name as a single word. For example, to print a global value of x defined in 'f2.c':
((gdb)) p 'f2.c'::x
84 Examining Data
Page 85
This use of '::' is very rarely in conflict with the very similar use of the same notation in C++. GDB also supports use of the C++ scope resolution operator in GDB expressions.
WARNING! Occasionally, a local variable may appear to have the wrong value at certain points in a function just after entry to a new scope, and just before exit.
You may see this problem when you are stepping by machine instructions. This is because, on most machines, it takes more than one instruction to set up a stack frame (including local variable definitions); if you are stepping by machine instructions, variables may appear to have the wrong values until the stack frame is completely built. On exit, it usually also takesmore than one machine instruction todestroy a stack frame; after you begin stepping through that group of instructions, local variable definitions may be gone.
This may also happen when the compiler does significant optimizations. To be sure of always seeing accurate values, turn o all optimization when compiling.
Another possible effect of compiler optimizations is to optimize unused variables out of existence, or assign variables to registers (as opposed to memory addresses). Depending on the support for such cases offered by the debug info format used by the compiler, GDB might not be able to display values for such local variables. If that happens, GDB will print a message like this:
No symbol "foo" in current context.
To solve such problems, either recompile without optimizations, or use a different debug info format, if the compiler supports several such formats. For example, GCC, the GNU C/C++ compiler usually supports the '-gstabs' option. The '-gstabs' produces debug information in a format that is superior to formats such as COFF. You may be able to use DWARF-2 ('-gdwarf-2'), which is also an effective form for debug info. See “Compiling for debugging” (page 39).

8.3 Artificial arrays

It is often useful to print out several successive objects of the same type in memory; a section of an array, or an array of dynamically determined size for which only a pointer exists in the program.
You can do this by referring to a contiguous span of memory as an artificial array, using the binary operator '@'. The left operand of '@' should be the first element of the desired array and be an individual object. The right operand should be the desired length of the array. The result is an array value whose elements are all of the type of the left argument. The first element is actually the left argument; the second element comes from bytes of memory immediately following those that hold the first element, and so on. Here is an example. If a program says
int *array = (int *) malloc (len * sizeof (int));
you can print the contents of array with
8.3 Artificial arrays 85
Page 86
p *array@len
The left operand of '@' must reside in memory. Array values made with '@' in this way behave just like other arrays in terms of subscripting, and are coerced to pointers when used in expressions. Artificial arrays most often appear in expressions via the value history (see “Value history” (page 95)), after printing one out.
Another way to create an artificial array is to use a cast. This re-interprets a value as if it were an array. The value need not be in memory:
((gdb)) p/x (short[2])0x12345678 $1 = {0x1234, 0x5678}
As a convenience, if you leave the array length out (as in '(type[])value'), GDB calculates the size to fill the value (as 'sizeof(value)/sizeof(type)':
((gdb)) p/x (short[])0x12345678 $2 = {0x1234, 0x5678}
Sometimes the artificial array mechanism is not quite enough; in moderately complex data structures, the elements of interest may not actually be adjacent―for example, if you are interested in the values of pointers in an array. One useful work-around in this situation is to use a convenience variable (See “Convenience variables” (page 96)) as a counter in an expression that prints the first interesting value, and then repeat that expression via RET. For instance, suppose you have an array dtab of pointers to structures, and you are interested in the values of a field fv in each structure. Here is an example of what you might type:
set $i = 0 p dtab[$i++]->fv <RET> <RET> ...

8.4 Output formats

By default, GDB prints a value according to its data type. Sometimes this is not what you want. For example, you might want to print a number in hex, or a pointer in decimal. Or you might want to view data in memory at a certain address as a character string or as an instruction. To do these things, specify an output format when you print a value.
The simplest use of output formats is to say how to print a value already computed. This is done by starting the arguments of the print command with a slash and a format letter. The format letters supported are:
Regard the bits of the value as an integer, and print the integer in hexadecimal.
x
Print as integer in signed decimal.
d
Print as integer in unsigned decimal.
u
Print as integer in octal.
o
86 Examining Data
Page 87
t2Print as integer in binary. The letter 't' stands for “two”2.
Print as an address, both absolute in hexadecimal and as an offset from the nearest
a
preceding symbol.You can use this format used to discover where (in what function) an unknown address is located:
((gdb)) p/a 0x54320 $3 = 0x54320 <_initialize_vx+396>
Regard as an integer and print it as a character constant.
c
Regard the bits of the value as a floating point number and print using typical
f
floating point syntax.
For example, to print the program counter in hex (see “Registers” (page 98)), type
p/x $pc
Note that no space is required before the slash; this is because command names in GDB cannot contain a slash.
To reprint the last value in the value history with a different format, you can use the print command with just a format and no expression. For example, 'p/x' reprints the last value in hex.

8.5 Examining memory

You can use the command x (for “examine”) to examine memory in any of several formats, independent of your program data types.
x/nfu addr,
Use the x command to examine memory.
x addr, x
[n],[ f], and [u] are all optional parameters that specify how much memory to display and how to format it; addr is an expression giving the address where you want to start displaying memory. If you use defaults for nfu, you need not type the slash '/'. Several commands set convenient defaults for addr.
[n], the repeat count
The repeat count is a decimal integer and the default is 1. It specifies how much memory (counting by units u) to display.
[f], the display format
The display format is one of the formats used by print, 's' (null-terminated string), or 'i' (machine instruction). The default is 'x' (hexadecimal) initially. The default changes each time you use either x or print.
[u], the unit size
2. 'b' cannot be used because these format letters are also used with the x command, where 'b' stands for “byte”; see “Examining memory” (page 87).
The unit size is any of
Bytes.
b
Halfwords (two bytes).
h
8.5 Examining memory 87
Page 88
Words (four bytes). This is the initial default.
w
Giant words (eight bytes).
g
Each time you specify a unit size with x, that size becomes the default unit the next time you use x. (For the 's' and 'i' formats, the unit size is ignored and is normally not written.)
addr, starting display address addr is the address where you want GDB to
begin displaying memory. The expression need not have a pointer value (though it may); it is always interpreted as an integer address of a byte of memory. Refer to See “Expressions”(page 83), for more information on expressions. The default for addr is usually just after the last address examined―but several othercommands also set the defaultaddress: info breakpoints (to the address of the last breakpoint listed), info line (to the starting address of a line), and print (if you use it to display a value from memory).
For example, 'x/3uh 0x54320' is a request to display three halfwords (h) of memory, formatted as unsigned decimal integers ('u'), starting at address 0x54320. 'x/4xw $sp' prints the four words ('w') of memory above the stack pointer (here, '$sp'; see “Registers”
(page 98)) in hexadecimal ('x').
Since the letters indicating unit sizes are all distinct from the letters specifying output formats, you do not have to remember whether unit size or format comes first; either order works. The output specifications '4xw' and '4wx' mean exactly the same thing. (However, the count n must come first; 'wx4' does not work.)
Even though the unit size u is ignored for the formats 's' and 'i', you might still want to use a count n; for example, '3i' specifies that you want to see three machine instructions, including any operands. The command disassemble gives an alternative way of inspecting machine instructions; see “Source and machine code” (page 80).
All the defaults for the arguments to x are designed to make it easy to continue scanning memory with minimal specifications each time you use x. For example, after you have inspected three machineinstructions with 'x/3i addr', you can inspect the next seven with just 'x/7'. If you use RET to repeat the x command, the repeat count n is used again; the other arguments default as for successive uses of x.
The addresses and contents printed by the x command are not saved in the value history because there is often too much of them and they would get in the way. Instead, GDB makes these values available for subsequent use in expressions as values of the convenience variables $_ and $__. After an x command, the last address examined is
88 Examining Data
Page 89
available for use in expressions in the convenience variable $_. The contents of that address, as examined, are available in the convenience variable $__.
If the x command has a repeat count, the address and contents saved are from the last memory unit printed; this is not the same as the last address printed if several units were printed on the last line of output.

8.6 Automatic display

If you find that you want to print the value of an expression frequently (to see how it changes), you might want to add it to the automatic display list so that GDB prints its value each time your program stops. Each expression added to the list is given a number to identify it; to remove an expression from the list, you specify that number. The automatic display looks like this:
2: foo = 38 3: bar[5] = (struct hack *) 0x3804
This display shows item numbers, expressions, and their current values. As with displays you request manually using x or print, you can specify the output format you prefer; in fact, display decides whether to use print or x depending on how elaborate your format specification is―it uses x if you specify a unit size, or one of the two formats ('i' and 's') that are only supported by x; otherwise it uses print.
display expr Add the expression expr to the list of expressions to display
each time your program stops. See “Expressions” (page 83).
display does not repeat if you press RET again after using it.
display/fmt expr For fmt specifying only a display format and not a size or
count, add the expression expr to the auto-display list but arrange to display it each time in the specified format fmt. See“Output formats” (page 86).
display/fmt addr For fmt 'i' or 's', or including a unit-size or a number of
units, add the expression addr as a memory address to be examined each time your program stops. Examining means in effect doing 'x/fmt addr'. See “Examining memory”
(page 87).
For example, `display/i $pc' can be helpful, to view the machine instruction about to be executed each time execution stops (`$pc' is a common name for the program counter; see “Registers” (page 98)).
undisplay dnums..., delete display dnums...
Remove item numbers dnums from the list of expressions to display. undisplay does not repeat if you press RET after using it. (Otherwise you would just get the error 'No display number ...'.)
8.6 Automatic display 89
Page 90
disable display dnums... Disable the display of item numbers dnums. A
disabled display item is not printed automatically, but is not forgotten. It may be enabled again later.
enable display dnums... Enable display of item numbers dnums. It
becomes effective once again in auto display of its expression, until you specify otherwise.
display
Display the current values of the expressions on the list, just as is done when your program stops.
info display
Print the list of expressions previously set up to display automatically, each one with its item number, but without showing the values. This includes disabledexpressions, which are marked as such. It also includes expressions which would not be displayed right now because they refer to automatic variables not currently available.
If a display expression refers to local variables, then it does not make sense outside the lexical context for which it was set up. Such an expression is disabled when execution enters a context where one of its variables is not defined. For example, if you give the command display last_char while inside a function with anargument last_char, GDB displays this argument while your program continues to stop inside that function. When it stops elsewhere, where there is no variable last_char, the display is disabled automatically. The next time your program stops where last_char is meaningful, you can enable the display expression again.

8.7 Print settings

GDB provides the following ways to control how arrays, structures, and symbols are printed.
These settings are useful for debugging programs in any language:
set print address, set print address on
90 Examining Data
GDB prints memory addresses showing the location of stack traces, structure values, pointer values, breakpoints, and so forth, even when it also displays the contents of those addresses. The default is on. For example, this is what a stack frame display looks like with set print address on:
((gdb)) f #0 set_quotes (lq=0x34c78 "<<", rq=0x34c88 ">>") at input.c:530 530 if (lquote != def_lquote)
Page 91
set print address off
Do not print addresses when displaying their contents. For example, this is the same stack frame displayed with set print address off:
((gdb)) set print addr off ((gdb)) f #0 set_quotes (lq="<<", rq=">>") at input.c:530 530 if (lquote != def_lquote)
You can use 'set print address off' to eliminate all machine dependent displays from the GDB interface. For example, with print address off, you should get the same text for backtraces on all machines―whether or not they involve pointer arguments.
show print address
Show whether or not addresses are to be printed.
When GDB prints a symbolic address, it normally prints the closest previous symbol plus an offset. If that symbol does not uniquely identify the address (for example, it is a name whose scope is a single source file), you may need to clarify it. One way to do this is with info line. For example 'info line *0x4537'. Alternately, you can set GDB to print the source file and the line number when it prints a symbolic address:
set print symbol-filename on
Tell GDB to print the source file name and line number of a symbol in the symbolic form of an address.
set print symbol-filename off
show print symbol-filename
Do not print source file name and line number of a symbol. This is the default.
Show whether or not GDB will print the source file name and line number of a symbol in the symbolic form of an address.
Another situation where it is helpful to show symbol filenames and line numbers is when disassembling code. GDB shows you the line number and source file that corresponds to each instruction.
Also, you may wish to see the symbolic form only if the address being printed is reasonably close to the closest earlier symbol:
set print max-symbolic-offset
max-offset
Tell GDB to only display the symbolic form of an address if the offset between the closest symbol and the address is less than max-offset. The default is 0, which tells GDB to always print the symbolic form of an address if any symbol precedes it.
show print max-symbolic-offset
Ask how large the maximum offset is that GDB prints in a symbolic address.
8.7 Print settings 91
Page 92
If you have a pointer and you are not sure where it points, try 'set print symbol-filename on'. Then you can determine the name and source file location of the variable where it points, using 'p/a pointer'. This interprets the address in symbolic form. For example, here GDB shows that a variable ptt points at another variable t, defined in 'hi2.c':
((gdb)) set print symbol-filename on ((gdb)) p/a ptt $4 = 0xe008 <t in hi2.c>
WARNING! For pointers that point to a local variable, 'p/a' does not show the symbol name and filename of the referent, even with the appropriate set print options turned on.
Other settings to control how different kinds of objects are printed:
set print array, set print array on
Pretty print arrays. This format is more convenient to read, but uses more space. The default is off.
set print array off
show print array
Return to compressed format for arrays.
Show whether compressed or pretty format is selected for displaying arrays.
set print elements
number-of-elements
Set a limit on how many elements of an array GDB will print. If GDB is printing a large array, it stops printing after it has printed the number of elements set by the set print elements command. This limit also applies to the display of strings. When GDB starts, this limit is set to
200. Setting number-of-elements to zero means that the printing is unlimited.
show print elements
Display the number of elements of a large array that GDB will print. If the number is 0, then the printing is unlimited.
set print null-stop
Cause GDB to stop printing the characters of an array when the first NULL is encountered. This is useful when large arrays actually contain only short strings. The default is off.
set print pretty on
Cause GDB to print structures in an indented format with one member per line, like this:
$1 = { next = 0x0, flags = { sweet = 1, sour = 1
92 Examining Data
Page 93
}, meat = 0x54 "Pork" }
set print pretty off
show print pretty
set print sevenbit-strings on
set print sevenbit-strings off
show print sevenbit-strings
set print union on
set print union off
show print union
Cause GDB to print structures in a compact format, like this:
$1 = {next = 0x0, flags = {sweet = 1, sour = 1}, \ meat = 0x54 "Pork"}
This is the default format.
Show which format GDB is using to print structures.
Print using only seven-bit characters; if this option is set, GDB displays any eight-bit characters (in strings or character values) using the notation \nnn. This setting is best if you are working in English (ASCII) and you use the high-order bit of characters as a marker or “meta” bit.
Print full eight-bit characters. This allows the use of more international character sets, and is the default.
Show whether or not GDB is printing only seven-bit characters.
Tell GDB to print unions which are contained in structures. This is the default setting.
Tell GDB not to print unions which are contained in structures.
Ask GDB whether or not it will print unions which are contained in structures.
For example, given the declarations
typedef enum {Tree, Bug} Species; typedef enum {Big_tree, Acorn, Seedling} Tree_forms; typedef enum {Caterpillar, Cocoon, Butterfly} Bug_forms;
struct thing { Species it; union { Tree_forms tree; Bug_forms bug;
8.7 Print settings 93
Page 94
} form; };
struct thing foo = {Tree, {Acorn}};
with set print union on in effect 'p foo' would print
$1 = {it = Tree, form = {tree = Acorn, bug = Cocoon}}
and with set print union off in effect it would print
$1 = {it = Tree, form = {...}}
These settings are of interest when debugging C++ programs:
set print demangle, set print demangle on
Print C++ names in their source form rather than in the encoded (“mangled”) form passed to the assembler and linker for type-safe linkage. The default is on.
show print demangle
Show whether C++ names are printed in mangled or demangled form.
set print asm-demangle, set print asm-demangle on
Print C++ names in their source form rather than their mangled form, even in assembler code printouts such as instruction disassemblies. The default is off.
show print asm-demangle
Show whether C++ names in assembly listings are printed in mangled or demangled form.
set demangle-style style
Choose among several encoding schemes used by different compilers to represent C++ names.
On HP-UX, WDB automatically chooses the appropriate style.
94 Examining Data
The choices for style currently supported are:
auto
Allow GDB to choose a decoding style by inspecting your program.
gnu
Decode based on the GNU C++ compiler (g++) encoding algorithm.
hp
Decode based on the HP ANSI C++ (aCC) encoding algorithm.
lucid
Decode based on the Lucid C++ compiler (lcc) encoding algorithm.
Page 95
arm
Decode using the algorithm in the C++ Annotated Reference Manual.
WARNING! This setting alone is not sufficient to allow debugging cfront generated executables. GDB would require further enhancementto permit that.
If you omit style, you will see a list of possible formats.
show demangle-style
set print object, set print object on
set print object off
show print object
set print static-members, set print static-members on
set print static-members off
show print static-members
set print vtbl, set print vtbl on
set print vtbl off
show print vtbl
Display the encoding style currently in use for decoding C++ symbols.
When displaying a pointer to an object, identify the actual (derived) type of the object rather than the declared type, using the virtual function table.
Display only the declared type of objects, without reference to the virtual function table. This is the default setting.
Show whether actual or declared object types are displayed.
Print static members when displaying a C++ object. The default is on.
Do not print static members when displaying a C++ object.
Show whether C++ static members are printed, or not.
Pretty print C++ virtual function tables. The default is off. (The vtbl commands do not work on programs compiled with the HP ANSI C++ compiler (aCC).)
Do not pretty print C++ virtual function tables.
Show whether C++ virtual function tables are pretty printed, or not.

8.8 Value history

Values printed by the print command are saved in the GDB value history. This allows you to refer to them in other expressions. Values are kept until the symbol table is
8.8 Value history 95
Page 96
re-read or discarded (for example with the file or symbol-file commands). When the symbol table changes, the value history is discarded, since the values may contain pointers back to the types defined in the symbol table.
The values printed are given history numbers by which you can refer to them. These are a range of integers starting with one. print shows you the history number assigned to a value by printing '$num = ' before the value; here num is the history number.
To refer to any previous value, use '$' followed by the history number of the value. The way print labels its output is designed to remind you of this. Just $ refers to the most recent value in the history, and $$ refers to the value before that. $$n refers to the nth value from the end; $$2 is the value just prior to $$, $$1 is equivalent to $$, and $$0 is equivalent to $.
For example, suppose you have just printed a pointer to a structure and want to see the contents of the structure. It suffices to type
p *$
If you have a chain of structures where the component next points to the next one, you can print the contents of the next one with this:
p *$.next
You can print successive links in the chain by repeating this command using the RET key.
Note that the history records values, not expressions. If the value of x is 4 and you type these commands:
print x set x=5
then the value recorded in the value history by the print command remains 4 even though the value of x has changed.
show values
Print the last ten values in the value history, with their item numbers. This is like 'p $$9' repeated ten times, except that show
values does not change the history.
show values n Print ten history values centered on history item number n.
show values +
Print ten history values following the values last printed. If no more values are available, show values + produces nodisplay.
Pressing RET to repeat show values n has exactly the same effect as 'show values +'.

8.9 Convenience variables

GDB provides convenience variables that you can use within GDB to hold on to a value and refer to it later. These variables exist entirely within GDB. They are not part of your program, and setting a convenience variable has no direct effect on further execution of your program. That is why you can use them freely.
96 Examining Data
Page 97
Convenience variables are prefixed with '$'. Any name preceded by '$' can be used for a convenience variable, unless it is one of the predefined machine-specific register names (see “Registers” (page 98)). (Value history references, in contrast, are numbers preceded by '$'. See “Value history” (page 95).)
You can save a value in a convenience variable with an assignment expression, just as you would set a variable in your program. For example:
set $foo = *object_ptr
would save in $foo the value contained in the object pointed to by object_ptr.
Using a convenience variable for the first time creates it, but its value is void until you assign a new value. You can alter the value with another assignment at any time.
Convenience variables have no fixed types. You can assign a convenience variable any type of value, including structures and arrays, even if that variable already has a value of a different type. The convenience variable, when used as an expression, has the type of its current value.
show convenience
Print a list of convenience variables used so far, and their values. Abbreviated show conv.
A convenient variable can be used as a counter to be incremented or a pointer to be advanced. For example, to print a field from successive elements of an array of structures:
set $i = 0 print bar[$i++]->contents
Repeat that command by typing RET.
Some convenience variables are created automatically by GDB and assigned values.
$_ The variable $_ is automatically set by the x command to the last
address examined (see “Examining memory” (page 87)). Other commands which provide a default address for x to examine, also set
$_ to that address. These commands include info line and info breakpoint. The type of $_ is void * except when set by the x command, in which case it is a pointer to the type of $__.
$__ The variable $__ is automatically set by the x command to the value
found in the last address examined. Its type is chosen to match the format in which the data was printed.
$_exitcode The variable $_exitcode is automatically set to the exit code when
the program being debugged terminates.
On HP-UX systems, if you refer to a function or variable name that begins with a dollar sign, GDB searches for a user or system name first, before it searches for a convenience variable.
8.9 Convenience variables 97
Page 98

8.10 Registers

You can refer to machine register contents, in expressions, as variables with names starting with '$'. The names of registers are different for each machine. Use info
registers to view the names used on your machine.
info registers
info all-registers
info registers regname ...
GDB has four standard register names that are available (in expressions) on most machines―whenever they do not conflict with an architecture's canonical mnemonics for registers. The register names $pc and $sp are used for the program counter register and the stack pointer. $fp is used for a register that contains a pointer to the current stack frame, and $ps is used for a register that contains the processor status. For example, you could print the program counter in hex with
p/x $pc
or print the instruction to be executed next with
x/i $pc
or add four to the stack pointer3with3with
set $sp += 4
Whenever possible, these four standard register names are available on your machine even though the machine has different canonical mnemonics, so long as there is no conflict. The info registers command shows the canonical names. For example, on the SPARC, info registers displays the processor status register as $psr but you can also refer to it as $ps; and on x86-based machines $ps is an alias for the EFLAGS register.
GDB always considers the contents of an ordinary register as an integer when the register is examined in this way. Some machines have special registers which can hold nothing but floating point; these registers are considered to have floating point values. There is no way to refer to the contents of an ordinary register as floating point value (although you can print it as a floating point value with 'print/f $regname').
Print the names and values of all registers except floating-point registers (in the selected stack frame).
Print the names and values of all registers, including floating-point registers.
Print the relativized value of each specified register regname. As discussed in detail below, register values are normally relative to the selected stack frame. regname may be any register name valid on the machine you are using, with or without the initial '$'.
3. This is a way ofremoving oneword from the stack,on machineswhere stacks grow downward in memory
(most machines, nowadays). This assumes that the innermost stack frame is selected; setting $sp is not allowed when other stack frames are selected. To pop entire frames off the stack, regardless of machine architecture, use return; see “Returning from a function” (page 121).
98 Examining Data
Page 99
Some registers have distinct raw and virtual data formats. This means that the data format in which the register contents are saved by the operating system is not the same one that your program normally sees. For example, the registers of the 68881 floating point coprocessor are always saved in “extended” (raw) format, but all C programs expect to work with “double” (virtual) format. In such cases, GDB normally works with the virtual format only (the format that makes sense for your program), but the info registers command prints the data in both formats.
Normally, register values are relative to the selected stack frame (see “Selecting a frame”
(page 73)). This means that you get the value that the register would contain if all stack
frames farther in were exited and their saved registers restored. In order to see the true contents of hardware registers, you must select the innermost frame (with 'frame 0').
However, GDBmust deduce where registers are saved,from the machine code generated by your compiler. If some registers are not saved, or if GDB is unable to locate the saved registers, the selected stack frame makes no difference.

8.11 Printing Floating Point Values

You can print the values of floating-point registers in different formats.
To print both single and double-precision values:
(gdb) info reg $fr5 fr5 (single precision) 10.1444092 fr5
To get the bit pattern, try the following macro:
define pbits set *((float *) $sp)=$arg0 p/x *((int *) $sp) end
This is what the macro produces:
(gdb) pbits $fr6 $1 = 0x4082852d

8.12 Floating point hardware

Depending on the configuration, GDB may be able to give you more information about the status of the floating point hardware.
info float
Display hardware-dependent information about the floating point unit. The exact contents and layout vary depending on the floating point chip. Currently, 'info float' is supported on the ARM and x86 machines.
8.11 Printing Floating Point Values 99
Page 100
100
Loading...