blob: 68ea817d1e2328ab26ae6d8882130f2ab807c119 [file] [log] [blame]
 \input texinfo @c -*-texinfo-*- @c Copyright (C) 1988-1996, 1998-2012 Free Software Foundation, Inc. @c @c %**start of header @c makeinfo ignores cmds prev to setfilename, so its arg cannot make use @c of @set vars. However, you can override filename with makeinfo -o. @setfilename gdb.info @c @include gdb-cfg.texi @c @settitle Debugging with @value{GDBN} @setchapternewpage odd @c %**end of header @iftex @c @smallbook @c @cropmarks @end iftex @finalout @c To avoid file-name clashes between index.html and Index.html, when @c the manual is produced on a Posix host and then moved to a @c case-insensitive filesystem (e.g., MS-Windows), we separate the @c indices into two: Concept Index and all the rest. @syncodeindex ky fn @syncodeindex tp fn @c readline appendices use @vindex, @findex and @ftable, @c annotate.texi and gdbmi use @findex. @syncodeindex vr fn @syncodeindex fn fn @c !!set GDB manual's edition---not the same as GDB version! @c This is updated by GNU Press. @set EDITION Tenth @c !!set GDB edit command default editor @set EDITOR /bin/ex @c THIS MANUAL REQUIRES TEXINFO 4.0 OR LATER. @c This is a dir.info fragment to support semi-automated addition of @c manuals to an info tree. @dircategory Software development @direntry * Gdb: (gdb). The GNU debugger. @end direntry @copying Copyright @copyright{} 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 2011, 2012 Free Software Foundation, Inc. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with the Invariant Sections being Free Software'' and Free Software Needs Free Documentation'', with the Front-Cover Texts being A GNU Manual,'' and with the Back-Cover Texts as in (a) below. (a) The FSF's Back-Cover Text is: You are free to copy and modify this GNU Manual. Buying copies from GNU Press supports the FSF in developing GNU and promoting software freedom.'' @end copying @ifnottex This file documents the @sc{gnu} debugger @value{GDBN}. This is the @value{EDITION} Edition, of @cite{Debugging with @value{GDBN}: the @sc{gnu} Source-Level Debugger} for @value{GDBN} @ifset VERSION_PACKAGE @value{VERSION_PACKAGE} @end ifset Version @value{GDBVN}. @insertcopying @end ifnottex @titlepage @title Debugging with @value{GDBN} @subtitle The @sc{gnu} Source-Level Debugger @sp 1 @subtitle @value{EDITION} Edition, for @value{GDBN} version @value{GDBVN} @ifset VERSION_PACKAGE @sp 1 @subtitle @value{VERSION_PACKAGE} @end ifset @author Richard Stallman, Roland Pesch, Stan Shebs, et al. @page @tex {\parskip=0pt \hfill (Send bugs and comments on @value{GDBN} to @value{BUGURL}.)\par \hfill {\it Debugging with @value{GDBN}}\par \hfill \TeX{}info \texinfoversion\par } @end tex @vskip 0pt plus 1filll Published by the Free Software Foundation @* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA@* ISBN 978-0-9831592-3-0 @* @insertcopying @end titlepage @page @ifnottex @node Top, Summary, (dir), (dir) @top Debugging with @value{GDBN} This file describes @value{GDBN}, the @sc{gnu} symbolic debugger. This is the @value{EDITION} Edition, for @value{GDBN} @ifset VERSION_PACKAGE @value{VERSION_PACKAGE} @end ifset Version @value{GDBVN}. Copyright (C) 1988-2012 Free Software Foundation, Inc. This edition of the GDB manual is dedicated to the memory of Fred Fish. Fred was a long-standing contributor to GDB and to Free software in general. We will miss him. @menu * Summary:: Summary of @value{GDBN} * Sample Session:: A sample @value{GDBN} session * Invocation:: Getting in and out of @value{GDBN} * Commands:: @value{GDBN} commands * Running:: Running programs under @value{GDBN} * Stopping:: Stopping and continuing * Reverse Execution:: Running programs backward * Process Record and Replay:: Recording inferior's execution and replaying it * Stack:: Examining the stack * Source:: Examining source files * Data:: Examining data * Optimized Code:: Debugging optimized code * Macros:: Preprocessor Macros * Tracepoints:: Debugging remote targets non-intrusively * Overlays:: Debugging programs that use overlays * Languages:: Using @value{GDBN} with different languages * Symbols:: Examining the symbol table * Altering:: Altering execution * GDB Files:: @value{GDBN} files * Targets:: Specifying a debugging target * Remote Debugging:: Debugging remote programs * Configurations:: Configuration-specific information * Controlling GDB:: Controlling @value{GDBN} * Extending GDB:: Extending @value{GDBN} * Interpreters:: Command Interpreters * TUI:: @value{GDBN} Text User Interface * Emacs:: Using @value{GDBN} under @sc{gnu} Emacs * GDB/MI:: @value{GDBN}'s Machine Interface. * Annotations:: @value{GDBN}'s annotation interface. * JIT Interface:: Using the JIT debugging interface. * In-Process Agent:: In-Process Agent * GDB Bugs:: Reporting bugs in @value{GDBN} @ifset SYSTEM_READLINE * Command Line Editing: (rluserman). Command Line Editing * Using History Interactively: (history). Using History Interactively @end ifset @ifclear SYSTEM_READLINE * Command Line Editing:: Command Line Editing * Using History Interactively:: Using History Interactively @end ifclear * In Memoriam:: In Memoriam * Formatting Documentation:: How to format and print @value{GDBN} documentation * Installing GDB:: Installing GDB * Maintenance Commands:: Maintenance Commands * Remote Protocol:: GDB Remote Serial Protocol * Agent Expressions:: The GDB Agent Expression Mechanism * Target Descriptions:: How targets can describe themselves to @value{GDBN} * Operating System Information:: Getting additional information from the operating system * Trace File Format:: GDB trace file format * Index Section Format:: .gdb_index section format * Copying:: GNU General Public License says how you can copy and share GDB * GNU Free Documentation License:: The license for this documentation * Concept Index:: Index of @value{GDBN} concepts * Command and Variable Index:: Index of @value{GDBN} commands, variables, functions, and Python data types @end menu @end ifnottex @contents @node Summary @unnumbered Summary of @value{GDBN} The purpose of a debugger such as @value{GDBN} is to allow you to see what is going on inside'' another program while it executes---or what another program was doing at the moment it crashed. @value{GDBN} can do four main kinds of things (plus other things in support of these) to help you catch bugs in the act: @itemize @bullet @item Start your program, specifying anything that might affect its behavior. @item Make your program stop on specified conditions. @item Examine what has happened, when your program has stopped. @item Change things in your program, so you can experiment with correcting the effects of one bug and go on to learn about another. @end itemize You can use @value{GDBN} to debug programs written in C and C@t{++}. For more information, see @ref{Supported Languages,,Supported Languages}. For more information, see @ref{C,,C and C++}. Support for D is partial. For information on D, see @ref{D,,D}. @cindex Modula-2 Support for Modula-2 is partial. For information on Modula-2, see @ref{Modula-2,,Modula-2}. Support for OpenCL C is partial. For information on OpenCL C, see @ref{OpenCL C,,OpenCL C}. @cindex Pascal Debugging Pascal programs which use sets, subranges, file variables, or nested functions does not currently work. @value{GDBN} does not support entering expressions, printing values, or similar features using Pascal syntax. @cindex Fortran @value{GDBN} can be used to debug programs written in Fortran, although it may be necessary to refer to some variables with a trailing underscore. @value{GDBN} can be used to debug programs written in Objective-C, using either the Apple/NeXT or the GNU Objective-C runtime. @menu * Free Software:: Freely redistributable software * Free Documentation:: Free Software Needs Free Documentation * Contributors:: Contributors to GDB @end menu @node Free Software @unnumberedsec Free Software @value{GDBN} is @dfn{free software}, protected by the @sc{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. @node Free Documentation @unnumberedsec Free Software Needs Free Documentation The biggest deficiency in the free software community today is not in the software---it is the lack of good free documentation that we can include with the free software. Many of our most important programs do not come with free reference manuals and free introductory texts. Documentation is an essential part of any software package; when an important free software package does not come with a free manual and a free tutorial, that is a major gap. We have many such gaps today. Consider Perl, for instance. The tutorial manuals that people normally use are non-free. How did this come about? Because the authors of those manuals published them with restrictive terms---no copying, no modification, source files not available---which exclude them from the free software world. That wasn't the first time this sort of thing happened, and it was far from the last. Many times we have heard a GNU user eagerly describe a manual that he is writing, his intended contribution to the community, only to learn that he had ruined everything by signing a publication contract to make it non-free. Free documentation, like free software, is a matter of freedom, not price. The problem with the non-free manual is not that publishers charge a price for printed copies---that in itself is fine. (The Free Software Foundation sells printed copies of manuals, too.) The problem is the restrictions on the use of the manual. Free manuals are available in source code form, and give you permission to copy and modify. Non-free manuals do not allow this. The criteria of freedom for a free manual are roughly the same as for free software. Redistribution (including the normal kinds of commercial redistribution) must be permitted, so that the manual can accompany every copy of the program, both on-line and on paper. Permission for modification of the technical content is crucial too. When people modify the software, adding or changing features, if they are conscientious they will change the manual too---so they can provide accurate and clear documentation for the modified program. A manual that leaves you no choice but to write a new manual to document a changed version of the program is not really available to our community. Some kinds of limits on the way modification is handled are acceptable. For example, requirements to preserve the original author's copyright notice, the distribution terms, or the list of authors, are ok. It is also no problem to require modified versions to include notice that they were modified. Even entire sections that may not be deleted or changed are acceptable, as long as they deal with nontechnical topics (like this one). These kinds of restrictions are acceptable because they don't obstruct the community's normal use of the manual. However, it must be possible to modify all the @emph{technical} content of the manual, and then distribute the result in all the usual media, through all the usual channels. Otherwise, the restrictions obstruct the use of the manual, it is not free, and we need another manual to replace it. Please spread the word about this issue. Our community continues to lose manuals to proprietary publishing. If we spread the word that free software needs free reference manuals and free tutorials, perhaps the next person who wants to contribute by writing documentation will realize, before it is too late, that only free manuals contribute to the free software community. If you are writing documentation, please insist on publishing it under the GNU Free Documentation License or another free documentation license. Remember that this decision requires your approval---you don't have to let the publisher decide. Some commercial publishers will use a free license if you insist, but they will not propose the option; it is up to you to raise the issue and say firmly that this is what you want. If the publisher you are dealing with refuses, please try other publishers. If you're not sure whether a proposed license is free, write to @email{licensing@@gnu.org}. You can encourage commercial publishers to sell more free, copylefted manuals and tutorials by buying them, and particularly by buying copies from the publishers that paid for their writing or for major improvements. Meanwhile, try to avoid buying non-free documentation at all. Check the distribution terms of a manual before you buy it, and insist that whoever seeks your business must respect your freedom. Check the history of the book, and try to reward the publishers that have paid or pay the authors to work on it. The Free Software Foundation maintains a list of free documentation published by other publishers, at @url{http://www.fsf.org/doc/other-free-books.html}. @node Contributors @unnumberedsec Contributors to @value{GDBN} Richard Stallman was the original author of @value{GDBN}, and of many other @sc{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 @file{ChangeLog} in the @value{GDBN} distribution approximates a blow-by-blow account. Changes much prior to version 2.0 are lost in the mists of time. @quotation @emph{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! @end quotation So that they may not regard their many labors as thankless, we particularly thank those who shepherded @value{GDBN} through major releases: Andrew Cagney (releases 6.3, 6.2, 6.1, 6.0, 5.3, 5.2, 5.1 and 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 @sc{gnu} C@t{++} support in @value{GDBN}, with significant additional contributions from Per Bothner and Daniel Berlin. James Clark wrote the @sc{gnu} C@t{++} demangler. Early work on C@t{++} was by Peter TerMaat (who also did much general update work leading to release 3.0). @value{GDBN} 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 and Bradley Davis contributed the ISI Optimum V support. Per Bothner, Noboyuki Hikichi, and Alessandro Forin contributed MIPS support. Jean-Daniel Fekete contributed Sun 386i support. Chris Hanson improved the HP9000 support. Noboyuki Hikichi and Tomoyuki Hasei contributed Sony/News OS 3 support. David Johnson contributed Encore Umax support. 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). Jonathan Stone 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. Marko Mlinar contributed OpenRISC 1000 support. Andreas Schwab contributed M68K @sc{gnu}/Linux support. Rich Schaefer and Peter Schauer helped with support of SunOS shared libraries. Jay Fenlason and Roland McGrath ensured that @value{GDBN} and GAS agree about several machine instruction sets. Patrick Duval, Ted Goldstein, Vikram Koka and Glenn Engel helped develop remote debugging. Intel Corporation, Wind River Systems, AMD, and ARM contributed remote debugging modules for the i960, VxWorks, A29K UDI, and RDI targets, respectively. 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@t{++} overloaded symbols. Hitachi America (now Renesas 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 (now Renesas) 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, Jeff 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 @value{GDBN}. 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.0 (narrow mode), HP's implementation of kernel threads, HP's aC@t{++} compiler, and the Text User Interface (nee Terminal User Interface): Ben Krepp, Richard Title, John Bishop, Susan Macchia, Kathy Mann, Satish Pai, India Paul, Steve Rehrauer, and Elena Zannoni. Kim Haase provided HP-specific information in this manual. DJ Delorie ported @value{GDBN} to MS-DOS, for the DJGPP project. Robert Hoehne made significant contributions to the DJGPP port. Cygnus Solutions has sponsored @value{GDBN} maintenance and much of its development since 1991. Cygnus engineers who have worked on @value{GDBN} fulltime 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, Geoffrey 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. Andrew Cagney, Fernando Nasser, and Elena Zannoni, while working for Cygnus Solutions, implemented the original @sc{gdb/mi} interface. Jim Blandy added support for preprocessor macros, while working for Red Hat. Andrew Cagney designed @value{GDBN}'s architecture vector. Many people including Andrew Cagney, Stephane Carrez, Randolph Chung, Nick Duffek, Richard Henderson, Mark Kettenis, Grace Sainsbury, Kei Sakamoto, Yoshinori Sato, Michael Snyder, Andreas Schwab, Jason Thorpe, Corinna Vinschen, Ulrich Weigand, and Elena Zannoni, helped with the migration of old architectures to this new framework. Andrew Cagney completely re-designed and re-implemented @value{GDBN}'s unwinder framework, this consisting of a fresh new design featuring frame IDs, independent frame sniffers, and the sentinel frame. Mark Kettenis implemented the @sc{dwarf 2} unwinder, Jeff Johnston the libunwind unwinder, and Andrew Cagney the dummy, sentinel, tramp, and trad unwinders. The architecture-specific changes, each involving a complete rewrite of the architecture's frame code, were carried out by Jim Blandy, Joel Brobecker, Kevin Buettner, Andrew Cagney, Stephane Carrez, Randolph Chung, Orjan Friberg, Richard Henderson, Daniel Jacobowitz, Jeff Johnston, Mark Kettenis, Theodore A. Roth, Kei Sakamoto, Yoshinori Sato, Michael Snyder, Corinna Vinschen, and Ulrich Weigand. Christian Zankel, Ross Morley, Bob Wilson, and Maxim Grigoriev from Tensilica, Inc.@: contributed support for Xtensa processors. Others who have worked on the Xtensa port of @value{GDBN} in the past include Steve Tjiang, John Newlin, and Scott Foehner. Michael Eager and staff of Xilinx, Inc., contributed support for the Xilinx MicroBlaze architecture. @node Sample Session @chapter A Sample @value{GDBN} Session You can use this manual at your leisure to read all about @value{GDBN}. However, a handful of commands are enough to get started using the debugger. This chapter illustrates those commands. @iftex In this sample session, we emphasize user input like this: @b{input}, to make it easier to pick out from the surrounding output. @end iftex @c FIXME: this example may not be appropriate for some configs, where @c FIXME...primary interest is in remote use. One of the preliminary versions of @sc{gnu} @code{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 @code{m4} session, we define a macro @code{foo} which expands to @code{0000}; we then use the @code{m4} built-in @code{defn} to define @code{bar} as the same thing. However, when we change the open quote string to @code{} and the close quote string to @code{}, the same procedure fails to define a new synonym @code{baz}: @smallexample $@b{cd gnu/m4}$ @b{./m4} @b{define(foo,0000)} @b{foo} 0000 @b{define(bar,defn(foo'))} @b{bar} 0000 @b{changequote(,)} @b{define(baz,defn(foo))} @b{baz} @b{Ctrl-d} m4: End of input: 0: fatal error: EOF in string @end smallexample @noindent Let us use @value{GDBN} to try to see what is going on. @smallexample $@b{@value{GDBP} m4} @c FIXME: this falsifies the exact text played out, to permit smallbook @c FIXME... format to come out better. @value{GDBN} is free software and you are welcome to distribute copies of it under certain conditions; type "show copying" to see the conditions. There is absolutely no warranty for @value{GDBN}; type "show warranty" for details. @value{GDBN} @value{GDBVN}, Copyright 1999 Free Software Foundation, Inc... (@value{GDBP}) @end smallexample @noindent @value{GDBN} reads only enough symbol data to know where to find the rest when needed; as a result, the first prompt comes up very quickly. We now tell @value{GDBN} to use a narrower display width than usual, so that examples fit in this manual. @smallexample (@value{GDBP}) @b{set width 70} @end smallexample @noindent We need to see how the @code{m4} built-in @code{changequote} works. Having looked at the source, we know the relevant subroutine is @code{m4_changequote}, so we set a breakpoint there with the @value{GDBN} @code{break} command. @smallexample (@value{GDBP}) @b{break m4_changequote} Breakpoint 1 at 0x62f4: file builtin.c, line 879. @end smallexample @noindent Using the @code{run} command, we start @code{m4} running under @value{GDBN} control; as long as control does not reach the @code{m4_changequote} subroutine, the program runs as usual: @smallexample (@value{GDBP}) @b{run} Starting program: /work/Editorial/gdb/gnu/m4/m4 @b{define(foo,0000)} @b{foo} 0000 @end smallexample @noindent To trigger the breakpoint, we call @code{changequote}. @value{GDBN} suspends execution of @code{m4}, displaying information about the context where it stops. @smallexample @b{changequote(,)} Breakpoint 1, m4_changequote (argc=3, argv=0x33c70) at builtin.c:879 879 if (bad_argc(TOKEN_DATA_TEXT(argv[0]),argc,1,3)) @end smallexample @noindent Now we use the command @code{n} (@code{next}) to advance execution to the next line of the current function. @smallexample (@value{GDBP}) @b{n} 882 set_quotes((argc >= 2) ? TOKEN_DATA_TEXT(argv[1])\ : nil, @end smallexample @noindent @code{set_quotes} looks like a promising subroutine. We can go into it by using the command @code{s} (@code{step}) instead of @code{next}. @code{step} goes to the next line to be executed in @emph{any} subroutine, so it steps into @code{set_quotes}. @smallexample (@value{GDBP}) @b{s} set_quotes (lq=0x34c78 "", rq=0x34c88 "") at input.c:530 530 if (lquote != def_lquote) @end smallexample @noindent The display that shows the subroutine where @code{m4} is now suspended (and its arguments) is called a stack frame display. It shows a summary of the stack. We can use the @code{backtrace} command (which can also be spelled @code{bt}), to see where we are in the stack as a whole: the @code{backtrace} command displays a stack frame for each active subroutine. @smallexample (@value{GDBP}) @b{bt} #0 set_quotes (lq=0x34c78 "", rq=0x34c88 "") 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 @end smallexample @noindent We step through a few more lines to see what happens. The first two times, we can use @samp{s}; the next two times we use @code{n} to avoid falling into the @code{xstrdup} subroutine. @smallexample (@value{GDBP}) @b{s} 0x3b5c 532 if (rquote != def_rquote) (@value{GDBP}) @b{s} 0x3b80 535 lquote = (lq == nil || *lq == '\0') ? \ def_lquote : xstrdup(lq); (@value{GDBP}) @b{n} 536 rquote = (rq == nil || *rq == '\0') ? def_rquote\ : xstrdup(rq); (@value{GDBP}) @b{n} 538 len_lquote = strlen(rquote); @end smallexample @noindent The last line displayed looks a little odd; we can examine the variables @code{lquote} and @code{rquote} to see if they are in fact the new left and right quotes we specified. We use the command @code{p} (@code{print}) to see their values. @smallexample (@value{GDBP}) @b{p lquote}$1 = 0x35d40 "" (@value{GDBP}) @b{p rquote} $2 = 0x35d50 "" @end smallexample @noindent @code{lquote} and @code{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 @code{l} (@code{list}) command. @smallexample (@value{GDBP}) @b{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 @end smallexample @noindent Let us step past the two lines that set @code{len_lquote} and @code{len_rquote}, and then examine the values of those variables. @smallexample (@value{GDBP}) @b{n} 539 len_rquote = strlen(lquote); (@value{GDBP}) @b{n} 540 @} (@value{GDBP}) @b{p len_lquote}$3 = 9 (@value{GDBP}) @b{p len_rquote} $4 = 7 @end smallexample @noindent That certainly looks wrong, assuming @code{len_lquote} and @code{len_rquote} are meant to be the lengths of @code{lquote} and @code{rquote} respectively. We can set them to better values using the @code{p} command, since it can print the value of any expression---and that expression can include subroutine calls and assignments. @smallexample (@value{GDBP}) @b{p len_lquote=strlen(lquote)}$5 = 7 (@value{GDBP}) @b{p len_rquote=strlen(rquote)} $6 = 9 @end smallexample @noindent Is that enough to fix the problem of using the new quotes with the @code{m4} built-in @code{defn}? We can allow @code{m4} to continue executing with the @code{c} (@code{continue}) command, and then try the example that caused trouble initially: @smallexample (@value{GDBP}) @b{c} Continuing. @b{define(baz,defn(foo))} baz 0000 @end smallexample @noindent 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 @code{m4} exit by giving it an EOF as input: @smallexample @b{Ctrl-d} Program exited normally. @end smallexample @noindent The message @samp{Program exited normally.} is from @value{GDBN}; it indicates @code{m4} has finished executing. We can end our @value{GDBN} session with the @value{GDBN} @code{quit} command. @smallexample (@value{GDBP}) @b{quit} @end smallexample @node Invocation @chapter Getting In and Out of @value{GDBN} This chapter discusses how to start @value{GDBN}, and how to get out of it. The essentials are: @itemize @bullet @item type @samp{@value{GDBP}} to start @value{GDBN}. @item type @kbd{quit} or @kbd{Ctrl-d} to exit. @end itemize @menu * Invoking GDB:: How to start @value{GDBN} * Quitting GDB:: How to quit @value{GDBN} * Shell Commands:: How to use shell commands inside @value{GDBN} * Logging Output:: How to log @value{GDBN}'s output to a file @end menu @node Invoking GDB @section Invoking @value{GDBN} Invoke @value{GDBN} by running the program @code{@value{GDBP}}. Once started, @value{GDBN} reads commands from the terminal until you tell it to exit. You can also run @code{@value{GDBP}} 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 @value{GDBN} is with one argument, specifying an executable program: @smallexample @value{GDBP} @var{program} @end smallexample @noindent You can also start with both an executable program and a core file specified: @smallexample @value{GDBP} @var{program} @var{core} @end smallexample You can, instead, specify a process ID as a second argument, if you want to debug a running process: @smallexample @value{GDBP} @var{program} 1234 @end smallexample @noindent would attach @value{GDBN} to process @code{1234} (unless you also have a file named @file{1234}; @value{GDBN} does check for a core file first). Taking advantage of the second command-line argument requires a fairly complete operating system; when you use @value{GDBN} 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. @value{GDBN} will warn you if it is unable to attach or to read core dumps. You can optionally have @code{@value{GDBP}} pass any arguments after the executable file to the inferior using @code{--args}. This option stops option processing. @smallexample @value{GDBP} --args gcc -O2 -c foo.c @end smallexample This will cause @code{@value{GDBP}} to debug @code{gcc}, and to set @code{gcc}'s command-line arguments (@pxref{Arguments}) to @samp{-O2 -c foo.c}. You can run @code{@value{GDBP}} without printing the front material, which describes @value{GDBN}'s non-warranty, by specifying @code{-silent}: @smallexample @value{GDBP} -silent @end smallexample @noindent You can further control how @value{GDBN} starts up by using command-line options. @value{GDBN} itself can remind you of the options available. @noindent Type @smallexample @value{GDBP} -help @end smallexample @noindent to display all available options and briefly describe their use (@samp{@value{GDBP} -h} is a shorter equivalent). All options and command line arguments you give are processed in sequential order. The order makes a difference when the @samp{-x} option is used. @menu * File Options:: Choosing files * Mode Options:: Choosing modes * Startup:: What @value{GDBN} does during startup @end menu @node File Options @subsection Choosing Files When @value{GDBN} 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 @samp{-se} and @samp{-c} (or @samp{-p}) options respectively. (@value{GDBN} reads the first argument that does not have an associated option flag as equivalent to the @samp{-se} option followed by that argument; and the second argument that does not have an associated option flag, if any, as equivalent to the @samp{-c}/@samp{-p} option followed by that argument.) If the second argument begins with a decimal digit, @value{GDBN} will first attempt to attach to it as a process, and if that fails, attempt to open it as a corefile. If you have a corefile whose name begins with a digit, you can prevent @value{GDBN} from treating it as a pid by prefixing it with @file{./}, e.g.@: @file{./12345}. If @value{GDBN} 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. @value{GDBN} 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 @samp{--} rather than @samp{-}, though we illustrate the more usual convention.) @c NOTE: the @cindex entries here use double dashes ON PURPOSE. This @c way, both those who look for -foo and --foo in the index, will find @c it. @table @code @item -symbols @var{file} @itemx -s @var{file} @cindex @code{--symbols} @cindex @code{-s} Read symbol table from file @var{file}. @item -exec @var{file} @itemx -e @var{file} @cindex @code{--exec} @cindex @code{-e} Use file @var{file} as the executable file to execute when appropriate, and for examining pure data in conjunction with a core dump. @item -se @var{file} @cindex @code{--se} Read symbol table from file @var{file} and use it as the executable file. @item -core @var{file} @itemx -c @var{file} @cindex @code{--core} @cindex @code{-c} Use file @var{file} as a core dump to examine. @item -pid @var{number} @itemx -p @var{number} @cindex @code{--pid} @cindex @code{-p} Connect to process ID @var{number}, as with the @code{attach} command. @item -command @var{file} @itemx -x @var{file} @cindex @code{--command} @cindex @code{-x} Execute commands from file @var{file}. The contents of this file is evaluated exactly as the @code{source} command would. @xref{Command Files,, Command files}. @item -eval-command @var{command} @itemx -ex @var{command} @cindex @code{--eval-command} @cindex @code{-ex} Execute a single @value{GDBN} command. This option may be used multiple times to call multiple commands. It may also be interleaved with @samp{-command} as required. @smallexample @value{GDBP} -ex 'target sim' -ex 'load' \ -x setbreakpoints -ex 'run' a.out @end smallexample @item -init-command @var{file} @itemx -ix @var{file} @cindex @code{--init-command} @cindex @code{-ix} Execute commands from file @var{file} before loading the inferior (but after loading gdbinit files). @xref{Startup}. @item -init-eval-command @var{command} @itemx -iex @var{command} @cindex @code{--init-eval-command} @cindex @code{-iex} Execute a single @value{GDBN} command before loading the inferior (but after loading gdbinit files). @xref{Startup}. @item -directory @var{directory} @itemx -d @var{directory} @cindex @code{--directory} @cindex @code{-d} Add @var{directory} to the path to search for source and script files. @item -r @itemx -readnow @cindex @code{--readnow} @cindex @code{-r} 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. @end table @node Mode Options @subsection Choosing Modes You can run @value{GDBN} in various alternative modes---for example, in batch mode or quiet mode. @table @code @anchor{-nx} @item -nx @itemx -n @cindex @code{--nx} @cindex @code{-n} Do not execute commands found in any initialization files. Normally, @value{GDBN} executes the commands in these files after all the command options and arguments have been processed. @xref{Command Files,,Command Files}. @item -quiet @itemx -silent @itemx -q @cindex @code{--quiet} @cindex @code{--silent} @cindex @code{-q} Quiet''. Do not print the introductory and copyright messages. These messages are also suppressed in batch mode. @item -batch @cindex @code{--batch} Run in batch mode. Exit with status @code{0} after processing all the command files specified with @samp{-x} (and all commands from initialization files, if not inhibited with @samp{-n}). Exit with nonzero status if an error occurs in executing the @value{GDBN} commands in the command files. Batch mode also disables pagination, sets unlimited terminal width and height @pxref{Screen Size}, and acts as if @kbd{set confirm off} were in effect (@pxref{Messages/Warnings}). Batch mode may be useful for running @value{GDBN} as a filter, for example to download and run a program on another computer; in order to make this more useful, the message @smallexample Program exited normally. @end smallexample @noindent (which is ordinarily issued whenever a program running under @value{GDBN} control terminates) is not issued when running in batch mode. @item -batch-silent @cindex @code{--batch-silent} Run in batch mode exactly like @samp{-batch}, but totally silently. All @value{GDBN} output to @code{stdout} is prevented (@code{stderr} is unaffected). This is much quieter than @samp{-silent} and would be useless for an interactive session. This is particularly useful when using targets that give @samp{Loading section} messages, for example. Note that targets that give their output via @value{GDBN}, as opposed to writing directly to @code{stdout}, will also be made silent. @item -return-child-result @cindex @code{--return-child-result} The return code from @value{GDBN} will be the return code from the child process (the process being debugged), with the following exceptions: @itemize @bullet @item @value{GDBN} exits abnormally. E.g., due to an incorrect argument or an internal error. In this case the exit code is the same as it would have been without @samp{-return-child-result}. @item The user quits with an explicit value. E.g., @samp{quit 1}. @item The child process never runs, or is not allowed to terminate, in which case the exit code will be -1. @end itemize This option is useful in conjunction with @samp{-batch} or @samp{-batch-silent}, when @value{GDBN} is being used as a remote program loader or simulator interface. @item -nowindows @itemx -nw @cindex @code{--nowindows} @cindex @code{-nw} No windows''. If @value{GDBN} comes with a graphical user interface (GUI) built in, then this option tells @value{GDBN} to only use the command-line interface. If no GUI is available, this option has no effect. @item -windows @itemx -w @cindex @code{--windows} @cindex @code{-w} If @value{GDBN} includes a GUI, then this option requires it to be used if possible. @item -cd @var{directory} @cindex @code{--cd} Run @value{GDBN} using @var{directory} as its working directory, instead of the current directory. @item -data-directory @var{directory} @cindex @code{--data-directory} Run @value{GDBN} using @var{directory} as its data directory. The data directory is where @value{GDBN} searches for its auxiliary files. @xref{Data Files}. @item -fullname @itemx -f @cindex @code{--fullname} @cindex @code{-f} @sc{gnu} Emacs sets this option when it runs @value{GDBN} as a subprocess. It tells @value{GDBN} 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 format looks like two @samp{\032} characters, followed by the file name, line number and character position separated by colons, and a newline. The Emacs-to-@value{GDBN} interface program uses the two @samp{\032} characters as a signal to display the source code for the frame. @item -epoch @cindex @code{--epoch} The Epoch Emacs-@value{GDBN} interface sets this option when it runs @value{GDBN} as a subprocess. It tells @value{GDBN} to modify its print routines so as to allow Epoch to display values of expressions in a separate window. @item -annotate @var{level} @cindex @code{--annotate} This option sets the @dfn{annotation level} inside @value{GDBN}. Its effect is identical to using @samp{set annotate @var{level}} (@pxref{Annotations}). The annotation @var{level} controls how much information @value{GDBN} prints 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 @value{GDBN} is run as a subprocess of @sc{gnu} Emacs, level 3 is the maximum annotation suitable for programs that control @value{GDBN}, and level 2 has been deprecated. The annotation mechanism has largely been superseded by @sc{gdb/mi} (@pxref{GDB/MI}). @item --args @cindex @code{--args} Change interpretation of command line so that arguments following the executable file are passed as command line arguments to the inferior. This option stops option processing. @item -baud @var{bps} @itemx -b @var{bps} @cindex @code{--baud} @cindex @code{-b} Set the line speed (baud rate or bits per second) of any serial interface used by @value{GDBN} for remote debugging. @item -l @var{timeout} @cindex @code{-l} Set the timeout (in seconds) of any communication used by @value{GDBN} for remote debugging. @item -tty @var{device} @itemx -t @var{device} @cindex @code{--tty} @cindex @code{-t} Run using @var{device} for your program's standard input and output. @c FIXME: kingdon thinks there is more to -tty. Investigate. @c resolve the situation of these eventually @item -tui @cindex @code{--tui} Activate the @dfn{Text User Interface} when starting. The Text User Interface manages several text windows on the terminal, showing source, assembly, registers and @value{GDBN} command outputs (@pxref{TUI, ,@value{GDBN} Text User Interface}). Do not use this option if you run @value{GDBN} from Emacs (@pxref{Emacs, , Using @value{GDBN} under @sc{gnu} Emacs}). @c @item -xdb @c @cindex @code{--xdb} @c Run in XDB compatibility mode, allowing the use of certain XDB commands. @c For information, see the file @file{xdb_trans.html}, which is usually @c installed in the directory @code{/opt/langtools/wdb/doc} on HP-UX @c systems. @item -interpreter @var{interp} @cindex @code{--interpreter} Use the interpreter @var{interp} for interface with the controlling program or device. This option is meant to be set by programs which communicate with @value{GDBN} using it as a back end. @xref{Interpreters, , Command Interpreters}. @samp{--interpreter=mi} (or @samp{--interpreter=mi2}) causes @value{GDBN} to use the @dfn{@sc{gdb/mi} interface} (@pxref{GDB/MI, , The @sc{gdb/mi} Interface}) included since @value{GDBN} version 6.0. The previous @sc{gdb/mi} interface, included in @value{GDBN} version 5.3 and selected with @samp{--interpreter=mi1}, is deprecated. Earlier @sc{gdb/mi} interfaces are no longer supported. @item -write @cindex @code{--write} Open the executable and core files for both reading and writing. This is equivalent to the @samp{set write on} command inside @value{GDBN} (@pxref{Patching}). @item -statistics @cindex @code{--statistics} This option causes @value{GDBN} to print statistics about time and memory usage after it completes each command and returns to the prompt. @item -version @cindex @code{--version} This option causes @value{GDBN} to print its version number and no-warranty blurb, and exit. @end table @node Startup @subsection What @value{GDBN} Does During Startup @cindex @value{GDBN} startup Here's the description of what @value{GDBN} does during session startup: @enumerate @item Sets up the command interpreter as specified by the command line (@pxref{Mode Options, interpreter}). @item @cindex init file Reads the system-wide @dfn{init file} (if @option{--with-system-gdbinit} was used when building @value{GDBN}; @pxref{System-wide configuration, ,System-wide configuration and settings}) and executes all the commands in that file. @anchor{Home Directory Init File} @item Reads the init file (if any) in your home directory@footnote{On DOS/Windows systems, the home directory is the one pointed to by the @code{HOME} environment variable.} and executes all the commands in that file. @anchor{Option -init-eval-command} @item Executes commands and command files specified by the @samp{-iex} and @samp{-ix} options in their specified order. Usually you should use the @samp{-ex} and @samp{-x} options instead, but this way you can apply settings before @value{GDBN} init files get executed and before inferior gets loaded. @item Processes command line options and operands. @anchor{Init File in the Current Directory during Startup} @item Reads and executes the commands from init file (if any) in the current working directory as long as @samp{set auto-load local-gdbinit} is set to @samp{on} (@pxref{Init File in the Current Directory}). This is only done if the current directory is different from your home directory. Thus, you can have more than one init file, one generic in your home directory, and another, specific to the program you are debugging, in the directory where you invoke @value{GDBN}. @item If the command line specified a program to debug, or a process to attach to, or a core file, @value{GDBN} loads any auto-loaded scripts provided for the program or for its loaded shared libraries. @xref{Auto-loading}. If you wish to disable the auto-loading during startup, you must do something like the following: @smallexample$ gdb -iex "set auto-load python-scripts off" myprogram @end smallexample Option @samp{-ex} does not work because the auto-loading is then turned off too late. @item Executes commands and command files specified by the @samp{-ex} and @samp{-x} options in their specified order. @xref{Command Files}, for more details about @value{GDBN} command files. @item Reads the command history recorded in the @dfn{history file}. @xref{Command History}, for more details about the command history and the files where @value{GDBN} records it. @end enumerate Init files use the same syntax as @dfn{command files} (@pxref{Command Files}) and are processed by @value{GDBN} in the same way. The init file in your home directory can set options (such as @samp{set complaints}) that affect subsequent processing of command line options and operands. Init files are not executed if you use the @samp{-nx} option (@pxref{Mode Options, ,Choosing Modes}). To display the list of init files loaded by gdb at startup, you can use @kbd{gdb --help}. @cindex init file name @cindex @file{.gdbinit} @cindex @file{gdb.ini} The @value{GDBN} init files are normally called @file{.gdbinit}. The DJGPP port of @value{GDBN} uses the name @file{gdb.ini}, due to the limitations of file names imposed by DOS filesystems. The Windows ports of @value{GDBN} use the standard name, but if they find a @file{gdb.ini} file, they warn you about that and suggest to rename the file to the standard name. @node Quitting GDB @section Quitting @value{GDBN} @cindex exiting @value{GDBN} @cindex leaving @value{GDBN} @table @code @kindex quit @r{[}@var{expression}@r{]} @kindex q @r{(@code{quit})} @item quit @r{[}@var{expression}@r{]} @itemx q To exit @value{GDBN}, use the @code{quit} command (abbreviated @code{q}), or type an end-of-file character (usually @kbd{Ctrl-d}). If you do not supply @var{expression}, @value{GDBN} will terminate normally; otherwise it will terminate using the result of @var{expression} as the error code. @end table @cindex interrupt An interrupt (often @kbd{Ctrl-c}) does not exit from @value{GDBN}, but rather terminates the action of any @value{GDBN} command that is in progress and returns to @value{GDBN} command level. It is safe to type the interrupt character at any time because @value{GDBN} does not allow it to take effect until a time when it is safe. If you have been using @value{GDBN} to control an attached process or device, you can release it with the @code{detach} command (@pxref{Attach, ,Debugging an Already-running Process}). @node Shell Commands @section Shell Commands If you need to execute occasional shell commands during your debugging session, there is no need to leave or suspend @value{GDBN}; you can just use the @code{shell} command. @table @code @kindex shell @kindex ! @cindex shell escape @item shell @var{command-string} @itemx !@var{command-string} Invoke a standard shell to execute @var{command-string}. Note that no space is needed between @code{!} and @var{command-string}. If it exists, the environment variable @code{SHELL} determines which shell to run. Otherwise @value{GDBN} uses the default shell (@file{/bin/sh} on Unix systems, @file{COMMAND.COM} on MS-DOS, etc.). @end table The utility @code{make} is often needed in development environments. You do not have to use the @code{shell} command for this purpose in @value{GDBN}: @table @code @kindex make @cindex calling make @item make @var{make-args} Execute the @code{make} program with the specified arguments. This is equivalent to @samp{shell make @var{make-args}}. @end table @node Logging Output @section Logging Output @cindex logging @value{GDBN} output @cindex save @value{GDBN} output to a file You may want to save the output of @value{GDBN} commands to a file. There are several commands to control @value{GDBN}'s logging. @table @code @kindex set logging @item set logging on Enable logging. @item set logging off Disable logging. @cindex logging file name @item set logging file @var{file} Change the name of the current logfile. The default logfile is @file{gdb.txt}. @item set logging overwrite [on|off] By default, @value{GDBN} will append to the logfile. Set @code{overwrite} if you want @code{set logging on} to overwrite the logfile instead. @item set logging redirect [on|off] By default, @value{GDBN} output will go to both the terminal and the logfile. Set @code{redirect} if you want output to go only to the log file. @kindex show logging @item show logging Show the current values of the logging settings. @end table @node Commands @chapter @value{GDBN} Commands You can abbreviate a @value{GDBN} command to the first few letters of the command name, if that abbreviation is unambiguous; and you can repeat certain @value{GDBN} commands by typing just @key{RET}. You can also use the @key{TAB} key to get @value{GDBN} 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). @menu * Command Syntax:: How to give commands to @value{GDBN} * Completion:: Command completion * Help:: How to ask @value{GDBN} for help @end menu @node Command Syntax @section Command Syntax A @value{GDBN} command is a single line of input. There is no limit on how long it can be. It starts with a command name, which is followed by arguments whose meaning depends on the command name. For example, the command @code{step} accepts an argument which is the number of times to step, as in @samp{step 5}. You can also use the @code{step} command with no arguments. Some commands do not allow any arguments. @cindex abbreviation @value{GDBN} command names may always be truncated if that abbreviation is unambiguous. Other possible command abbreviations are listed in the documentation for individual commands. In some cases, even ambiguous abbreviations are allowed; for example, @code{s} is specially defined as equivalent to @code{step} even though there are other commands whose names start with @code{s}. You can test abbreviations by using them as arguments to the @code{help} command. @cindex repeating commands @kindex RET @r{(repeat last command)} A blank line as input to @value{GDBN} (typing just @key{RET}) means to repeat the previous command. Certain commands (for example, @code{run}) will not repeat this way; these are commands whose unintentional repetition might cause trouble and which you are unlikely to want to repeat. User-defined commands can disable this feature; see @ref{Define, dont-repeat}. The @code{list} and @code{x} commands, when you repeat them with @key{RET}, construct new arguments rather than repeating exactly as typed. This permits easy scanning of source or memory. @value{GDBN} can also use @key{RET} in another way: to partition lengthy output, in a way similar to the common utility @code{more} (@pxref{Screen Size,,Screen Size}). Since it is easy to press one @key{RET} too many in this situation, @value{GDBN} disables command repetition after any command that generates this sort of display. @kindex # @r{(a comment)} @cindex comment Any text from a @kbd{#} to the end of the line is a comment; it does nothing. This is useful mainly in command files (@pxref{Command Files,,Command Files}). @cindex repeating command sequences @kindex Ctrl-o @r{(operate-and-get-next)} The @kbd{Ctrl-o} binding is useful for repeating a complex sequence of commands. This command accepts the current line, like @key{RET}, and then fetches the next line relative to the current line from the history for editing. @node Completion @section Command Completion @cindex completion @cindex word completion @value{GDBN} 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 @value{GDBN} commands, @value{GDBN} subcommands, and the names of symbols in your program. Press the @key{TAB} key whenever you want @value{GDBN} to fill out the rest of a word. If there is only one possibility, @value{GDBN} fills in the word, and waits for you to finish the command (or press @key{RET} to enter it). For example, if you type @c FIXME "@key" does not distinguish its argument sufficiently to permit @c complete accuracy in these examples; space introduced for clarity. @c If texinfo enhancements make it unnecessary, it would be nice to @c replace " @key" by "@key" in the following... @smallexample (@value{GDBP}) info bre @key{TAB} @end smallexample @noindent @value{GDBN} fills in the rest of the word @samp{breakpoints}, since that is the only @code{info} subcommand beginning with @samp{bre}: @smallexample (@value{GDBP}) info breakpoints @end smallexample @noindent You can either press @key{RET} at this point, to run the @code{info breakpoints} command, or backspace and enter something else, if @samp{breakpoints} does not look like the command you expected. (If you were sure you wanted @code{info breakpoints} in the first place, you might as well just type @key{RET} immediately after @samp{info bre}, to exploit command abbreviations rather than command completion). If there is more than one possibility for the next word when you press @key{TAB}, @value{GDBN} sounds a bell. You can either supply more characters and try again, or just press @key{TAB} a second time; @value{GDBN} displays all the possible completions for that word. For example, you might want to set a breakpoint on a subroutine whose name begins with @samp{make_}, but when you type @kbd{b make_@key{TAB}} @value{GDBN} just sounds the bell. Typing @key{TAB} again displays all the function names in your program that begin with those characters, for example: @smallexample (@value{GDBP}) b make_ @key{TAB} @exdent @value{GDBN} sounds bell; press @key{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 (@value{GDBP}) b make_ @end smallexample @noindent After displaying the available possibilities, @value{GDBN} copies your partial input (@samp{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 @kbd{M-?} rather than pressing @key{TAB} twice. @kbd{M-?} means @kbd{@key{META} ?}. You can type this either by holding down a key designated as the @key{META} shift on your keyboard (if there is one) while typing @kbd{?}, or as @key{ESC} followed by @kbd{?}. @cindex quotes in commands @cindex completion of quoted strings Sometimes the string you need, while logically a word'', may contain parentheses or other characters that @value{GDBN} normally excludes from its notion of a word. To permit word completion to work in this situation, you may enclose words in @code{'} (single quote marks) in @value{GDBN} commands. The most likely situation where you might need this is in typing the name of a C@t{++} function. This is because C@t{++} 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 @code{name} that takes an @code{int} parameter, @code{name(int)}, or the version that takes a @code{float} parameter, @code{name(float)}. To use the word-completion facilities in this situation, type a single quote @code{'} at the beginning of the function name. This alerts @value{GDBN} that it may need to consider more information than usual when you press @key{TAB} or @kbd{M-?} to request word completion: @smallexample (@value{GDBP}) b 'bubble( @kbd{M-?} bubble(double,double) bubble(int,int) (@value{GDBP}) b 'bubble( @end smallexample In some cases, @value{GDBN} can tell that completing a name requires using quotes. When this happens, @value{GDBN} inserts the quote for you (while completing as much as it can) if you do not type the quote in the first place: @smallexample (@value{GDBP}) b bub @key{TAB} @exdent @value{GDBN} alters your input line to the following, and rings a bell: (@value{GDBP}) b 'bubble( @end smallexample @noindent In general, @value{GDBN} can tell that a quote is needed (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 @ref{C Plus Plus Expressions, ,C@t{++} Expressions}. You can use the command @code{set overload-resolution off} to disable overload resolution; see @ref{Debugging C Plus Plus, ,@value{GDBN} Features for C@t{++}}. @cindex completion of structure field names @cindex structure field name completion @cindex completion of union field names @cindex union field name completion When completing in an expression which looks up a field in a structure, @value{GDBN} also tries@footnote{The completer can be confused by certain kinds of invalid expressions. Also, it only examines the static type of the expression, not the dynamic type.} to limit completions to the field names available in the type of the left-hand-side: @smallexample (@value{GDBP}) p gdb_stdout.@kbd{M-?} magic to_fputs to_rewind to_data to_isatty to_write to_delete to_put to_write_async_safe to_flush to_read @end smallexample @noindent This is because the @code{gdb_stdout} is a variable of the type @code{struct ui_file} that is defined in @value{GDBN} sources as follows: @smallexample struct ui_file @{ int *magic; ui_file_flush_ftype *to_flush; ui_file_write_ftype *to_write; ui_file_write_async_safe_ftype *to_write_async_safe; ui_file_fputs_ftype *to_fputs; ui_file_read_ftype *to_read; ui_file_delete_ftype *to_delete; ui_file_isatty_ftype *to_isatty; ui_file_rewind_ftype *to_rewind; ui_file_put_ftype *to_put; void *to_data; @} @end smallexample @node Help @section Getting Help @cindex online documentation @kindex help You can always ask @value{GDBN} itself for information on its commands, using the command @code{help}. @table @code @kindex h @r{(@code{help})} @item help @itemx h You can use @code{help} (abbreviated @code{h}) with no arguments to display a short list of named classes of commands: @smallexample (@value{GDBP}) 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. (@value{GDBP}) @end smallexample @c the above line break eliminates huge line overfull... @item help @var{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 @code{status}: @smallexample (@value{GDBP}) help status Status inquiries. List of commands: @c Line break in "show" line falsifies real output, but needed @c to fit in smallbook page size. 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. (@value{GDBP}) @end smallexample @item help @var{command} With a command name as @code{help} argument, @value{GDBN} displays a short paragraph on how to use that command. @kindex apropos @item apropos @var{args} The @code{apropos} command searches through all of the @value{GDBN} commands, and their documentation, for the regular expression specified in @var{args}. It prints out all matches found. For example: @smallexample apropos alias @end smallexample @noindent results in: @smallexample @c @group alias -- Define a new command that is an alias of an existing command aliases -- Aliases of other commands d -- Delete some breakpoints or auto-display expressions del -- Delete some breakpoints or auto-display expressions delete -- Delete some breakpoints or auto-display expressions @c @end group @end smallexample @kindex complete @item complete @var{args} The @code{complete @var{args}} command lists all the possible completions for the beginning of a command. Use @var{args} to specify the beginning of the command you want completed. For example: @smallexample complete i @end smallexample @noindent results in: @smallexample @group if ignore info inspect @end group @end smallexample @noindent This is intended for use by @sc{gnu} Emacs. @end table In addition to @code{help}, you can use the @value{GDBN} commands @code{info} and @code{show} to inquire about the state of your program, or the state of @value{GDBN} itself. Each command supports many topics of inquiry; this manual introduces each of them in the appropriate context. The listings under @code{info} and under @code{show} in the Command, Variable, and Function Index point to all the sub-commands. @xref{Command and Variable Index}. @c @group @table @code @kindex info @kindex i @r{(@code{info})} @item info This command (abbreviated @code{i}) is for describing the state of your program. For example, you can show the arguments passed to a function with @code{info args}, list the registers currently in use with @code{info registers}, or list the breakpoints you have set with @code{info breakpoints}. You can get a complete list of the @code{info} sub-commands with @w{@code{help info}}. @kindex set @item set You can assign the result of an expression to an environment variable with @code{set}. For example, you can set the @value{GDBN} prompt to a $-sign with @code{set prompt$}. @kindex show @item show In contrast to @code{info}, @code{show} is for describing the state of @value{GDBN} itself. You can change most of the things you can @code{show}, by using the related command @code{set}; for example, you can control what number system is used for displays with @code{set radix}, or simply inquire which is currently in use with @code{show radix}. @kindex info set To display all the settable parameters and their current values, you can use @code{show} with no arguments; you may also use @code{info set}. Both commands produce the same display. @c FIXME: "info set" violates the rule that "info" is for state of @c FIXME...program. Ck w/ GNU: "info set" to be called something else, @c FIXME...or change desc of rule---eg "state of prog and debugging session"? @end table @c @end group Here are three miscellaneous @code{show} subcommands, all of which are exceptional in lacking corresponding @code{set} commands: @table @code @kindex show version @cindex @value{GDBN} version number @item show version Show what version of @value{GDBN} is running. You should include this information in @value{GDBN} bug-reports. If multiple versions of @value{GDBN} are in use at your site, you may need to determine which version of @value{GDBN} you are running; as @value{GDBN} evolves, new commands are introduced, and old ones may wither away. Also, many system vendors ship variant versions of @value{GDBN}, and there are variant versions of @value{GDBN} in @sc{gnu}/Linux distributions as well. The version number is the same as the one announced when you start @value{GDBN}. @kindex show copying @kindex info copying @cindex display @value{GDBN} copyright @item show copying @itemx info copying Display information about permission for copying @value{GDBN}. @kindex show warranty @kindex info warranty @item show warranty @itemx info warranty Display the @sc{gnu} NO WARRANTY'' statement, or a warranty, if your version of @value{GDBN} comes with one. @end table @node Running @chapter Running Programs Under @value{GDBN} When you run a program under @value{GDBN}, you must first generate debugging information when you compile it. You may start @value{GDBN} 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. @menu * Compilation:: Compiling for debugging * Starting:: Starting your program * Arguments:: Your program's arguments * Environment:: Your program's environment * Working Directory:: Your program's working directory * Input/Output:: Your program's input and output * Attach:: Debugging an already-running process * Kill Process:: Killing the child process * Inferiors and Programs:: Debugging multiple inferiors and programs * Threads:: Debugging programs with multiple threads * Forks:: Debugging forks * Checkpoint/Restart:: Setting a @emph{bookmark} to return to later @end menu @node Compilation @section Compiling for Debugging In order to debug a program effectively, you need to generate debugging information when you compile it. This debugging information is stored in the object file; it describes the data type of each variable or function and the correspondence between source line numbers and addresses in the executable code. To request debugging information, specify the @samp{-g} option when you run the compiler. Programs that are to be shipped to your customers are compiled with optimizations, using the @samp{-O} compiler option. However, some compilers are unable to handle the @samp{-g} and @samp{-O} options together. Using those compilers, you cannot generate optimized executables containing debugging information. @value{NGCC}, the @sc{gnu} C/C@t{++} compiler, supports @samp{-g} with or without @samp{-O}, making it possible to debug optimized code. We recommend that you @emph{always} use @samp{-g} whenever you compile a program. You may think your program is correct, but there is no sense in pushing your luck. For more information, see @ref{Optimized Code}. Older versions of the @sc{gnu} C compiler permitted a variant option @w{@samp{-gg}} for debugging information. @value{GDBN} no longer supports this format; if your @sc{gnu} C compiler has this option, do not use it. @value{GDBN} knows about preprocessor macros and can show you their expansion (@pxref{Macros}). Most compilers do not include information about preprocessor macros in the debugging information if you specify the @option{-g} flag alone. Version 3.1 and later of @value{NGCC}, the @sc{gnu} C compiler, provides macro information if you are using the DWARF debugging format, and specify the option @option{-g3}. @xref{Debugging Options,,Options for Debugging Your Program or GCC, gcc.info, Using the @sc{gnu} Compiler Collection (GCC)}, for more information on @value{NGCC} options affecting debug information. You will have the best debugging experience if you use the latest version of the DWARF debugging format that your compiler supports. DWARF is currently the most expressive and best supported debugging format in @value{GDBN}. @need 2000 @node Starting @section Starting your Program @cindex starting @cindex running @table @code @kindex run @kindex r @r{(@code{run})} @item run @itemx r Use the @code{run} command to start your program under @value{GDBN}. You must first specify the program name (except on VxWorks) with an argument to @value{GDBN} (@pxref{Invocation, ,Getting In and Out of @value{GDBN}}), or by using the @code{file} or @code{exec-file} command (@pxref{Files, ,Commands to Specify Files}). @end table If you are running your program in an execution environment that supports processes, @code{run} creates an inferior process and makes that process run your program. In some environments without processes, @code{run} jumps to the start of your program. Other targets, like @samp{remote}, are always running. If you get an error message like this one: @smallexample The "remote" target does not support "run". Try "help target" or "continue". @end smallexample @noindent then use @code{continue} to run your program. You may need @code{load} first (@pxref{load}). The execution of a program is affected by certain information it receives from its superior. @value{GDBN} provides ways to specify this information, which you must do @emph{before} starting your program. (You can change it after starting your program, but such changes only affect your program the next time you start it.) This information may be divided into four categories: @table @asis @item The @emph{arguments.} Specify the arguments to give your program as the arguments of the @code{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 variable substitution) in describing the arguments. In Unix systems, you can control which shell is used with the @code{SHELL} environment variable. @xref{Arguments, ,Your Program's Arguments}. @item The @emph{environment.} Your program normally inherits its environment from @value{GDBN}, but you can use the @value{GDBN} commands @code{set environment} and @code{unset environment} to change parts of the environment that affect your program. @xref{Environment, ,Your Program's Environment}. @item The @emph{working directory.} Your program inherits its working directory from @value{GDBN}. You can set the @value{GDBN} working directory with the @code{cd} command in @value{GDBN}. @xref{Working Directory, ,Your Program's Working Directory}. @item The @emph{standard input and output.} Your program normally uses the same device for standard input and standard output as @value{GDBN} is using. You can redirect input and output in the @code{run} command line, or you can use the @code{tty} command to set a different device for your program. @xref{Input/Output, ,Your Program's Input and Output}. @cindex pipes @emph{Warning:} While input and output redirection work, you cannot use pipes to pass the output of the program you are debugging to another program; if you attempt this, @value{GDBN} is likely to wind up debugging the wrong program. @end table When you issue the @code{run} command, your program begins to execute immediately. @xref{Stopping, ,Stopping and Continuing}, 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 @code{print} or @code{call} commands. @xref{Data, ,Examining Data}. If the modification time of your symbol file has changed since the last time @value{GDBN} read its symbols, @value{GDBN} discards its symbol table, and reads it again. When it does this, @value{GDBN} tries to retain your current breakpoints. @table @code @kindex start @item start @cindex run to main procedure The name of the main procedure can vary from language to language. With C or C@t{++}, the main procedure name is always @code{main}, but other languages such as Ada do not require a specific name for their main procedure. The debugger provides a convenient way to start the execution of the program and to stop at the beginning of the main procedure, depending on the language used. The @samp{start} command does the equivalent of setting a temporary breakpoint at the beginning of the main procedure and then invoking the @samp{run} command. @cindex elaboration phase Some programs contain an @dfn{elaboration} phase where some startup code is executed before the main procedure is called. This depends on the languages used to write your program. In C@t{++}, for instance, constructors for static and global objects are executed before @code{main} is called. It is therefore possible that the debugger stops before reaching the main procedure. However, the temporary breakpoint will remain to halt execution. Specify the arguments to give to your program as arguments to the @samp{start} command. These arguments will be given verbatim to the underlying @samp{run} command. Note that the same arguments will be reused if no argument is provided during subsequent calls to @samp{start} or @samp{run}. It is sometimes necessary to debug the program during elaboration. In these cases, using the @code{start} command would stop the execution of your program too late, as the program would have already completed the elaboration phase. Under these circumstances, insert breakpoints in your elaboration code before running your program. @kindex set exec-wrapper @item set exec-wrapper @var{wrapper} @itemx show exec-wrapper @itemx unset exec-wrapper When @samp{exec-wrapper} is set, the specified wrapper is used to launch programs for debugging. @value{GDBN} starts your program with a shell command of the form @kbd{exec @var{wrapper} @var{program}}. Quoting is added to @var{program} and its arguments, but not to @var{wrapper}, so you should add quotes if appropriate for your shell. The wrapper runs until it executes your program, and then @value{GDBN} takes control. You can use any program that eventually calls @code{execve} with its arguments as a wrapper. Several standard Unix utilities do this, e.g.@: @code{env} and @code{nohup}. Any Unix shell script ending with @code{exec "$@@"} will also work. For example, you can use @code{env} to pass an environment variable to the debugged program, without setting the variable in your shell's environment: @smallexample (@value{GDBP}) set exec-wrapper env 'LD_PRELOAD=libtest.so' (@value{GDBP}) run @end smallexample This command is available when debugging locally on most targets, excluding @sc{djgpp}, Cygwin, MS Windows, and QNX Neutrino. @kindex set disable-randomization @item set disable-randomization @itemx set disable-randomization on This option (enabled by default in @value{GDBN}) will turn off the native randomization of the virtual address space of the started program. This option is useful for multiple debugging sessions to make the execution better reproducible and memory addresses reusable across debugging sessions. This feature is implemented only on certain targets, including @sc{gnu}/Linux. On @sc{gnu}/Linux you can get the same behavior using @smallexample (@value{GDBP}) set exec-wrapper setarch uname -m -R @end smallexample @item set disable-randomization off Leave the behavior of the started executable unchanged. Some bugs rear their ugly heads only when the program is loaded at certain addresses. If your bug disappears when you run the program under @value{GDBN}, that might be because @value{GDBN} by default disables the address randomization on platforms, such as @sc{gnu}/Linux, which do that for stand-alone programs. Use @kbd{set disable-randomization off} to try to reproduce such elusive bugs. On targets where it is available, virtual address space randomization protects the programs against certain kinds of security attacks. In these cases the attacker needs to know the exact location of a concrete executable code. Randomizing its location makes it impossible to inject jumps misusing a code at its expected addresses. Prelinking shared libraries provides a startup performance advantage but it makes addresses in these libraries predictable for privileged processes by having just unprivileged access at the target system. Reading the shared library binary gives enough information for assembling the malicious code misusing it. Still even a prelinked shared library can get loaded at a new random address just requiring the regular relocation process during the startup. Shared libraries not already prelinked are always loaded at a randomly chosen address. Position independent executables (PIE) contain position independent code similar to the shared libraries and therefore such executables get loaded at a randomly chosen address upon startup. PIE executables always load even already prelinked shared libraries at a random address. You can build such executable using @command{gcc -fPIE -pie}. Heap (malloc storage), stack and custom mmap areas are always placed randomly (as long as the randomization is enabled). @item show disable-randomization Show the current setting of the explicit disable of the native randomization of the virtual address space of the started program. @end table @node Arguments @section Your Program's Arguments @cindex arguments (to your program) The arguments to your program can be specified by the arguments of the @code{run} command. They are passed to a shell, which expands wildcard characters and performs redirection of I/O, and thence to your program. Your @code{SHELL} environment variable (if it exists) specifies what shell @value{GDBN} uses. If you do not define @code{SHELL}, @value{GDBN} uses the default shell (@file{/bin/sh} on Unix). On non-Unix systems, the program is usually invoked directly by @value{GDBN}, 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. @code{run} with no arguments uses the same arguments used by the previous @code{run}, or those set by the @code{set args} command. @table @code @kindex set args @item set args Specify the arguments to be used the next time your program is run. If @code{set args} has no arguments, @code{run} executes your program with no arguments. Once you have run your program with arguments, using @code{set args} before the next @code{run} is the only way to run it again without arguments. @kindex show args @item show args Show the arguments to give your program when it is started. @end table @node Environment @section Your Program's Environment @cindex environment (of your program) The @dfn{environment} consists of a set of environment variables and their values. Environment variables conventionally record such things 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 programs you run. When debugging, it can be useful to try running your program with a modified environment without having to start @value{GDBN} over again. @table @code @kindex path @item path @var{directory} Add @var{directory} to the front of the @code{PATH} environment variable (the search path for executables) that will be passed to your program. The value of @code{PATH} used by @value{GDBN} does not change. You may specify several directory names, separated by whitespace or by a system-dependent separator character (@samp{:} on Unix, @samp{;} on MS-DOS and MS-Windows). If @var{directory} is already in the path, it is moved to the front, so it is searched sooner. You can use the string @samp{$cwd} to refer to whatever is the current working directory at the time @value{GDBN} searches the path. If you use @samp{.} instead, it refers to the directory where you executed the @code{path} command. @value{GDBN} replaces @samp{.} in the @var{directory} argument (with the current path) before adding @var{directory} to the search path. @c 'path' is explicitly nonrepeatable, but RMS points out it is silly to @c document that, since repeating it would be a no-op. @kindex show paths @item show paths Display the list of search paths for executables (the @code{PATH} environment variable). @kindex show environment @item show environment @r{[}@var{varname}@r{]} Print the value of environment variable @var{varname} to be given to your program when it starts. If you do not supply @var{varname}, print the names and values of all environment variables to be given to your program. You can abbreviate @code{environment} as @code{env}. @kindex set environment @item set environment @var{varname} @r{[}=@var{value}@r{]} Set environment variable @var{varname} to @var{value}. The value changes for your program only, not for @value{GDBN} itself. @var{value} may be any string; the values of environment variables are just strings, and any interpretation is supplied by your program itself. The @var{value} parameter is optional; if it is eliminated, the variable is set to a null value. @c "any string" here does not include leading, trailing @c blanks. Gnu asks: does anyone care? For example, this command: @smallexample set env USER = foo @end smallexample @noindent tells the debugged program, when subsequently run, that its user is named @samp{foo}. (The spaces around @samp{=} are used for clarity here; they are not actually required.) @kindex unset environment @item unset environment @var{varname} Remove variable @var{varname} from the environment to be passed to your program. This is different from @samp{set env @var{varname} =}; @code{unset environment} removes the variable from the environment, rather than assigning it an empty value. @end table @emph{Warning:} On Unix systems, @value{GDBN} runs your program using the shell indicated by your @code{SHELL} environment variable if it exists (or @code{/bin/sh} if not). If your @code{SHELL} variable names a shell that runs an initialization file---such as @file{.cshrc} for C-shell, or @file{.bashrc} for BASH---any variables you set in that file affect your program. You may wish to move setting of environment variables to files that are only run when you sign on, such as @file{.login} or @file{.profile}. @node Working Directory @section Your Program's Working Directory @cindex working directory (of your program) Each time you start your program with @code{run}, it inherits its working directory from the current working directory of @value{GDBN}. The @value{GDBN} working directory is initially whatever it inherited from its parent process (typically the shell), but you can specify a new working directory in @value{GDBN} with the @code{cd} command. The @value{GDBN} working directory also serves as a default for the commands that specify files for @value{GDBN} to operate on. @xref{Files, ,Commands to Specify Files}. @table @code @kindex cd @cindex change working directory @item cd @var{directory} Set the @value{GDBN} working directory to @var{directory}. @kindex pwd @item pwd Print the @value{GDBN} working directory. @end table It is generally impossible to find the current working directory of the process being debugged (since a program can change its directory during its run). If you work on a system where @value{GDBN} is configured with the @file{/proc} support, you can use the @code{info proc} command (@pxref{SVR4 Process Information}) to find out the current working directory of the debuggee. @node Input/Output @section Your Program's Input and Output @cindex redirection @cindex i/o @cindex terminal By default, the program you run under @value{GDBN} does input and output to the same terminal that @value{GDBN} uses. @value{GDBN} 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. @table @code @kindex info terminal @item info terminal Displays information recorded by @value{GDBN} about the terminal modes your program is using. @end table You can redirect your program's input and/or output using shell redirection with the @code{run} command. For example, @smallexample run > outfile @end smallexample @noindent starts your program, diverting its output to the file @file{outfile}. @kindex tty @cindex controlling terminal Another way to specify where your program should do input and output is with the @code{tty} command. This command accepts a file name as argument, and causes this file to be the default for future @code{run} commands. It also resets the controlling terminal for the child process, for future @code{run} commands. For example, @smallexample tty /dev/ttyb @end smallexample @noindent directs that processes started with subsequent @code{run} commands default to do input and output on the terminal @file{/dev/ttyb} and have that as their controlling terminal. An explicit redirection in @code{run} overrides the @code{tty} command's effect on the input/output device, but not its effect on the controlling terminal. When you use the @code{tty} command or redirect input in the @code{run} command, only the input @emph{for your program} is affected. The input for @value{GDBN} still comes from your terminal. @code{tty} is an alias for @code{set inferior-tty}. @cindex inferior tty @cindex set inferior controlling terminal You can use the @code{show inferior-tty} command to tell @value{GDBN} to display the name of the terminal that will be used for future runs of your program. @table @code @item set inferior-tty /dev/ttyb @kindex set inferior-tty Set the tty for the program being debugged to /dev/ttyb. @item show inferior-tty @kindex show inferior-tty Show the current tty for the program being debugged. @end table @node Attach @section Debugging an Already-running Process @kindex attach @cindex attach @table @code @item attach @var{process-id} This command attaches to a running process---one that was started outside @value{GDBN}. (@code{info files} shows your active targets.) The command takes as argument a process ID. The usual way to find out the @var{process-id} of a Unix process is with the @code{ps} utility, or with the @samp{jobs -l} shell command. @code{attach} does not repeat if you press @key{RET} a second time after executing the command. @end table To use @code{attach}, your program must be running in an environment which supports processes; for example, @code{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 @code{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 (@pxref{Source Path, ,Specifying Source Directories}). You can also use the @code{file} command to load the program. @xref{Files, ,Commands to Specify Files}. The first thing @value{GDBN} does after arranging to debug the specified process is to stop it. You can examine and modify an attached process with all the @value{GDBN} commands that are ordinarily available when you start processes with @code{run}. You can insert breakpoints; you can step and continue; you can modify storage. If you would rather the process continue running, you may use the @code{continue} command after attaching @value{GDBN} to the process. @table @code @kindex detach @item detach When you have finished debugging the attached process, you can use the @code{detach} command to release it from @value{GDBN} control. Detaching the process continues its execution. After the @code{detach} command, that process and @value{GDBN} become completely independent once more, and you are ready to @code{attach} another process or start one with @code{run}. @code{detach} does not repeat if you press @key{RET} again after executing the command. @end table If you exit @value{GDBN} while you have an attached process, you detach that process. If you use the @code{run} command, you kill that process. By default, @value{GDBN} asks for confirmation if you try to do either of these things; you can control whether or not you need to confirm by using the @code{set confirm} command (@pxref{Messages/Warnings, ,Optional Warnings and Messages}). @node Kill Process @section Killing the Child Process @table @code @kindex kill @item kill Kill the child process in which your program is running under @value{GDBN}. @end table This command is useful if you wish to debug a core dump instead of a running process. @value{GDBN} ignores any core dump file while your program is running. On some operating systems, a program cannot be executed outside @value{GDBN} while you have breakpoints set on it inside @value{GDBN}. You can use the @code{kill} command in this situation to permit running your program outside the debugger. The @code{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 @code{run}, @value{GDBN} notices that the file has changed, and reads the symbol table again (while trying to preserve your current breakpoint settings). @node Inferiors and Programs @section Debugging Multiple Inferiors and Programs @value{GDBN} lets you run and debug multiple programs in a single session. In addition, @value{GDBN} on some systems may let you run several programs simultaneously (otherwise you have to exit from one before starting another). In the most general case, you can have multiple threads of execution in each of multiple processes, launched from multiple executables. @cindex inferior @value{GDBN} represents the state of each program execution with an object called an @dfn{inferior}. An inferior typically corresponds to a process, but is more general and applies also to targets that do not have processes. Inferiors may be created before a process runs, and may be retained after a process exits. Inferiors have unique identifiers that are different from process ids. Usually each inferior will also have its own distinct address space, although some embedded targets may have several inferiors running in different parts of a single address space. Each inferior may in turn have multiple threads running in it. To find out what inferiors exist at any moment, use @w{@code{info inferiors}}: @table @code @kindex info inferiors @item info inferiors Print a list of all inferiors currently being managed by @value{GDBN}. @value{GDBN} displays for each inferior (in this order): @enumerate @item the inferior number assigned by @value{GDBN} @item the target system's inferior identifier @item the name of the executable the inferior is running. @end enumerate @noindent An asterisk @samp{*} preceding the @value{GDBN} inferior number indicates the current inferior. For example, @end table @c end table here to get a little more width for example @smallexample (@value{GDBP}) info inferiors Num Description Executable 2 process 2307 hello * 1 process 3401 goodbye @end smallexample To switch focus between inferiors, use the @code{inferior} command: @table @code @kindex inferior @var{infno} @item inferior @var{infno} Make inferior number @var{infno} the current inferior. The argument @var{infno} is the inferior number assigned by @value{GDBN}, as shown in the first field of the @samp{info inferiors} display. @end table You can get multiple executables into a debugging session via the @code{add-inferior} and @w{@code{clone-inferior}} commands. On some systems @value{GDBN} can add inferiors to the debug session automatically by following calls to @code{fork} and @code{exec}. To remove inferiors from the debugging session use the @w{@code{remove-inferiors}} command. @table @code @kindex add-inferior @item add-inferior [ -copies @var{n} ] [ -exec @var{executable} ] Adds @var{n} inferiors to be run using @var{executable} as the executable. @var{n} defaults to 1. If no executable is specified, the inferiors begins empty, with no program. You can still assign or change the program assigned to the inferior at any time by using the @code{file} command with the executable name as its argument. @kindex clone-inferior @item clone-inferior [ -copies @var{n} ] [ @var{infno} ] Adds @var{n} inferiors ready to execute the same program as inferior @var{infno}. @var{n} defaults to 1. @var{infno} defaults to the number of the current inferior. This is a convenient command when you want to run another instance of the inferior you are debugging. @smallexample (@value{GDBP}) info inferiors Num Description Executable * 1 process 29964 helloworld (@value{GDBP}) clone-inferior Added inferior 2. 1 inferiors added. (@value{GDBP}) info inferiors Num Description Executable 2 helloworld * 1 process 29964 helloworld @end smallexample You can now simply switch focus to inferior 2 and run it. @kindex remove-inferiors @item remove-inferiors @var{infno}@dots{} Removes the inferior or inferiors @var{infno}@dots{}. It is not possible to remove an inferior that is running with this command. For those, use the @code{kill} or @code{detach} command first. @end table To quit debugging one of the running inferiors that is not the current inferior, you can either detach from it by using the @w{@code{detach inferior}} command (allowing it to run independently), or kill it using the @w{@code{kill inferiors}} command: @table @code @kindex detach inferiors @var{infno}@dots{} @item detach inferior @var{infno}@dots{} Detach from the inferior or inferiors identified by @value{GDBN} inferior number(s) @var{infno}@dots{}. Note that the inferior's entry still stays on the list of inferiors shown by @code{info inferiors}, but its Description will show @samp{}. @kindex kill inferiors @var{infno}@dots{} @item kill inferiors @var{infno}@dots{} Kill the inferior or inferiors identified by @value{GDBN} inferior number(s) @var{infno}@dots{}. Note that the inferior's entry still stays on the list of inferiors shown by @code{info inferiors}, but its Description will show @samp{}. @end table After the successful completion of a command such as @code{detach}, @code{detach inferiors}, @code{kill} or @code{kill inferiors}, or after a normal process exit, the inferior is still valid and listed with @code{info inferiors}, ready to be restarted. To be notified when inferiors are started or exit under @value{GDBN}'s control use @w{@code{set print inferior-events}}: @table @code @kindex set print inferior-events @cindex print messages on inferior start and exit @item set print inferior-events @itemx set print inferior-events on @itemx set print inferior-events off The @code{set print inferior-events} command allows you to enable or disable printing of messages when @value{GDBN} notices that new inferiors have started or that inferiors have exited or have been detached. By default, these messages will not be printed. @kindex show print inferior-events @item show print inferior-events Show whether messages will be printed when @value{GDBN} detects that inferiors have started, exited or have been detached. @end table Many commands will work the same with multiple programs as with a single program: e.g., @code{print myglobal} will simply display the value of @code{myglobal} in the current inferior. Occasionaly, when debugging @value{GDBN} itself, it may be useful to get more info about the relationship of inferiors, programs, address spaces in a debug session. You can do that with the @w{@code{maint info program-spaces}} command. @table @code @kindex maint info program-spaces @item maint info program-spaces Print a list of all program spaces currently being managed by @value{GDBN}. @value{GDBN} displays for each program space (in this order): @enumerate @item the program space number assigned by @value{GDBN} @item the name of the executable loaded into the program space, with e.g., the @code{file} command. @end enumerate @noindent An asterisk @samp{*} preceding the @value{GDBN} program space number indicates the current program space. In addition, below each program space line, @value{GDBN} prints extra information that isn't suitable to display in tabular form. For example, the list of inferiors bound to the program space. @smallexample (@value{GDBP}) maint info program-spaces Id Executable 2 goodbye Bound inferiors: ID 1 (process 21561) * 1 hello @end smallexample Here we can see that no inferior is running the program @code{hello}, while @code{process 21561} is running the program @code{goodbye}. On some targets, it is possible that multiple inferiors are bound to the same program space. The most common example is that of debugging both the parent and child processes of a @code{vfork} call. For example, @smallexample (@value{GDBP}) maint info program-spaces Id Executable * 1 vfork-test Bound inferiors: ID 2 (process 18050), ID 1 (process 18045) @end smallexample Here, both inferior 2 and inferior 1 are running in the same program space as a result of inferior 1 having executed a @code{vfork} call. @end table @node Threads @section Debugging Programs with Multiple Threads @cindex threads of execution @cindex multiple threads @cindex switching threads In some operating systems, such as HP-UX and Solaris, a single program may have more than one @dfn{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 perhaps private memory. @value{GDBN} provides these facilities for debugging multi-thread programs: @itemize @bullet @item automatic notification of new threads @item @samp{thread @var{threadno}}, a command to switch among threads @item @samp{info threads}, a command to inquire about existing threads @item @samp{thread apply [@var{threadno}] [@var{all}] @var{args}}, a command to apply a command to a list of threads @item thread-specific breakpoints @item @samp{set print thread-events}, which controls printing of messages on thread start and exit. @item @samp{set libthread-db-search-path @var{path}}, which lets the user specify which @code{libthread_db} to use if the default choice isn't compatible with the program. @end itemize @quotation @emph{Warning:} These facilities are not yet available on every @value{GDBN} configuration where the operating system supports threads. If your @value{GDBN} does not support threads, these commands have no effect. For example, a system without thread support shows no output from @samp{info threads}, and always rejects the @code{thread} command, like this: @smallexample (@value{GDBP}) info threads (@value{GDBP}) thread 1 Thread ID 1 not known. Use the "info threads" command to see the IDs of currently known threads. @end smallexample @c FIXME to implementors: how hard would it be to say "sorry, this GDB @c doesn't support threads"? @end quotation @cindex focus of debugging @cindex current thread The @value{GDBN} thread debugging facility allows you to observe all threads while your program runs---but whenever @value{GDBN} takes control, one thread in particular is always the focus of debugging. This thread is called the @dfn{current thread}. Debugging commands show program information from the perspective of the current thread. @cindex @code{New} @var{systag} message @cindex thread identifier (system) @c FIXME-implementors!! It would be more helpful if the [New...] message @c included GDB's numeric thread handle, so you could just go to that @c thread without first checking info threads'. Whenever @value{GDBN} detects a new thread in your program, it displays the target system's identification for the thread with a message in the form @samp{[New @var{systag}]}. @var{systag} is a thread identifier whose form varies depending on the particular system. For example, on @sc{gnu}/Linux, you might see @smallexample [New Thread 0x41e02940 (LWP 25582)] @end smallexample @noindent when @value{GDBN} notices a new thread. In contrast, on an SGI system, the @var{systag} is simply something like @samp{process 368}, with no further qualifier. @c FIXME!! (1) Does the [New...] message appear even for the very first @c thread of a program, or does it only appear for the @c second---i.e.@: when it becomes obvious we have a multithread @c program? @c (2) *Is* there necessarily a first thread always? Or do some @c multithread systems permit starting a program with multiple @c threads ab initio? @cindex thread number @cindex thread identifier (GDB) For debugging purposes, @value{GDBN} associates its own thread number---always a single integer---with each thread in your program. @table @code @kindex info threads @item info threads @r{[}@var{id}@dots{}@r{]} Display a summary of all threads currently in your program. Optional argument @var{id}@dots{} is one or more thread ids separated by spaces, and means to print information only about the specified thread or threads. @value{GDBN} displays for each thread (in this order): @enumerate @item the thread number assigned by @value{GDBN} @item the target system's thread identifier (@var{systag}) @item the thread's name, if one is known. A thread can either be named by the user (see @code{thread name}, below), or, in some cases, by the program itself. @item the current stack frame summary for that thread @end enumerate @noindent An asterisk @samp{*} to the left of the @value{GDBN} thread number indicates the current thread. For example, @end table @c end table here to get a little more width for example @smallexample (@value{GDBP}) info threads Id Target Id Frame 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 @end smallexample On Solaris, you can display more information about user threads with a Solaris-specific command: @table @code @item maint info sol-threads @kindex maint info sol-threads @cindex thread info (Solaris) Display info on Solaris user threads. @end table @table @code @kindex thread @var{threadno} @item thread @var{threadno} Make thread number @var{threadno} the current thread. The command argument @var{threadno} is the internal @value{GDBN} thread number, as shown in the first field of the @samp{info threads} display. @value{GDBN} responds by displaying the system identifier of the thread you selected, and its current stack frame summary: @smallexample (@value{GDBP}) thread 2 [Switching to thread 2 (Thread 0xb7fdab70 (LWP 12747))] #0 some_function (ignore=0x0) at example.c:8 8 printf ("hello\n"); @end smallexample @noindent As with the @samp{[New @dots{}]} message, the form of the text after @samp{Switching to} depends on your system's conventions for identifying threads. @vindex $_thread@r{, convenience variable} The debugger convenience variable @samp{$_thread} contains the number of the current thread. You may find this useful in writing breakpoint conditional expressions, command scripts, and so forth. See @xref{Convenience Vars,, Convenience Variables}, for general information on convenience variables. @kindex thread apply @cindex apply command to several threads @item thread apply [@var{threadno} | all] @var{command} The @code{thread apply} command allows you to apply the named @var{command} to one or more threads. Specify the numbers of the threads that you want affected with the command argument @var{threadno}. It can be a single thread number, one of the numbers shown in the first field of the @samp{info threads} display; or it could be a range of thread numbers, as in @code{2-4}. To apply a command to all threads, type @kbd{thread apply all @var{command}}. @kindex thread name @cindex name a thread @item thread name [@var{name}] This command assigns a name to the current thread. If no argument is given, any existing user-specified name is removed. The thread name appears in the @samp{info threads} display. On some systems, such as @sc{gnu}/Linux, @value{GDBN} is able to determine the name of the thread as given by the OS. On these systems, a name specified with @samp{thread name} will override the system-give name, and removing the user-specified name will cause @value{GDBN} to once again display the system-specified name. @kindex thread find @cindex search for a thread @item thread find [@var{regexp}] Search for and display thread ids whose name or @var{systag} matches the supplied regular expression. As well as being the complement to the @samp{thread name} command, this command also allows you to identify a thread by its target @var{systag}. For instance, on @sc{gnu}/Linux, the target @var{systag} is the LWP id. @smallexample (@value{GDBN}) thread find 26688 Thread 4 has target id 'Thread 0x41e02940 (LWP 26688)' (@value{GDBN}) info thread 4 Id Target Id Frame 4 Thread 0x41e02940 (LWP 26688) 0x00000031ca6cd372 in select () @end smallexample @kindex set print thread-events @cindex print messages on thread start and exit @item set print thread-events @itemx set print thread-events on @itemx set print thread-events off The @code{set print thread-events} command allows you to enable or disable printing of messages when @value{GDBN} notices that new threads have started or that threads have exited. By default, these messages will be printed if detection of these events is supported by the target. Note that these messages cannot be disabled on all targets. @kindex show print thread-events @item show print thread-events Show whether messages will be printed when @value{GDBN} detects that threads have started and exited. @end table @xref{Thread Stops,,Stopping and Starting Multi-thread Programs}, for more information about how @value{GDBN} behaves when you stop and start programs with multiple threads. @xref{Set Watchpoints,,Setting Watchpoints}, for information about watchpoints in programs with multiple threads. @anchor{set libthread-db-search-path} @table @code @kindex set libthread-db-search-path @cindex search path for @code{libthread_db} @item set libthread-db-search-path @r{[}@var{path}@r{]} If this variable is set, @var{path} is a colon-separated list of directories @value{GDBN} will use to search for @code{libthread_db}. If you omit @var{path}, @samp{libthread-db-search-path} will be reset to its default value (@code{$sdir:$pdir} on @sc{gnu}/Linux and Solaris systems). Internally, the default value comes from the @code{LIBTHREAD_DB_SEARCH_PATH} macro. On @sc{gnu}/Linux and Solaris systems, @value{GDBN} uses a helper'' @code{libthread_db} library to obtain information about threads in the inferior process. @value{GDBN} will use @samp{libthread-db-search-path} to find @code{libthread_db}. @value{GDBN} also consults first if inferior specific thread debugging library loading is enabled by @samp{set auto-load libthread-db} (@pxref{libthread_db.so.1 file}). A special entry @samp{$sdir} for @samp{libthread-db-search-path} refers to the default system directories that are normally searched for loading shared libraries. The @samp{$sdir} entry is the only kind not needing to be enabled by @samp{set auto-load libthread-db} (@pxref{libthread_db.so.1 file}). A special entry @samp{$pdir} for @samp{libthread-db-search-path} refers to the directory from which @code{libpthread} was loaded in the inferior process. For any @code{libthread_db} library @value{GDBN} finds in above directories, @value{GDBN} attempts to initialize it with the current inferior process. If this initialization fails (which could happen because of a version mismatch between @code{libthread_db} and @code{libpthread}), @value{GDBN} will unload @code{libthread_db}, and continue with the next directory. If none of @code{libthread_db} libraries initialize successfully, @value{GDBN} will issue a warning and thread debugging will be disabled. Setting @code{libthread-db-search-path} is currently implemented only on some platforms. @kindex show libthread-db-search-path @item show libthread-db-search-path Display current libthread_db search path. @kindex set debug libthread-db @kindex show debug libthread-db @cindex debugging @code{libthread_db} @item set debug libthread-db @itemx show debug libthread-db Turns on or off display of @code{libthread_db}-related events. Use @code{1} to enable, @code{0} to disable. @end table @node Forks @section Debugging Forks @cindex fork, debugging programs which call @cindex multiple processes @cindex processes, multiple On most systems, @value{GDBN} has no special support for debugging programs which create additional processes using the @code{fork} function. When a program forks, @value{GDBN} 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 @code{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 @code{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 don't want to run @value{GDBN} on the child. While the child is sleeping, use the @code{ps} program to get its process ID. Then tell @value{GDBN} (a new invocation of @value{GDBN} if you are also debugging the parent process) to attach to the child process (@pxref{Attach}). From that point on you can debug the child process just like any other process which you attached to. On some systems, @value{GDBN} provides support for debugging programs that create additional processes using the @code{fork} or @code{vfork} functions. Currently, the only platforms with this feature are HP-UX (11.x and later only?) and @sc{gnu}/Linux (kernel version 2.5.60 and later). By default, when a program forks, @value{GDBN} 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 @w{@code{set follow-fork-mode}}. @table @code @kindex set follow-fork-mode @item set follow-fork-mode @var{mode} Set the debugger response to a program call of @code{fork} or @code{vfork}. A call to @code{fork} or @code{vfork} creates a new process. The @var{mode} argument can be: @table @code @item parent The original process is debugged after a fork. The child process runs unimpeded. This is the default. @item child The new process is debugged after a fork. The parent process runs unimpeded. @end table @kindex show follow-fork-mode @item show follow-fork-mode Display the current debugger response to a @code{fork} or @code{vfork} call. @end table @cindex debugging multiple processes On Linux, if you want to debug both the parent and child processes, use the command @w{@code{set detach-on-fork}}. @table @code @kindex set detach-on-fork @item set detach-on-fork @var{mode} Tells gdb whether to detach one of the processes after a fork, or retain debugger control over them both. @table @code @item on The child process (or parent process, depending on the value of @code{follow-fork-mode}) will be detached and allowed to run independently. This is the default. @item off Both processes will be held under the control of @value{GDBN}. One process (child or parent, depending on the value of @code{follow-fork-mode}) is debugged as usual, while the other is held suspended. @end table @kindex show detach-on-fork @item show detach-on-fork Show whether detach-on-fork mode is on/off. @end table If you choose to set @samp{detach-on-fork} mode off, then @value{GDBN} will retain control of all forked processes (including nested forks). You can list the forked processes under the control of @value{GDBN} by using the @w{@code{info inferiors}} command, and switch from one fork to another by using the @code{inferior} command (@pxref{Inferiors and Programs, ,Debugging Multiple Inferiors and Programs}). To quit debugging one of the forked processes, you can either detach from it by using the @w{@code{detach inferiors}} command (allowing it to run independently), or kill it using the @w{@code{kill inferiors}} command. @xref{Inferiors and Programs, ,Debugging Multiple Inferiors and Programs}. If you ask to debug a child process and a @code{vfork} is followed by an @code{exec}, @value{GDBN} executes the new target up to the first breakpoint in the new target. If you have a breakpoint set on @code{main} in your original program, the breakpoint will also be set on the child process's @code{main}. On some systems, when a child process is spawned by @code{vfork}, you cannot debug the child or parent until an @code{exec} call completes. If you issue a @code{run} command to @value{GDBN} after an @code{exec} call executes, the new target restarts. To restart the parent process, use the @code{file} command with the parent executable name as its argument. By default, after an @code{exec} call executes, @value{GDBN} discards the symbols of the previous executable image. You can change this behaviour with the @w{@code{set follow-exec-mode}} command. @table @code @kindex set follow-exec-mode @item set follow-exec-mode @var{mode} Set debugger response to a program call of @code{exec}. An @code{exec} call replaces the program image of a process. @code{follow-exec-mode} can be: @table @code @item new @value{GDBN} creates a new inferior and rebinds the process to this new inferior. The program the process was running before the @code{exec} call can be restarted afterwards by restarting the original inferior. For example: @smallexample (@value{GDBP}) info inferiors (gdb) info inferior Id Description Executable * 1 prog1 (@value{GDBP}) run process 12020 is executing new program: prog2 Program exited normally. (@value{GDBP}) info inferiors Id Description Executable * 2 prog2 1 prog1 @end smallexample @item same @value{GDBN} keeps the process bound to the same inferior. The new executable image replaces the previous executable loaded in the inferior. Restarting the inferior after the @code{exec} call, with e.g., the @code{run} command, restarts the executable the process was running after the @code{exec} call. This is the default mode. For example: @smallexample (@value{GDBP}) info inferiors Id Description Executable * 1 prog1 (@value{GDBP}) run process 12020 is executing new program: prog2 Program exited normally. (@value{GDBP}) info inferiors Id Description Executable * 1 prog2 @end smallexample @end table @end table You can use the @code{catch} command to make @value{GDBN} stop whenever a @code{fork}, @code{vfork}, or @code{exec} call is made. @xref{Set Catchpoints, ,Setting Catchpoints}. @node Checkpoint/Restart @section Setting a @emph{Bookmark} to Return to Later @cindex checkpoint @cindex restart @cindex bookmark @cindex snapshot of a process @cindex rewind program state On certain operating systems@footnote{Currently, only @sc{gnu}/Linux.}, @value{GDBN} is able to save a @dfn{snapshot} of a program's state, called a @dfn{checkpoint}, and come back to it later. Returning to a checkpoint effectively undoes everything that has happened in the program since the @code{checkpoint} was saved. This includes changes in memory, registers, and even (within some limits) system state. Effectively, it is like going back in time to the moment when the checkpoint was saved. Thus, if you're stepping thru a program and you think you're getting close to the point where things go wrong, you can save a checkpoint. Then, if you accidentally go too far and miss the critical statement, instead of having to restart your program from the beginning, you can just go back to the checkpoint and start again from there. This can be especially useful if it takes a lot of time or steps to reach the point where you think the bug occurs. To use the @code{checkpoint}/@code{restart} method of debugging: @table @code @kindex checkpoint @item checkpoint Save a snapshot of the debugged program's current execution state. The @code{checkpoint} command takes no arguments, but each checkpoint is assigned a small integer id, similar to a breakpoint id. @kindex info checkpoints @item info checkpoints List the checkpoints that have been saved in the current debugging session. For each checkpoint, the following information will be listed: @table @code @item Checkpoint ID @item Process ID @item Code Address @item Source line, or label @end table @kindex restart @var{checkpoint-id} @item restart @var{checkpoint-id} Restore the program state that was saved as checkpoint number @var{checkpoint-id}. All program variables, registers, stack frames etc.@: will be returned to the values that they had when the checkpoint was saved. In essence, gdb will wind back the clock'' to the point in time when the checkpoint was saved. Note that breakpoints, @value{GDBN} variables, command history etc. are not affected by restoring a checkpoint. In general, a checkpoint only restores things that reside in the program being debugged, not in the debugger. @kindex delete checkpoint @var{checkpoint-id} @item delete checkpoint @var{checkpoint-id} Delete the previously-saved checkpoint identified by @var{checkpoint-id}. @end table Returning to a previously saved checkpoint will restore the user state of the program being debugged, plus a significant subset of the system (OS) state, including file pointers. It won't un-write'' data from a file, but it will rewind the file pointer to the previous location, so that the previously written data can be overwritten. For files opened in read mode, the pointer will also be restored so that the previously read data can be read again. Of course, characters that have been sent to a printer (or other external device) cannot be snatched back'', and characters received from eg.@: a serial device can be removed from internal program buffers, but they cannot be pushed back'' into the serial pipeline, ready to be received again. Similarly, the actual contents of files that have been changed cannot be restored (at this time). However, within those constraints, you actually can rewind'' your program to a previously saved point in time, and begin debugging it again --- and you can change the course of events so as to debug a different execution path this time. @cindex checkpoints and process id Finally, there is one bit of internal program state that will be different when you return to a checkpoint --- the program's process id. Each checkpoint will have a unique process id (or @var{pid}), and each will be different from the program's original @var{pid}. If your program has saved a local copy of its process id, this could potentially pose a problem. @subsection A Non-obvious Benefit of Using Checkpoints On some systems such as @sc{gnu}/Linux, address space randomization is performed on new processes for security reasons. This makes it difficult or impossible to set a breakpoint, or watchpoint, on an absolute address if you have to restart the program, since the absolute location of a symbol will change from one execution to the next. A checkpoint, however, is an @emph{identical} copy of a process. Therefore if you create a checkpoint at (eg.@:) the start of main, and simply return to that checkpoint instead of restarting the process, you can avoid the effects of address randomization and your symbols will all stay in the same place. @node Stopping @chapter Stopping and Continuing The principal purposes of using a debugger are so that you can stop your program before it terminates; or so that, if your program runs into trouble, you can investigate and find out why. Inside @value{GDBN}, your program may stop for any of several reasons, such as a signal, a breakpoint, or reaching a new line after a @value{GDBN} command such as @code{step}. You may then examine and change variables, set new breakpoints or remove old ones, and then continue execution. Usually, the messages shown by @value{GDBN} provide ample explanation of the status of your program---but you can also explicitly request this information at any time. @table @code @kindex info program @item info program Display information about the status of your program: whether it is running or not, what process it is, and why it stopped. @end table @menu * Breakpoints:: Breakpoints, watchpoints, and catchpoints * Continuing and Stepping:: Resuming execution * Skipping Over Functions and Files:: Skipping over functions and files * Signals:: Signals * Thread Stops:: Stopping and starting multi-thread programs @end menu @node Breakpoints @section Breakpoints, Watchpoints, and Catchpoints @cindex breakpoints A @dfn{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 breakpoints with the @code{break} command and its variants (@pxref{Set Breaks, ,Setting Breakpoints}), to specify the place where your program should stop by line number, function name or exact address in the program. On some systems, you can set breakpoints in shared libraries before the executable is run. There is a minor limitation on HP-UX systems: you must wait until the executable is run in order to set breakpoints in shared library routines that are not called directly by the program (for example, routines that are arguments in a @code{pthread_create} call). @cindex watchpoints @cindex data breakpoints @cindex memory tracing @cindex breakpoint on memory address @cindex breakpoint on variable modification A @dfn{watchpoint} is a special breakpoint that stops your program when the value of an expression changes. The expression may be a value of a variable, or it could involve values of one or more variables combined by operators, such as @samp{a + b}. This is sometimes called @dfn{data breakpoints}. You must use a different command to set watchpoints (@pxref{Set Watchpoints, ,Setting Watchpoints}), but aside from that, you can manage a watchpoint like any other breakpoint: you enable, disable, and delete both breakpoints and watchpoints using the same commands. You can arrange to have values from your program displayed automatically whenever @value{GDBN} stops at a breakpoint. @xref{Auto Display,, Automatic Display}. @cindex catchpoints @cindex breakpoint on events A @dfn{catchpoint} is another special breakpoint that stops your program when a certain kind of event occurs, such as the throwing of a C@t{++} exception or the loading of a library. As with watchpoints, you use a different command to set a catchpoint (@pxref{Set Catchpoints, ,Setting Catchpoints}), but aside from that, you can manage a catchpoint like any other breakpoint. (To stop when your program receives a signal, use the @code{handle} command; see @ref{Signals, ,Signals}.) @cindex breakpoint numbers @cindex numbers for breakpoints @value{GDBN} 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 @dfn{enabled} or @dfn{disabled}; if disabled, it has no effect on your program until you enable it again. @cindex breakpoint ranges @cindex ranges of breakpoints Some @value{GDBN} commands accept a range of breakpoints on which to operate. A breakpoint range is either a single breakpoint number, like @samp{5}, or two such numbers, in increasing order, separated by a hyphen, like @samp{5-7}. When a breakpoint range is given to a command, all breakpoints in that range are operated on. @menu * Set Breaks:: Setting breakpoints * Set Watchpoints:: Setting watchpoints * Set Catchpoints:: Setting catchpoints * Delete Breaks:: Deleting breakpoints * Disabling:: Disabling breakpoints * Conditions:: Break conditions * Break Commands:: Breakpoint command lists * Dynamic Printf:: Dynamic printf * Save Breakpoints:: How to save breakpoints in a file * Static Probe Points:: Listing static probe points * Error in Breakpoints:: Cannot insert breakpoints'' * Breakpoint-related Warnings:: Breakpoint address adjusted...'' @end menu @node Set Breaks @subsection Setting Breakpoints @c FIXME LMB what does GDB do if no code on line of breakpt? @c consider in particular declaration with/without initialization. @c @c FIXME 2 is there stuff on this already? break at fun start, already init? @kindex break @kindex b @r{(@code{break})} @vindex$bpnum@r{, convenience variable} @cindex latest breakpoint Breakpoints are set with the @code{break} command (abbreviated @code{b}). The debugger convenience variable @samp{$bpnum} records the number of the breakpoint you've set most recently; see @ref{Convenience Vars,, Convenience Variables}, for a discussion of what you can do with convenience variables. @table @code @item break @var{location} Set a breakpoint at the given @var{location}, which can specify a function name, a line number, or an address of an instruction. (@xref{Specify Location}, for a list of all the possible ways to specify a @var{location}.) The breakpoint will stop your program just before it executes any of the code in the specified @var{location}. When using source languages that permit overloading of symbols, such as C@t{++}, a function name may refer to more than one possible place to break. @xref{Ambiguous Expressions,,Ambiguous Expressions}, for a discussion of that situation. It is also possible to insert a breakpoint that will stop the program only if a specific thread (@pxref{Thread-Specific Breakpoints}) or a specific task (@pxref{Ada Tasks}) hits that breakpoint. @item break When called without any arguments, @code{break} sets a breakpoint at the next instruction to be executed in the selected stack frame (@pxref{Stack, ,Examining the Stack}). 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 @code{finish} command in the frame inside the selected frame---except that @code{finish} does not leave an active breakpoint. If you use @code{break} without an argument in the innermost frame, @value{GDBN} stops the next time it reaches the current location; this may be useful inside loops. @value{GDBN} 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. @item break @dots{} if @var{cond} Set a breakpoint with condition @var{cond}; evaluate the expression @var{cond} each time the breakpoint is reached, and stop only if the value is nonzero---that is, if @var{cond} evaluates as true. @samp{@dots{}} stands for one of the possible arguments described above (or no argument) specifying where to break. @xref{Conditions, ,Break Conditions}, for more information on breakpoint conditions. @kindex tbreak @item tbreak @var{args} Set a breakpoint enabled only for one stop. @var{args} are the same as for the @code{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. @xref{Disabling, ,Disabling Breakpoints}. @kindex hbreak @cindex hardware breakpoints @item hbreak @var{args} Set a hardware-assisted breakpoint. @var{args} are the same as for the @code{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 be used with the new trap-generation provided by SPARClite DSU and most 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 @value{GDBN} will reject this command if more than two are used. Delete or disable unused hardware breakpoints before setting new ones (@pxref{Disabling, ,Disabling Breakpoints}). @xref{Conditions, ,Break Conditions}. For remote targets, you can restrict the number of hardware breakpoints @value{GDBN} will use, see @ref{set remote hardware-breakpoint-limit}. @kindex thbreak @item thbreak @var{args} Set a hardware-assisted breakpoint enabled only for one stop. @var{args} are the same as for the @code{hbreak} command and the breakpoint is set in the same way. However, like the @code{tbreak} command, the breakpoint is automatically deleted after the first time your program stops there. Also, like the @code{hbreak} command, the breakpoint requires hardware support and some target hardware may not have this support. @xref{Disabling, ,Disabling Breakpoints}. See also @ref{Conditions, ,Break Conditions}. @kindex rbreak @cindex regular expression @cindex breakpoints at functions matching a regexp @cindex set breakpoints in many functions @item rbreak @var{regex} Set breakpoints on all functions matching the regular expression @var{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 @code{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 @file{grep}. Note that this is different from the syntax used by shells, so for instance @code{foo*} matches all functions that include an @code{fo} followed by zero or more @code{o}s. There is an implicit @code{.*} leading and trailing the regular expression you supply, so to match only functions that begin with @code{foo}, use @code{^foo}. @cindex non-member C@t{++} functions, set breakpoint in When debugging C@t{++} programs, @code{rbreak} is useful for setting breakpoints on overloaded functions that are not members of any special classes. @cindex set breakpoints on all functions The @code{rbreak} command can be used to set breakpoints in @strong{all} the functions in a program, like this: @smallexample (@value{GDBP}) rbreak . @end smallexample @item rbreak @var{file}:@var{regex} If @code{rbreak} is called with a filename qualification, it limits the search for functions matching the given regular expression to the specified @var{file}. This can be used, for example, to set breakpoints on every function in a given file: @smallexample (@value{GDBP}) rbreak file.c:. @end smallexample The colon separating the filename qualifier from the regex may optionally be surrounded by spaces. @kindex info breakpoints @cindex @code{$_} and @code{info breakpoints} @item info breakpoints @r{[}@var{n}@dots{}@r{]} @itemx info break @r{[}@var{n}@dots{}@r{]} Print a table of all breakpoints, watchpoints, and catchpoints set and not deleted. Optional argument @var{n} means print information only about the specified breakpoint(s) (or watchpoint(s) or catchpoint(s)). For each breakpoint, following columns are printed: @table @emph @item Breakpoint Numbers @item Type Breakpoint, watchpoint, or catchpoint. @item Disposition Whether the breakpoint is marked to be disabled or deleted when hit. @item Enabled or Disabled Enabled breakpoints are marked with @samp{y}. @samp{n} marks breakpoints that are not enabled. @item Address Where the breakpoint is in your program, as a memory address. For a pending breakpoint whose address is not yet known, this field will contain @samp{}. Such breakpoint won't fire until a shared library that has the symbol or line referred by breakpoint is loaded. See below for details. A breakpoint with several locations will have @samp{} in this field---see below for details. @item What Where the breakpoint is in the source for your program, as a file and line number. For a pending breakpoint, the original string passed to the breakpoint command will be listed as it cannot be resolved until the appropriate shared library is loaded in the future. @end table @noindent If a breakpoint is conditional, there are two evaluation modes: host'' and target''. If mode is host'', breakpoint condition evaluation is done by @value{GDBN} on the host's side. If it is target'', then the condition is evaluated by the target. The @code{info break} command shows the condition on the line following the affected breakpoint, together with its condition evaluation mode in between parentheses. Breakpoint commands, if any, are listed after that. A pending breakpoint is allowed to have a condition specified for it. The condition is not parsed for validity until a shared library is loaded that allows the pending breakpoint to resolve to a valid location. @noindent @code{info break} with a breakpoint number @var{n} as argument lists only that breakpoint. The convenience variable @code{\$_} and the default examining-address for the @code{x} command are set to the address of the last breakpoint listed (@pxref{Memory, ,Examining Memory}). @noindent @code{info break} displays a count of the number of times the breakpoint has been hit. This is especially useful in conjunction with the @code{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. @noindent For a breakpoints with an enable count (xref) greater than 1, @code{info break} also displays that count. @end table @value{GDBN} 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 (@pxref{Conditions, ,Break Conditions}). @cindex multiple locations, breakpoints @cindex breakpoints, multiple locations It is possible that a breakpoint corresponds to several locations in your program. Examples of this situation are: @itemize @bullet @item Multiple functions in the program may have the same name. @item For a C@t{++} constructor, the @value{NGCC} compiler generates several instances of the function body, used in different cases. @item For a C@t{++} template function, a given line in the function can correspond to any number of instantiations. @item For an inlined function, a given source line can correspond to several places where that function is inlined. @end itemize In all those cases, @value{GDBN} will insert a breakpoint at all the relevant locations. A breakpoint with multiple locations is displayed in the breakpoint table using several rows---one header row, followed by one row for each breakpoint location. The header row has @samp{} in the address column. The rows for individual locations contain the actual addresses for locations, and show the functions to which those locations belong. The number column for a location is of the form @var{breakpoint-number}.@var{location-number}. For example: @smallexample Num Type Disp Enb Address What 1 breakpoint keep y stop only if i==1 breakpoint already hit 1 time 1.1 y 0x080486a2 in void foo() at t.cc:8 1.2 y 0x080486ca in void foo() at t.cc:8 @end smallexample Each location can be individually enabled or disabled by passing @var{breakpoint-number}.@var{location-number} as argument to the @code{enable} and @code{disable} commands. Note that you cannot delete the individual locations from the list, you can only delete the entire list of locations that belong to their parent breakpoint (with the @kbd{delete @var{num}} command, where @var{num} is the number of the parent breakpoint, 1 in the above example). Disabling or enabling the parent breakpoint (@pxref{Disabling}) affects all of the locations that belong to that breakpoint. @cindex pending breakpoints It's quite common to have a breakpoint inside a shared library. Shared libraries can be loaded and unloaded explicitly, and possibly repeatedly, as the program is executed. To support this use case, @value{GDBN} updates breakpoint locations whenever any shared library is loaded or unloaded. Typically, you would set a breakpoint in a shared library at the beginning of your debugging session, when the library is not loaded, and when the symbols from the library are not available. When you try to set breakpoint, @value{GDBN} will ask you if you want to set a so called @dfn{pending breakpoint}---breakpoint whose address is not yet resolved. After the program is run, whenever a new shared library is loaded, @value{GDBN} reevaluates all the breakpoints. When a newly loaded shared library contains the symbol or line referred to by some pending breakpoint, that breakpoint is resolved and becomes an ordinary breakpoint. When a library is unloaded, all breakpoints that refer to its symbols or source lines become pending again. This logic works for breakpoints with multiple locations, too. For example, if you have a breakpoint in a C@t{++} template function, and a newly loaded shared library has an instantiation of that template, a new location is added to the list of locations for the breakpoint. Except for having unresolved address, pending breakpoints do not differ from regular breakpoints. You can set conditions or commands, enable and disable them and perform other breakpoint operations. @value{GDBN} provides some additional commands for controlling what