Debugging with GDB The gnu Source-Level Debugger HP Eighteenth Edition, for GDB February 2008 Richard Stallman, Roland Pesch, Stan Shebs, et al.
(Send bugs and comments on GDB to bug-gdb@gnu.org with copy to wdb-help@cup.hp.com ) Debugging with GDB TEXinfo 2003-02-03.16 Copyright c 2008 Free Software Foundation, Inc. Published by the Free Software Foundation 59 Temple Place - Suite 330, Boston, MA 02111-1307 USA ISBN 1-882114-77-9 Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.
i Table of Contents Summary of GDB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Free software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Contributors to GDB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 1 A Sample GDB Session . . . . . . . . . . . . . . . . . . . . 5 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 1.10 2 2.2 2.3 Invoking GDB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
ii 5 Debugging with GDB Stopping and Continuing . . . . . . . . . . . . . . . . . . 33 5.1 5.2 5.3 5.4 6 Stack frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Stacks Without frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Commands for Examining the Stack . . . . . . . . . . . . . . . . . . . . . Backtraces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Selecting a frame . . . . . . . . . .
iii 9 Using GDB with Different Languages . . . . . . 79 9.1 9.2 9.3 9.4 Switching between source languages . . . . . . . . . . . . . . . . . . . . . 9.1.1 List of filename extensions and languages . . . . . . . . 9.1.2 Setting the working language . . . . . . . . . . . . . . . . . . . 9.1.3 Having GDB infer the source language . . . . . . . . . . Displaying the language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Type and range checking. . . . . . . . . . . . . . . . . . . . . . . .
iv 14 Debugging with GDB HP-UX Configuration-Specific Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 14.1 14.2 Summary of HP Enhancements to GDB . . . . . . . . . . . . . . . 113 HP-UX dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 14.2.1 Linker Dependencies . . . . . . . . . . . . . . . . . . . . . . . . . 116 14.2.2 Dependent Standard Library Routines for Run Time Checking . . . . . . . . . . . . . . . . . . . . . . . .
v 14.11 14.10.8.1 Stop when freeing unallocated or deallocated blocks . . . . . . . . . . . . . . . . . . . . . . . 147 14.10.8.2 Stop when freeing a block if bad writes occurred outside block boundary . . . . . . . . . . 147 14.10.8.3 Stop when a specified block address is allocated or deallocated . . . . . . . . . . . . . . . . . . 147 14.10.8.4 Scramble previous memory contents at malloc/free calls . . . . . . . . . . . . . . . . . . . . . . . . . 148 14.10.8.
vi Debugging with GDB 14.12 Debugging MPI Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . 163 14.13 Debugging multiple processes ( programs with fork and vfork calls) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164 14.13.1 Ask mode for set follow-fork-mode . . . . . . . . 164 14.13.2 serial mode for set follow-fork-mode . . . . . . . 164 14.13.3 Support for showing unwind info. . . . . . . . . . . . . 164 14.13.4 Printing CFM and PFS registers. . . .
vii 14.21.4 Support for 64-bit Java, C, aC++ stack unwinding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178 14.21.5 Enhanced support for C++ templates . . . . . . . . . 179 14.21.6 Support for __fpreg data type on IPF . . . . . . . 180 14.21.7 Support for Complex variables in HP C . . . . . 180 14.21.8 Support for debugging namespaces . . . . . . . . . . . 180 14.21.9 Command for evaluating the address of an expression . . . . . . . . . . . . . . . . . . .
viii Debugging with GDB 14.31 14.32 15 The HP-UX Terminal User Interface. . . . . 199 15.1 15.2 15.3 15.4 15.5 15.6 15.7 15.8 15.9 16 14.30.2 Additional support for command line calls in a stripped executable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195 14.30.2.1 For 32-bit applications: . . . . . . . . . . . . . 195 14.30.2.2 For 64-bit applications . . . . . . . . . . . . . 195 14.30.3 Support for debugging stripped binaries . . . . . . 196 14.30.3.
ix 16.2.6 Assertion control commands . . . . . . . . . . . . . . . . . . 225 16.2.7 Record and playback commands . . . . . . . . . . . . . . 225 16.2.8 Macro facility commands . . . . . . . . . . . . . . . . . . . . . 226 16.2.9 Signal control commands . . . . . . . . . . . . . . . . . . . . . 226 16.2.10 Miscellaneous commands . . . . . . . . . . . . . . . . . . . . 227 16.3 XDB data formats and HP WDB equivalents . . . . . . . . . . . 228 16.4 XDB location syntax and HP WDB equivalents . . . . . . . .
x 20 Debugging with GDB GDB Annotations . . . . . . . . . . . . . . . . . . . . . . 261 20.1 20.2 20.3 20.4 20.5 20.6 20.7 20.8 20.9 20.10 20.11 20.12 21 What is an annotation?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The server prefix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Values. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
xi Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
xii Debugging with GDB
Summary of GDB 1 Summary of GDB The purpose of a debugger such as GDB 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. GDB allows you to do the following: • Load the executable along with any required arguments. • Stop your program on specified blocks of code. • Examine your program when it has stopped running due to an error.
2 Debugging with GDB So that they may not regard their many labors as thankless, we particularly thank those who shepherded GDB through major releases: Andrew Cagney (release 5.0); Jim Blandy (release 4.18); Jason Molenda (release 4.17); Stan Shebs (release 4.14); Fred Fish (releases 4.16, 4.15, 4.13, 4.12, 4.11, 4.10, and 4.9); Stu Grossman and John Gilmore (releases 4.8, 4.7, 4.6, 4.5, and 4.4); John Gilmore (releases 4.3, 4.2, 4.1, 4.0, and 3.9); Jim Kingdon (releases 3.5, 3.4, and 3.
Summary of GDB 3 Hitachi America, Ltd. sponsored the support for H8/300, H8/500, and Super-H processors. NEC sponsored the support for the v850, Vr4xxx, and Vr5xxx processors. Mitsubishi sponsored the support for D10V, D30V, and M32R/D processors. Toshiba sponsored the support for the TX39 Mips processor. Matsushita sponsored the support for the MN10200 and MN10300 processors. Fujitsu sponsored the support for SPARClite and FR30 processors.
4 Debugging with GDB
Chapter 1: A Sample GDB Session 5 1 A Sample GDB Session This chapter describes the most common GDB commands with the help of an example.
6 Debugging with GDB Copyright 1986 - 2001 Free Software Foundation, Inc. Hewlett-Packard Wildebeest 3.0 (based on GDB ) is covered by the GNU General Public License. Type "show copying" to see the conditions to change it and/or distribute copies. Type "show warranty" for warranty/support. GDB reads only enough symbol data to know where to find the rest when needed; as a result, the first prompt comes up very quickly. 1.
Chapter 1: A Sample GDB Session 7 1.6 Stepping into a subroutine The set_quotes looks like a promising subroutine. We can go into it by using the command s (step) instead of next. step goes to the next line to be executed in any subroutine, so it steps into set_quotes. ((gdb)) s set_quotes (lq=0x34c78 "", rq=0x34c88 "") at input.c:530 530 if (lquote != def_lquote) 1.
8 Debugging with GDB 1.9 Listing Source Code lquote and rquote are indeed the new left and right quotes. To look at some context, we can display ten lines of source surrounding the current line with the l (list) command.
Chapter 1: A Sample GDB Session 9 C-d Program exited normally. The message ‘Program exited normally.’ is from GDB; it indicates m4 has finished executing. We can end our GDB session with the GDB quit command.
10 Debugging with GDB
Chapter 2: Getting In and Out of GDB 11 2 Getting In and Out of GDB This chapter discusses how to start GDB, and exit out of it. The essentials are: • type ‘(gdb)’ to start GDB. • type quit or C-d to exit. 2.1 Invoking GDB Invoke GDB by running the program (gdb). Once started, GDB reads commands from the terminal until you tell it to exit. You can also run (gdb) with a variety of arguments and options, to specify more of your debugging environment at the outset.
12 Debugging with GDB 2.1.1 Choosing files When GDB starts, it reads any arguments other than options as specifying an executable file and core file (or process ID). This is the same as if the arguments were specified by the ‘-se’ and ‘-c’ options respectively.
Chapter 2: Getting In and Out of GDB 13 The ‘.syms’ file is specific to the host machine where GDB is run. It holds an exact image of the internal GDB symbol table. It cannot be shared across multiple host platforms. -r -readnow 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. You typically combine the -mapped and -readnow options in order to build a ‘.
14 Debugging with GDB -cd directory Run GDB using directory as its working directory, instead of the current directory. -dbx Support additional dbx commands, including: • use • status (in dbx mode, status has a different meaning than in default GDB mode.) • whereis • func • file • assign • call • stop -fullname -f gnu Emacs sets this option when it runs GDB as a subprocess.
Chapter 2: Getting In and Out of GDB -noasync 15 Disable the asynchronous event loop for the command-line interface. -baud bps -b bps Set the line speed (baud rate or bits per second) of any serial interface used by GDB for remote debugging. -tty device -t device Run using device for your program’s standard input and output. -tui Use a Terminal User Interface. For information, use your Web browser to read the file ‘tui.
16 Debugging with GDB 2.2 Quitting GDB quit [expression ] q To exit GDB, use the quit command (abbreviated q), or type an end-of-file character (usually C-d). If you do not supply expression, GDB will terminate normally; otherwise it will terminate using the result of expression as the error code. An interrupt (often C-c) does not exit from GDB, but rather terminates the action of any GDB command that is in progress and returns to GDB command level.
Chapter 3: GDB Commands 17 3 GDB Commands You can abbreviate a GDB command to the first few letters of the command name, if that abbreviation is unambiguous; and you can repeat certain GDB commands by typing just hRETi. You can also use the hTABi key to get GDB to fill out the rest of a word in a command (or to show you the alternatives available, if there is more than one possibility). 3.1 Command syntax • A GDB command is a single line of input. There is no limit on how long it can be.
18 Debugging with GDB You can either press hRETi at this point, to run the info breakpoints command, or backspace and enter something else, if ‘breakpoints’ does not look like the command you expected. (If you were sure you wanted info breakpoints in the first place, you might as well just type hRETi immediately after ‘info bre’, to exploit command abbreviations rather than command completion.) If there is more than one possibility for the next word when you press hTABi, GDB sounds a bell.
Chapter 3: GDB Commands 19 ((gdb)) b ’bubble( In general, GDB 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 Section 9.4.1.3 [C++ expressions], page 86. You can use the command set overload-resolution off to disable overload resolution; see Section 9.4.1.7 [GDB features for C++], page 88. 3.
20 Debugging with GDB Type "help" followed by command name for full documentation. Command name abbreviations are allowed if unambiguous. ((gdb)) help command With a command name as help argument, GDB displays a short paragraph on how to use that command. apropos args The apropos args command searches through all of the GDB commands, and their documentation, for the regular expression specified in args. It prints out all matches found.
Chapter 3: GDB Commands 21 Here are three miscellaneous show subcommands, all of which are exceptional in lacking corresponding set commands: show version Show what version of GDB is running. You should include this information in GDB bug-reports. If multiple versions of GDB are in use at your site, you may need to determine which version of GDB you are running; as GDB evolves, new commands are introduced, and old ones may wither away.
22 Debugging with GDB
Chapter 4: Running Programs Under GDB 23 4 Running Programs Under GDB When you run a program under GDB, you must first generate debugging information when you compile it using compiler option cc -g -O. You may start GDB with its arguments, if any, in an environment of your choice. If you are doing native debugging, you may redirect your program’s input and output, debug an already running process, or kill a child process. 4.
24 Debugging with GDB or variable substitution) in describing the arguments. On Unix systems, you can control which shell is used with the SHELL environment variable. GDB uses the C shell (/usr/bin/csh). See hundefinedi [Your program’s arguments], page hundefinedi. environment. Your program inherits its environment from GDB. However, you can use the GDB commands set environment and unset environment to change parts of the environment that affect your program.
Chapter 4: Running Programs Under GDB set args 25 Specify the arguments to be used the next time your program is run. If set args has no arguments, run executes your program with no arguments. Once you have run your program with arguments, using set args before the next run is the only way to run it again without arguments. show args Show the arguments to give your program when it is started. 4.4 Program Environment The environment consists of a set of environment variables and their values.
26 Debugging with GDB character (‘:’ on Unix, ‘;’ on MS-DOS and MS-Windows). If directory is already in the path, it is moved to the front, so it is searched sooner. You can use the string ‘$cwd’ to refer to whatever is the current working directory at the time GDB searches the path. If you use ‘.’ instead, it refers to the directory where you executed the path command. GDB replaces ‘.’ in the directory argument (with the current path) before adding directory to the search path. 4.
Chapter 4: Running Programs Under GDB 27 run > outfile starts your program, diverting its output to the file ‘outfile’. • An explicit redirection in run overrides the tty command’s effect on the input/output device, but not its effect on the controlling terminal. • When you use the tty command or redirect input in the run command, only the input for your program is affected. The input for GDB still comes from your terminal. 4.
28 Debugging with GDB If you exit GDB or use the run command while you have an attached process, you kill that process. By default, GDB asks for confirmation if you try to do either of these things; you can control whether or not you need to confirm by using the set confirm command (see Section 17.6 [Optional warnings and messages], page 252). NOTE: When GDB attaches to a running program you may get a message saying "Attaching to process #nnnnn failed.
Chapter 4: Running Programs Under GDB 29 ((gdb)) info threads ((gdb)) thread 1 Thread ID 1 not known. Use the "info threads" command to see the IDs of currently known threads.
30 Debugging with GDB [New thread 2 (system thread 26594)] when GDB notices a new thread. On HP-UX systems, you can control the display of thread creation messages. Following commands are used to control the display of thread creation: set threadverbose on Enable the output of informational messages regarding thread creation. The default setting is on. You can set it to off to stop the display of messages. set threadverbose off Disable the output of informational messages regarding thread creation.
Chapter 4: Running Programs Under GDB 31 thread apply [threadno ] [all ] args The thread apply command allows you to apply a command to one or more threads. Specify the numbers of the threads that you want affected with the command argument threadno. threadno is the internal GDB thread number, as shown in the first field of the ‘info threads’ display. To apply a command to all threads, use thread apply all args.
32 Debugging with GDB parent The original process is debugged after a fork. The child process runs unimpeded. This is the default. child The new process is debugged after a fork. The parent process runs unimpeded. show follow-fork-mode Display the current debugger response to a fork or vfork call. If you ask to debug a child process and a vfork is followed by an exec, GDB executes the new target up to the first breakpoint in the new target.
Chapter 5: Stopping and Continuing 33 5 Stopping and Continuing The principal purpose of a debugger is to let you stop your program before it terminates abnormaly or runs into trouble, so that you can investigate and determine the reason. Inside GDB, your program can stop for several reasons, such as a signal, a breakpoint, or reaching a new line after a GDB command such as step. You can then examine and change variables, set new breakpoints or remove old ones, and then continue execution.
34 Debugging with GDB see Section 8.9 [Convenience variables], page 75, for a discussion of what you can do with convenience variables. You have several ways to say where the breakpoint should go. break function Set a breakpoint at entry to function function. When using source languages that permit overloading of symbols, such as C++, function may refer to more than one possible place to break. See Section 5.1.7 [Breakpoint menus], page 42, for a discussion of that situation.
Chapter 5: Stopping and Continuing 35 tbreak args Set a breakpoint enabled only for one stop. args are the same as for the break command, and the breakpoint is set in the same way, but the breakpoint is automatically deleted after the first time your program stops there. See Section 5.1.4 [Disabling breakpoints], page 39. hbreak args Set a hardware-assisted breakpoint.
36 Debugging with GDB Breakpoint Numbers Type Breakpoint, watchpoint, or catchpoint. Disposition Whether the breakpoint is marked to be disabled or deleted when hit. Enabled or Disabled Enabled breakpoints are marked with ‘y’. ‘n’ marks breakpoints that are not enabled. Address Where the breakpoint is in your program, as a memory address. What Where the breakpoint is in the source for your program, as a file and line number.
Chapter 5: Stopping and Continuing 37 longjmp resume Internal breakpoint at the target of a longjmp. until Temporary internal breakpoint used by the GDB until command. finish Temporary internal breakpoint used by the GDB finish command. shlib events Shared library events. 5.1.2 Setting catchpoints You can use catchpoints to cause the debugger to stop for certain kinds of program events, such as C++ exceptions or the loading of a shared library. Use the catch command to set a catchpoint.
38 Debugging with GDB • You cannot raise an exception interactively. • You cannot install an exception handler interactively. Sometimes catch is not the best way to debug exception handling: if you need to know exactly where an exception is raised, it is better to stop before the exception handler is called, since that way you can see the stack before any unwinding takes place. If you set a breakpoint in an exception handler instead, it may not be easy to find out where the exception was raised.
Chapter 5: Stopping and Continuing 39 delete [breakpoints] [range ...] Delete the breakpoints, watchpoints, or catchpoints of the breakpoint ranges specified as arguments. If no argument is specified, delete all breakpoints (GDB asks confirmation, unless you have set confirm off). You can abbreviate this command as d. 5.1.4 Disabling breakpoints Rather than deleting a breakpoint, watchpoint, or catchpoint, you might prefer to disable it.
40 Debugging with GDB disabled or enabled only when you use one of the commands above. (The command until can set and delete a breakpoint of its own, but it does not change the state of your other breakpoints; see Section 5.2 [Continuing and stepping], page 44.) 5.1.5 Break conditions The simplest sort of breakpoint breaks every time your program reaches a specified place. You can also specify a condition for a breakpoint.
Chapter 5: Stopping and Continuing 41 condition bnum Remove the condition from breakpoint number bnum. It becomes an ordinary unconditional breakpoint. A special case of a breakpoint condition is to stop only when the breakpoint has been reached a certain number of times. This is so useful that there is a special way to do it, using the ignore count of the breakpoint. Every breakpoint has an ignore count, which is an integer. Most of the time, the ignore count is zero, and therefore has no effect.
42 Debugging with GDB You can use breakpoint commands to start your program up again. Simply use the continue command, or step, or any other command that resumes execution. Any other commands in the command list, after a command that resumes execution, are ignored. This is because any time you resume execution (even with a simple next or step), you may encounter another breakpoint—which could have its own command list, leading to ambiguities about which list to execute.
Chapter 5: Stopping and Continuing 43 ‘[1] all’. Typing 1 sets a breakpoint at each definition of function, and typing 0 aborts the break command without setting any new breakpoints. For example, the following session excerpt shows an attempt to set a breakpoint at the overloaded symbol String::after. We choose three particular definitions of that function name: ((gdb)) b String::after [0] cancel [1] all [2] file:String.cc; line number:867 [3] file:String.cc; line number:860 [4] file:String.
44 Debugging with GDB 5.2 Continuing and stepping Continuing means resuming program execution until your program completes normally. In contrast, stepping means executing just one more “step” of your program, where “step” may mean either one line of source code, or one machine instruction (depending on what particular command you use). Either when continuing or when stepping, your program may stop even sooner, due to a breakpoint or a signal.
Chapter 5: Stopping and Continuing 45 Also, the step command only enters a function if there is line number information for the function. Otherwise it acts like the next command. This avoids problems when using cc -gl on MIPS machines. Previously, step entered subroutines if there was any debugging information about the routine. step count Continue running as in step, but do so count times.
46 Debugging with GDB even though the test in a C for-loop is written before the body of the loop. The until command appeared to step back to the beginning of the loop when it advanced to this expression; however, it has not really gone to an earlier statement—not in terms of the actual machine code. until with no argument works by means of single instruction stepping, and hence is slower than until with an argument.
Chapter 5: Stopping and Continuing 47 immediately whenever an error signal happens. You can change these settings with the handle command. Note: Use caution if you disable all signals from certain processes. Disabling ‘SIGTRAP’ in your program may cause your program to hang. HP-UX uses ‘SIGTRAP’ to communicate with the debugger. If you disable all signals from certain processes so that signals will be delivered to the right process, your program may hang when you try to debug it.
48 Debugging with GDB When a signal stops your program, the signal is not visible to the program until you continue. Your program sees the signal then, if pass is in effect for the signal in question at that time. In other words, after GDB reports a signal, you can use the handle command with pass or nopass to control whether your program sees that signal when you continue.
Chapter 5: Stopping and Continuing 49 On some OSes, you can lock the OS scheduler and thus allow only a single thread to run. set scheduler-locking mode Set the scheduler locking mode. If it is off, then there is no locking and any thread may run at any time. If on, then only the current thread may run when the inferior is resumed. The step mode optimizes for single-stepping. It stops other threads from “seizing the prompt” by preempting the current thread while you are stepping.
50 Debugging with GDB
Chapter 6: Examining the Stack 51 6 Examining the Stack When your program has stopped, the first thing you need to know is where it stopped and how it got there. Each time your program performs a function call, information about the call is generated.The information includes the location of the call in your program, the arguments of the call, and the local variables of the function being called. The information is saved in a block of data called a stack frame.
52 Debugging with GDB ‘-fomit-frame-pointer’ generates functions without a frame.) This is occasionally done with heavily used library functions to save the frame setup time. GDB has limited facilities for dealing with these function invocations. If the innermost function invocation has no stack frame, GDB nevertheless regards it as though it had a separate frame, which is numbered zero as usual, allowing correct tracing of the function call chain.
Chapter 6: Examining the Stack 53 Each line in the backtrace shows the frame number and the function name. The program counter value is also shown—unless you use set print address off. The backtrace also shows the source file name and line number, as well as the arguments to the function. The program counter value is omitted if it is at the beginning of the code for that line number. Here is an example of a backtrace. It was made with the command ‘bt 3’, so it shows the innermost three frames.
54 Debugging with GDB All of these commands end by printing two lines of output describing the frame. The first line shows the frame number, the function name, the arguments, and the source file and line number of execution in that frame. The second line shows the text of that source line. For example: ((gdb)) up #1 0x22f0 in main (argc=1, argv=0xf7fffbf4, env=0xf7fffbfc) at env.
Chapter 6: Examining the Stack 55 the same kind of address (more than one for some architectures) that you specify in the frame command. See Section 6.5 [Selecting a frame], page 53. info args Print the arguments of the selected frame, each on a separate line. info locals Print the local variables of the selected frame, each on a separate line. These are all variables (declared either static or automatic) accessible at the point of execution of the selected frame.
56 Debugging with GDB
Chapter 7: Examining Source Files 57 7 Examining Source Files GDB can print parts of the source code of your program, since the debugging information recorded in the program tells GDB what source files were used to build it. When your program stops, GDB spontaneously prints the line where it stopped. Likewise, when you select a stack frame (see Section 6.5 [Selecting a frame], page 53), GDB prints the line where execution in that frame has stopped.
58 Debugging with GDB list linespec Print lines centered around the line specified by linespec. list first,last Print lines from first to last. Both arguments must be linespecs. list ,last Print lines ending with last. list first, Print lines starting with first. list + Print lines just after the lines last printed. list - Print lines just before the lines last printed. list As described in the preceding table.
Chapter 7: Examining Source Files 59 reverse-search regexp The command ‘reverse-search regexp ’ checks each line, starting with the one before the last line listed and going backward, for a match for the regexp. It lists the line(s) that is found. You can abbreviate this command as rev. 7.3 Specifying source directories Executable programs sometimes do not record the directories of the source files from which they were compiled.
60 Debugging with GDB 7.4 Source and machine code You can use the command info line to map source lines to program addresses (and vice versa), and the command disassemble to display a range of addresses as machine instructions. When run under gnu Emacs mode, the info line command causes the arrow to point to the line specified. Also, info line prints addresses in symbolic form as well as hex. info line linespec Print the starting and ending addresses of the compiled code for source line linespec.
Chapter 7: Examining Source Files 61 Some architectures have more than one commonly-used set of instruction mnemonics or other syntax. set disassembly-flavor instruction-set Select the instruction set to use when disassembling the program via the disassemble or x/i commands. Currently this command is only defined for the Intel x86 family. You can set instruction-set to either intel or att. The default is att, the AT&T flavor used by default by Unix assemblers for x86-based targets.
62 Debugging with GDB
Chapter 8: Examining Data 63 8 Examining Data The usual way to examine data in your program is with the print command (abbreviated p), or its synonym inspect. It evaluates and prints the value of an expression of the language your program is written in (see Chapter 9 [Using GDB with Different Languages], page 79). The following forms of print command are supported: print expr print /f expr expr is an expression (in the source language).
64 Debugging with GDB @ ‘@’ is a binary operator for treating parts of memory as arrays. Refer to See Section 8.3 [Artificial arrays], page 65, for more information. :: ‘::’ allows you to specify a variable in terms of the file or function where it is defined. See Section 8.2 [Program variables], page 64. {type } addr Refers to an object of type type stored at address addr in memory.
Chapter 8: Examining Data 65 ((gdb)) p ’f2.c’::x This use of ‘::’ is very rarely in conflict with the very similar use of the same notation in C++. GDB also supports use of the C++ scope resolution operator in GDB expressions. Warning: Occasionally, a local variable may appear to have the wrong value at certain points in a function just after entry to a new scope, and just before exit. You may see this problem when you are stepping by machine instructions.
66 Debugging with GDB used in expressions. Artificial arrays most often appear in expressions via the value history (see Section 8.8 [Value history], page 74), after printing one out. Another way to create an artificial array is to use a cast. This re-interprets a value as if it were an array.
Chapter 8: Examining Data 67 a Print as an address, both absolute in hexadecimal and as an offset from the nearest preceding symbol. You can use this format used to discover where (in what function) an unknown address is located: ((gdb)) p/a 0x54320 $3 = 0x54320 <_initialize_vx+396> c Regard as an integer and print it as a character constant. f Regard the bits of the value as a floating point number and print using typical floating point syntax.
68 Debugging with GDB g Giant words (eight bytes). Each time you specify a unit size with x, that size becomes the default unit the next time you use x. (For the ‘s’ and ‘i’ formats, the unit size is ignored and is normally not written.) addr, starting display address addr is the address where you want GDB to begin displaying memory. The expression need not have a pointer value (though it may); it is always interpreted as an integer address of a byte of memory. Refer to See Section 8.
Chapter 8: Examining Data 69 value each time your program stops. Each expression added to the list is given a number to identify it; to remove an expression from the list, you specify that number. The automatic display looks like this: 2: foo = 38 3: bar[5] = (struct hack *) 0x3804 This display shows item numbers, expressions and their current values.
70 Debugging with GDB would not be displayed right now because they refer to automatic variables not currently available. If a display expression refers to local variables, then it does not make sense outside the lexical context for which it was set up. Such an expression is disabled when execution enters a context where one of its variables is not defined.
Chapter 8: Examining Data 71 set print symbol-filename on Tell GDB to print the source file name and line number of a symbol in the symbolic form of an address. set print symbol-filename off Do not print source file name and line number of a symbol. This is the default. show print symbol-filename Show whether or not GDB will print the source file name and line number of a symbol in the symbolic form of an address.
72 Debugging with GDB set print elements number-of-elements Set a limit on how many elements of an array GDB will print. If GDB is printing a large array, it stops printing after it has printed the number of elements set by the set print elements command. This limit also applies to the display of strings. When GDB starts, this limit is set to 200. Setting number-of-elements to zero means that the printing is unlimited.
Chapter 8: Examining Data 73 set print union off Tell GDB not to print unions which are contained in structures. show print union Ask GDB whether or not it will print unions which are contained in structures.
74 Debugging with GDB gnu Decode based on the gnu C++ compiler (g++) encoding algorithm. hp Decode based on the HP ANSI C++ (aCC) encoding algorithm. lucid Decode based on the Lucid C++ compiler (lcc) encoding algorithm. arm Decode using the algorithm in the C++ Annotated Reference Manual. Warning: this setting alone is not sufficient to allow debugging cfront generated executables. GDB would require further enhancement to permit that. If you omit style, you will see a list of possible formats.
Chapter 8: Examining Data 75 or discarded (for example with the file or symbol-file commands). When the symbol table changes, the value history is discarded, since the values may contain pointers back to the types defined in the symbol table. The values printed are given history numbers by which you can refer to them. These are a range of integers starting with one. print shows you the history number assigned to a value by printing ‘$num = ’ before the value; here num is the history number.
76 Debugging with GDB Convenience variables are prefixed with ‘$’. Any name preceded by ‘$’ can be used for a convenience variable, unless it is one of the predefined machine-specific register names (see Section 8.10 [Registers], page 77). (Value history references, in contrast, are numbers preceded by ‘$’. See Section 8.8 [Value history], page 74.) You can save a value in a convenience variable with an assignment expression, just as you would set a variable in your program.
Chapter 8: Examining Data 77 8.10 Registers You can refer to machine register contents, in expressions, as variables with names starting with ‘$’. The names of registers are different for each machine. Use info registers to view the names used on your machine. info registers Print the names and values of all registers except floating-point registers (in the selected stack frame). info all-registers Print the names and values of all registers, including floating-point registers. info registers regname ...
78 Debugging with GDB coprocessor are always saved in “extended” (raw) format, but all C programs expect to work with “double” (virtual) format. In such cases, GDB normally works with the virtual format only (the format that makes sense for your program), but the info registers command prints the data in both formats. Normally, register values are relative to the selected stack frame (see Section 6.5 [Selecting a frame], page 53).
Chapter 9: Using GDB with Different Languages 79 9 Using GDB with Different Languages Although programming languages generally have common aspects, they are rarely expressed in the same manner. For instance, in ANSI C, dereferencing a pointer p is accomplished by *p, but in Modula-2, it is accomplished by p^. Values can also be represented (and displayed) differently. Hex numbers in C appear as ‘0x1ae’, while in Modula-2 they appear as ‘1AEH’.
80 ‘.f’ ‘.F’ ‘.f90’ ‘.s’ ‘.S’ Debugging with GDB Fortran source file. GDB does not distinguish between Fortran 77 and Fortran 90 files. Assembler source file. This actually behaves almost like C, but GDB does not skip over function prologues when stepping. In addition, you may set the language associated with a filename extension. See Section 9.2 [Displaying the language], page 80. 9.1.
Chapter 9: Using GDB with Different Languages 81 show language Display the current working language. This is the language you can use with commands such as print to build and compute expressions that may involve variables in your program. info frame Display the source language for this frame. This language becomes the working language if you use an identifier from this frame. See Section 6.6 [Information about a frame], page 54, to identify the other information listed here.
82 Debugging with GDB The second example fails because the CARDINAL 1 is not type-compatible with the REAL 2.3. For the expressions you use in GDB commands, you can tell the GDB type checker to skip checking; to treat any mismatches as errors and abandon the expression; or to only issue warnings when type mismatches occur, and evaluate the expression anyway. When you choose the last of these, GDB evaluates expressions like the second example above, but also issues a warning.
Chapter 9: Using GDB with Different Languages 83 A range error can result from numerical overflow, from exceeding an array index bound, or when you type a constant that is not a member of any type. Some languages, however, do not treat overflows as an error.
84 Debugging with GDB 9.4.1 C and C++ Since C and C++ are so closely related, many features of GDB apply to both languages. Whenever this is the case, we discuss those languages together. The C++ debugging facilities are jointly implemented by the C++ compiler and GDB. Therefore, to debug your C++ code effectively, you must compile your C++ programs with a supported C++ compiler, such as gnu g++, or the HP ANSI C++ compiler (aCC). For best results when using gnu C++, use the stabs debugging format.
Chapter 9: Using GDB with Different Languages ==, != 85 Equality and inequality. Defined on scalar types. The value of these expressions is 0 for false and non-zero for true. <, >, <=, >= Less than, greater than, less than or equal, greater than or equal. Defined on scalar types. The value of these expressions is 0 for false and non-zero for true. <<, >> left shift, and right shift. Defined on integral types. @ The GDB “artificial array” operator (see Section 8.1 [Expressions], page 63).
86 Debugging with GDB 9.4.1.2 C and C++ constants GDB allows you to express the constants of C and C++ in the following ways: • Integer constants are a sequence of digits. Octal constants are specified by a leading ‘0’ (i.e. zero), and hexadecimal constants by a leading ‘0x’ or ‘0X’. Constants can also end with a letter ‘l’, specifying that the constant should be treated as a long value.
Chapter 9: Using GDB with Different Languages 87 2. While a member function is active (in the selected stack frame), your expressions have the same namespace available as the member function; that is, GDB allows implicit references to the class instance pointer this following the same rules as C++. 3. You can call overloaded functions; GDB resolves the function call to the right definition, with some restrictions.
88 Debugging with GDB 9.4.1.4 C and C++ defaults If you allow GDB to set type and range checking automatically, they both default to off whenever the working language changes to C or C++. This happens regardless of whether you or GDB selects the working language. If you allow GDB to set the language automatically, it recognizes source files whose names end with ‘.c’, ‘.C’, or ‘.cc’, etc, and when GDB enters code compiled from one of these files, it sets the working language to C or C++.
Chapter 9: Using GDB with Different Languages 89 catch throw catch catch Debug C++ exception handling using these commands. See Section 5.1.2 [Setting catchpoints], page 37. ptype typename Print inheritance relationships as well as other information for type. typename. See Chapter 10 [Examining the Symbol Table], page 93.
90 Debugging with GDB 9.4.2 Fortran You can use WDB to debug programs written in Fortran. WDB does not distinguish between Fortran 77 and Fortran 90 files. WDB provides the following command to control case sensitivity: case-sensitive [on | off] The default for Fortran is off, while for other languages the default is on. Other supported features are: • Fortran 90 pointers • Structures and unions • Calling functions with integer, logical, real, complex arguments • Intrinsic support 9.4.2.
Chapter 9: Using GDB with Different Languages +, - Unary operators ** Exponentiation .EQ., = Equal .NE., /= Not equal, or concatenation .LT., < Less than .LE., <= Less than or equal to .GT., > Greater than .GE., >= Greater than or equal to // Concatenation .NOT. Logical negation .AND. Logical AND .OR. Logical OR .EQV. Logical equivalence 91 .NEQV., .XOR. Logical non-equivalence Logical constants are represented as .TRUE. or .FALSE.
92 Debugging with GDB
Chapter 10: Examining the Symbol Table 93 10 Examining the Symbol Table The commands described in this chapter allow you to inquire about the symbols (names of variables, functions and types) defined in your program. This information is inherent in the text of your program and does not change as your program executes. GDB finds it in your program’s symbol table, in the file indicated when you started GDB (see Section 2.1.
94 Debugging with GDB ((gdb)) whatis v type = struct complex ((gdb)) ptype v type = struct complex { double real; double imag; } As with whatis, using ptype without an argument refers to the type of $, the last value in the value history. info types regexp info types Print a brief description of all types whose names match regexp (or all types in your program, if you supply no argument).
Chapter 10: Examining the Symbol Table 95 set symbol-reloading on Replace symbol definitions for the corresponding source file when an object file with a particular name is seen again. set symbol-reloading off Do not replace symbol definitions when encountering object files of the same name more than once.
96 Debugging with GDB
Chapter 11: Altering Execution 97 11 Altering Execution Once you think you have found an error in your program, you might want to find out for certain whether correcting the apparent error would lead to correct results in the rest of the run. You can find the answer by experiment, using the GDB features for altering execution of the program.
98 Debugging with GDB ((gdb)) whatis g type = double ((gdb)) p g $1 = 1 ((gdb)) set g=4 ((gdb)) p g $2 = 1 ((gdb)) r The program being debugged has been started already. Start it from the beginning? (y or n) y Starting program: /home/smith/cc_progs/a.out "/home/smith/cc_progs/a.out": can’t open to read symbols: Invalid bfd target. ((gdb)) show g The current BFD target is "=4". The steps shown above sets the gnutarget to an invalid value in place of the program variable g.
Chapter 11: Altering Execution 99 counter. If line linespec is in a different function from the one currently executing, the results may be bizarre if the two functions expect different patterns of arguments or of local variables. For this reason, the jump command requests confirmation if the specified line is not in the function currently executing. However, even bizarre results are predictable if you are well acquainted with the machine-language code of your program.
100 Debugging with GDB return return expression You can cancel execution of a function call with the return command. If you give an expression argument, its value is used as the return value from the function value. When you use return, GDB discards the selected stack frame (and all frames within it). You can think of this as making the discarded frame return prematurely. If you wish to specify a value to be returned, give that value as the argument to return.
Chapter 11: Altering Execution 101 If you have already loaded a file, you must load it again (using the exec-file or core-file command) after changing set write, for your new setting to take effect. show write Display whether executable files and core files are opened for writing as well as reading.
102 Debugging with GDB
Chapter 12: GDB Files 103 12 GDB Files GDB needs to know the file name of the program to be debugged, both in order to read its symbol table and in order to start your program. To debug a core dump of a previous run, you must also tell GDB the name of the core dump file. 12.1 Commands to specify files You can specify executable and core dump file names as arguments to the GDB start-up command. (see Chapter 2 [Getting In and Out of GDB], page 11).
104 Debugging with GDB symbol-file does not repeat if you press hRETi again after executing it once. When GDB is configured for a particular environment, it understands debugging information in whatever format is the standard generated for that environment; you may use either a gnu compiler, or other compilers that adhere to the local conventions. For most kinds of object files, the symbol-file command does not normally read the symbol table in full right away.
Chapter 12: GDB Files 105 To do this, use the kill command (see Section 4.8 [Killing the child process], page 28). add-symbol-file filename address add-symbol-file filename address [ -readnow ] [ -mapped ] add-symbol-file filename address data_address bss_address add-symbol-file filename -ssection address The add-symbol-file command reads additional symbol table information from the file filename.
106 Debugging with GDB info share info sharedlibrary Print the names of the shared libraries which are currently loaded. sharedlibrary regex share regex Load shared object library symbols for files matching a Unix regular expression. As with files loaded automatically, it only loads shared libraries required by your program for a core file or after typing run. If regex is omitted all shared libraries required by your program are loaded.
Chapter 12: GDB Files 107 For example, if you want GDB to search for libraries in ‘/home/debugger/lib’ and ‘/tmp/lib’ before searching the default system directories for libraries, you can use this setting: GDB_SHLIB_PATH=/home/debugger/lib:/tmp/lib With this setting, GDB searches the directories in the order specified until it finds a library with the correct name. In this example, if GDB encounters a library by the name of ‘/usr/lib/libsubs.sl’, GDB searches first for ‘/home/debugger/lib/libsubs.
108 Debugging with GDB block at address out of order The symbol information for symbol scope blocks should occur in order of increasing addresses. This error indicates that it does not do so. GDB does not circumvent this problem, and has trouble locating symbols in the source file whose symbols it is reading. (You can often determine what source file is affected by specifying set verbose on. See Section 17.6 [Optional warnings and messages], page 252.
Chapter 13: Specifying a Debugging Target 109 13 Specifying a Debugging Target A target is the execution environment occupied by your program. Often, GDB runs in the same host environment as your program; in that case, the debugging target is specified as a side effect when you use the file or core commands. For HP-UX specific information, see hundefinedi [HP-UX Targets], page hundefinedi.
110 Debugging with GDB help target Displays the names of all targets available. To display targets currently selected, use either info target or info files (see Section 12.1 [Commands to specify files], page 103). help target name Describe a particular target, including any parameters necessary to select it. set gnutarget args GDB uses its own library BFD to read your files. GDB knows whether it is reading an executable, a core, or a .
Chapter 13: Specifying a Debugging Target 111 target nrom dev NetROM ROM emulator. This target only supports downloading. Different targets are available on different configurations of GDB; your configuration may have more or fewer targets. Many remote targets require you to download the executable code once you have successfully established a connection. load filename Depending on what remote debugging facilities are configured into GDB, the load command may be available.
112 Debugging with GDB
Chapter 14: HP-UX Configuration-Specific Information 113 14 HP-UX Configuration-Specific Information While nearly all GDB commands are available for all native and cross versions of the debugger, there are some exceptions. This chapter describes features, commands and, enhancements available only on HP-UX. 14.1 Summary of HP Enhancements to GDB WDB provides the following features in addition to the standard GDB features: • Support for debugging memory problems.
114 Debugging with GDB • Support for core file commands packcore, unpackcore, getcore, dumpcore and info rtti address . • On PA-RISC systems, sanity check for core files dumped by hardware generated signals can be performed. HP WDB can detect and warn the user about certain cases of corrupted core files. • Inline support is on by default on Integrity systems. On PA-RISC, the inline support is still off by default. • For PA 64-bit applications, WDB can step into shared library bind-on-reference calls.
Chapter 14: HP-UX Configuration-Specific Information 115 • Support for persistent display of expressions across re-runs. The user does not need to re-initiate the display settings for every run. • Viewing wide character and wide-character strings of type wchar_t using the type print command.
116 Debugging with GDB 14.2 HP-UX dependencies 14.2.1 Linker Dependencies Several features available in WDB depend on specific versions of the linker or the compiler. • Linker patch required for +objdebug For releases prior to HP-UX 11i v2 (for IA) and HP-UX 11i v1 (for PA-RISC), you must install the latest linker patch to generate object modules that enable faster linking and smaller executable file sizes for large applications. See your your compiler release notes for more details.
Chapter 14: HP-UX Configuration-Specific Information srand() uwx_register_callbacks() 117 unlink() lseek() open() sprintf() strcmp() printf() pthread_self() putenv() shmctl() rand() strchr() uwx_self_lookupip() shl_get() shl_unload() shl_findsym () strtok_r() time() uwx_get_reg() shl_get_r() perror() uwx_init() uwx_self_copyin() creat() uwx_step() write() pthread_getschedparam() uwx_self_init_context() uwx_self_init_info() uwx_register_alloc_cb() U_STACK_TRACE() close() strchr()
118 Debugging with GDB • Support for debugging large core files (> 2GB) HP WDB supports debugging of core files with sizes more than 2 GB. • Support co-variant type HP WDB can step into a co-variant function. The compiler-generated function called thunks, which is used internally by the compiler to support co-variant return type, is not shown when you do a backtrace or switch from one frame to another frame.
Chapter 14: HP-UX Configuration-Specific Information 119 If you specify both WDB_ROOT and GDB_ROOT, the value for GDB_ROOT is ignored. HP WDB supports these environment variables to override the location of different component of HP WDB. Defined Variable None WDB_ROOT GDB_ROOT GDB_SERVER LIBRTC_SERVER WDB Location /opt/langtools/bin $WDB_ROOT/bin n/a n/a n/a GDB location /opt/langtools/bin $WDB_ROOT/bin $GDB_ROOT/bin $GDB_SERVER n/a librtc.
120 Debugging with GDB To use this feature, the program must be compiled with the +objdebug option. For information on how pathmap works type help pathmap at the HP WDB prompt. If the debugger cannot find the source: files. 1. Make certain the files were compiled with the ’-g’ switch. Type info sources to find the list of files that the debugger knows were compiled with ’-g’. 2. Make certain that the debugger can find the source file.
Chapter 14: HP-UX Configuration-Specific Information 121 Fix and Continue is only supported with the most recent versions of HP C and HP aC++ on PA-RISC systems. In command-line mode, you use the edit command before invoking the fix command. The edit command has the following syntax: edit file1 file2 where file represents one or more source files for the current executable. If you do not specify a file name, WDB edits the currently open source file.
122 Debugging with GDB • If you change the name of a function and there was a breakpoint set to the old function, WDB does not move the breakpoint to the new function. The old breakpoint is still valid. • If the number of lines of the modified file is different from that of the original file, the placement of breakpoints may not be correct. • When the program resumes, the program counter is moved to the beginning of the same line in the modified function. The program counter may be at the wrong line. 14.
Chapter 14: HP-UX Configuration-Specific Information 123 } main() { int num = 10; printf("The sum from 1 to %d is = %d\n", num, sum(num)); } 1. Compile the program. cc sum.c -g -o mysum /usr/ccs/bin/ld: (Warning) At least one PA 2.0 object file (sum.o) was detected. The linked output may not run on a PA 1.x system. 2. Run the program. ./mysum The sum from 1 to 10 is = 0 This result is obviously wrong. We need to debug the program. 3. Run the debugger: gdb mysum HP gdb 3.0 for PA-RISC 1.1 or 2.
124 7. 8. 9. 10. Debugging with GDB Because you are going to edit the current file, you do not need to specify a source file name. (gdb) edit The edit command opens a new terminal session using your environment variable settings for terminal and editor. The debugger automatically loads the source file. Make the necessary changes. In this case, add: return total; to the function named num. Save the edited source file and exit the editor. This saves the changes in the actual source file for the program.
Chapter 14: HP-UX Configuration-Specific Information 125 and later support the inline debugging feature in Integrity systems. 14.8.1 Inline Debugging in HP 9000 Systems To debug inline functions in HP 9000 systems, complete the following steps: Step 1: Compile the source files with the +inline_debug option. For example: /opt/aCC/bin/aCC -g +inline_debug test.c Step 2: Inline debugging is enabled by default.
126 Debugging with GDB 14.8.2 Inline Debugging in Integrity Systems In Integrity systems, applications that are compiled with -g option support inline debugging by default. Compiler versions A.06.02 and later support the inline debugging feature in Integrity systems and require no additional options. WDB 5.6 and later versions enable you to set and modify breakpoints in inline functions for programs compiled with optimization level less than +O2.
Chapter 14: HP-UX Configuration-Specific Information 127 • The inline breakpoint features can degrade performance of the application that is being debugged. You can explicitly disable the breakpoint features when the features are not required and continue to use other inline debugging features, such as step and next. 14.8.2.
128 Debugging with GDB (gdb) set inline-debug inline_bp_individual or $ gdb --inline = inline_bp_individual • To disable inline debugging, enter either of the following commands before debugging the application: (gdb) set inline-debug off or $ gdb --inline= off Step 3: You can use the following commands for debugging inline functions in Integrity systems: step next list backtrace frame info locals info args breakpoint The following commands are not available for debugging inline functions in Integrity
Chapter 14: HP-UX Configuration-Specific Information 129 (gdb) info macro VAR2 Defined at scope.c:21 #define VAR2 201 - macro expand [macro-name] Expands the macro and the parameters in the macro. If there are any parameters in the macro, they are substituted in the macro definition when the definition is displayed. For example: #define YY 6 #define MAC (67 + YY) ... $ gdb ... (gdb) macro expand MAC expands to: (67 + 6) • Evaluating Macros HP WDB enables you to evaluate a macro and display the output.
130 Debugging with GDB 14.9.2 Examples for Macro Debugging The following example illustrates the use of the macro debugging: Sample Program: $ cat scope.c 1 2 #include
Chapter 14: HP-UX Configuration-Specific Information 131 ... (gdb) b 13 Breakpoint 1 at 0x40007d0:0: file scope.c, line 13 from sc. (gdb) b 23 Breakpoint 2 at 0x40007d0:2: file scope.c, line 23 from sc. (gdb) b 30 Breakpoint 3 at 0x40007e0:0: file scope.c, line 30 from sc. (gdb) r Starting program: sc Breakpoint 1, main () at scope.c:13 13 { (gdb) print USED1 100 (gdb) print USED1+10 110 (gdb) info macro USED1 Defined at scope.c:4 #define USED1 100 (gdb) info macro USED2 Defined at scope.
132 Debugging with GDB $ cc -g +macro_debug=referenced -o sc1 scope.c $ gdb sc1 HP gdb for HP Itanium (32 or 64 bit) and target Copyright 1986 - 2001 Free Software Foundation, ... (gdb) b 13 Breakpoint 1 at 0x40007d0:0: file scope.c, line (gdb) b 23 Breakpoint 2 at 0x40007d0:2: file scope.c, line (gdb) b 30 Breakpoint 3 at 0x40007e0:0: file scope.c, line (gdb) r Starting program: sc1 HP-UX 11.2x. Inc. 13 from sc1. 23 from sc1. 30 from sc1. Breakpoint 1, main () at scope.
Chapter 14: HP-UX Configuration-Specific Information The program is running. 133 Exit anyway? (y or n) y. 14.10 Debugging Memory Problems You can use WDB to find leaks, profile heap usage and detect other heap-related errors in HP C, HP aC++, and HP Fortran programs written for HP-UX 11.x systems. (Both 32-bit and 64-bit programs are supported.) On HP-UX 11.x, the memory debugging features of WDB work with both single-threaded and multi-threaded programs that use POSIX threads.
134 Debugging with GDB 14.10.3 Memory Debugging Methodologies WDB enables you to debug memory problems in applications written for HP-UX 11.x or later using C, aC++, FORTRAN 77, and Fortran 90. WDB provides several commands that help expose memory-related problems.
Chapter 14: HP-UX Configuration-Specific Information 135 report does not show allocations that have already been freed. For example, if you make several allocations, free them all, and then you use info heap, the result does not show any allocations. info heap filename Writes heap report output to the specified file. info heap idnumber Produces detailed information on the specified heap allocation including the allocation call stack. show heap-check Displays all current settings for memory checking.
136 Debugging with GDB info leak leaknumber Produces detailed information on the specified leak including the allocation call stack. set heap-check block-size num-bytes Instructs WDB to stop the program whenever it tries to allocate a block larger than num-bytes in size. set heap-check heap-size num-size Instructs WDB to stop the program whenever it tries to increase the program heap by at least num-bytes.
Chapter 14: HP-UX Configuration-Specific Information 137 set heap-check scramble [on | off] Scrambles a memory block and overwrites it with a specific pattern when it is allocated or deallocated. This change to the memory contents increases the chance that erroneous behaviors, such as attempting to access space that is freed or depending on initial values of malloc() blocks, cause the program to fail.
138 Debugging with GDB 4. Set one or more breakpoints in the code where you want to examine cumulative leaks: (gdb) b myfunction 5. Run the program in the debugger: (gdb) run 6. Use the info command to show list of memory leaks: (gdb) info leaks Scanning for memory leaks...done 2439 bytes leaked in 25 blocks No. 0 1 2 Total bytes 1234 333 245 Blocks 1 1 8 Address 0x40419710 0x40410bf8 0x40410838 Function foo() main() strdup() [...] The debugger assigns each leak a numeric identifier. 7.
Chapter 14: HP-UX Configuration-Specific Information 139 check_free=on|off (or) set heap-check free Enables detection of multiple incorrect free of memory check_heap|heap=on|off (or) set heap-check Enables heap profiling. check_leaks|leaks=on|off (or) set heap-check leaks Enables leak detection. check_string=on|off (or) set heap-check string Enables detection for writing out of boundary for strcpy, strncpy, memcpy, memccpy, memset, memmove, bzero, bcopy.
140 Debugging with GDB $ cat rtcconfig check_leaks=on check_heap = on files=batchrtc4 $ Steps for Batch Mode Memory Debugging To use batch memory debugging, complete the following steps: 1. Compile the source files 2. Create an rtcconfig file in the current directory. 3. Define an environment variable BATCH_RTC. If you are using the Korn or Posix shell, enter the following command at the HP-UX prompt: export BATCH_RTC=on 4.
Chapter 14: HP-UX Configuration-Specific Information 141 (This step is not required on Integrity systems.) To explicitly preload the librtc runtime library and start the target application, enter one of the following commands: - For 32 bit IPF applications, LD_PRELOAD=/opt/langtools/lib/hpux32/librtc.so - For 64 bit IPF applications, LD_PRELOAD=/opt/langtools/lib/hpux64/librtc.so - For 32 bit PA applications, LD_PRELOAD=/opt/langtools/lib/librtc.
142 Debugging with GDB 14.10.5.2 Environment variable setting for Batch mode debugging Batch mode memory leak detection uses the following environment variables: • GDBRTC_CONFIG species the location of rtc configuration file. If this option is not specified, the configuration file is assumed to be in the current location, and has the filename rtcconfig. If user prefers to set this option, it must include the filename. • Incorrect usage: export GDBRTC_CONFIG=.
Chapter 14: HP-UX Configuration-Specific Information 143 14.10.5.3 Example for Batch Mode RTC This section illustrates examples of batch mode RTC on HP 9000 and Integrity Systems. • Example for Batch Mode RTC of a PA-RISC 32 bit Executable Step 1: Compile the source files.
144 Debugging with GDB - Preload the librtc runtime library, as follows: LD_ PRELOAD=/opt/langtools/lib/hpux32/librtc.so (Or) - Preload the librtc runtime library, as follows: $ chatr +mem_check enable • Example from Integrity Systems: Example-2 Step 1: Compile the source files.
Chapter 14: HP-UX Configuration-Specific Information 145 To enable or disable the target application to preload the librtc runtime library, enter the following command at the HP-UX prompt: $ chatr +mem_check Note: To attach and find leaks for PA-32 applications from the startup, the environment variable RTC_INIT should be set to on in addition to preloading the librtc.
146 Debugging with GDB 14.10.7 Configuring memory debugging settings The following configuration settings are supported to control the level of details of information required to be displayed when debugging memory leaks. 14.10.7.1 Specifying the stack depth Memory debugging reduces the performance of an application by 20-40% because of stack unwinding.
Chapter 14: HP-UX Configuration-Specific Information 147 Example: set heap-check min-heap-size 100 When the option min-heap-size is set to 100, GDB reports all the cumulative block allocations that 100 bytes at each call-site. 14.10.8 Scenarios in memory debugging 14.10.8.1 Stop when freeing unallocated or deallocated blocks WDB enables you to locate improper calls to free() and realloc(), with the command • In interactive debugging mode: set heap-check free [on | off].
148 Debugging with GDB 14.10.8.3 Stop when a specified block address is allocated or deallocated To stop a program whenever a block at a specified address is allocated or deallocated, use the command: set heap-check watch address You can use this to debug situations such as multiple free() calls to the same block. Limitation : This is not supported in batch mode debugging. 14.10.8.
Chapter 14: HP-UX Configuration-Specific Information 149 WDB tries to help as much as possible to detect if these pointers are of type datum or real pointers. In a -g compiled binary, WDB performs a look-up on a symbol table to find the symbol name and type to find the symbol name of the potential pointer and if its of pointer type, then the corresponding dangling block is really dangling(not a false positive). WDB turns on these checks, only when you specify set heap-check retain-freedblocks on. 14.10.
150 Debugging with GDB Memory Debugging Commands in Interactive and Batch Mode Command Description Interactive mode Batch mode Toggles heap profiling and detection of leaks, bounds, set heap-check [on | check_heap= [on | off] (or) set heap-check [on | off] off] and double free Toggle the leak detection set heap-check leaks capability [on |off] Toggle validation of calls to strcpy, strncpy, memcpy, memccpy, memset, memmove, set heap-check string [on | off] check_leaks =[on | off] set heap-chec
Chapter 14: HP-UX Configuration-Specific Information Specify the minimum size of a block for stack trace collection. GDB report leaks of blocks, smaller than this value. However, set heap-check min-leak-size 151 min_leak_size = (or) set heap-check min-leak-size no stack trace is provided.
152 Debugging with GDB NULL pointer return by memory allocators; used with set heap-check on, with/without null-check catch nomem Not supported in batch mode enabled Note: The files= and output_dir= options are exclusive to batch mode debugging. 14.10.10 Heap Profiling The heap profile is useful for identifying how memory is being used by the program. You can use WDB to profile an application’s current heap usage. 14.10.10.
Chapter 14: HP-UX Configuration-Specific Information 153 14.10.10.3 info heap arena [0 |1|2|..] blocks stacks Displays the memory profile report for block level and overall memory usage with stack trace where applicable.This command is available only for applications running on 11i v3 or later. 14.10.10.4 info module ADDRESS The info module command identifies load modules, and determines whether it lies in the text or data region for a given address.
154 Debugging with GDB No. 0 1 2 3 Total bytes 34567 4096 1234 245 Blocks 1 1 1 8 Address 0x40411000 0x7bd63000 0x40419710 0x404108b0 Function foo() bar() baz() boo() [...] The display shows the currently allocated heap blocks. Any blocks that have been allocated and already freed are not listed. To look at a specific allocation, specify the allocation number with the info heap command: (gdb) info heap 1 4096 bytes at 0x7bd63000 (9.86% of all bytes allocated) in bar () at test.
Chapter 14: HP-UX Configuration-Specific Information 155 info heap high-mem Displays the number of times brk() value changes for a given run. set heap-check high-mem-count X_number Stops when brk() value has moved X_number of times. Limitations: • This feature assumes that an application has a deterministic memory allocation pattern from one run to another. • The high_mem feature is not supported in batch mode debugging. 14.
156 Debugging with GDB (gdb) thread enable 1 Enabling thread 1 14.11.2 Backtrace Support for Thread Debugging The following commands are available as backtrace support for thread debugging: • bt The bt command provides the stack trace of the current thread that is being executed or the thread that accepts the signal in case of a core file. • thread apply all bt You can use the thread apply all bt command to display the backtrace of all threads.
Chapter 14: HP-UX Configuration-Specific Information 157 • The thread terminates execution, and the resources associated with the terminated thread continues to exist in the application because the thread has not been joined or detached. • The thread uses more than the specified percentage of the stack allocated to the thread. • The number of threads waiting on any pthread object exceeds the specified threshold number. 14.11.3.
158 Debugging with GDB set thread check { [on|off]| [option] [on|off] |[option] [num]} The set thread-check [on|off] command enables or disables advanced thread debugging. This feature is off by default. The set thread-check [on|off] command must be enabled prior to running the application under the debugger, to force the underlying runtime system to collect information on pthread primitives. The advanced thread debugging features can be enabled only if the set thread-check [on] command is enabled.
Chapter 14: HP-UX Configuration-Specific Information 159 This option is used to detect unintentional use of multiple mutexes with the same condition variable by different threads. In the case of applications that use a dynamic pool of mutexes, the cv-multiple-mxs option is not required because this usage is normal and expected application behavior.
160 Debugging with GDB [num]. The debugger transfers the execution control to the user and prints a warning message when this condition is detected. 14.11.3.3 Commands to view information on pthread primitives WDB 5.5 and later versions of the debugger display extended information on pthread primitives for multi-threaded applications running on HP-UX 11i v2, or 11i v3. This feature is available only if the set thread-check [on|off] command is enabled.
Chapter 14: HP-UX Configuration-Specific Information 161 - For 64-bit PA applications, LD_LIBRARY_PATH=/opt/langtools/wdb/lib/pa20_64 2. Explicitly preload the librtc runtime library and start the target application by entering one of the following commands: - For 32 bit IPF applications, LD_PRELOAD=/opt/langtools/lib/hpux32/librtc.so - For 64 bit IPF applications, LD_PRELOAD=/opt/langtools/lib/hpux64/librtc.so - For 32 bit PA applications, LD_PRELOAD=/opt/langtools/lib/librtc.
162 Debugging with GDB 14.11.5.1 Pre-requisites for Batch mode of Thread Debugging The various prerequisites for Batch mode of Thread Debugging are as follows: - The thread-debugging feature in HP WDB is dependent on the availability of the dynamic linker version B.11.19. - Advanced thread-debugging feature requires the pthread tracer library which is available by default on systems running HP-UX 11i v2 or later. Steps to debug threads in batch mode 1. Compile the source files.
Chapter 14: HP-UX Configuration-Specific Information 163 If HP WDB detects any thread error condition during the application run, the error log is output to a file in the current working directory. The output file has the following naming convention: ..threads Where is the process id. 14.11.5.2 Limitations in Batch mode of thread debugging The feature does not obtain the thread-error information in batch mode for forked process in a multiprocessing application.
164 Debugging with GDB or set MPI_FLAGS= ewdb for invoking WDB For more information, see the mpidebug(1) and mpienv(1) manpages. Attaching the debugger to an MPI process (or to any other process that has not been compiled for debugging) can result in the following warning: warning: reading ’r3’ register: No data 14.13 Debugging multiple processes ( programs with fork and vfork calls) 14.13.
Chapter 14: HP-UX Configuration-Specific Information 165 where exp is an address expression. For example: (gdb) maint info unwind $pc modsched: 0x4000930 ..
166 Debugging with GDB make a packcore.tar.Z file. This is a compressed tar file which contains the core file, the executable, and all the shared libraries that were used by the program when it generated the core file.The core file is removed after it is added to the packcore.tar.Z file. The packcore command has one optional argument, basename, which can be used instead of packcore to make packcore.tar.Z. The packcore.tar.
Chapter 14: HP-UX Configuration-Specific Information 167 % gdb --lcore a.out core. For example: % ./gdb --lcore sample core.24091 HP gdb... Type "show warranty" for warranty/support.... Core was generated by ’sample’.#0 main () at sample.c:10 (gdb) 14.14.2.
168 Debugging with GDB modules. The first instruction in each block associated with the executed branch is displayed. This feature is supported only for compiler versions A.06.15 and later. HP WDB supports the following commands to print the execution path entries in the current frame, or in the current thread: • info exec-path [start_index] [end_index] (aliased to info ep) Lists all the local execution path entries in the current frame.
Chapter 14: HP-UX Configuration-Specific Information 169 14.15.1 Compiler Dependencies for Printing the Execution Path Entries The +pathtrace compiler option provides a mechanism to record program execution control flow into global path tables, local path tables, or both. This saved information enables the debugger to print the execution path entries in the current thread or frame.
170 Debugging with GDB Type "show warranty" for warranty/support. ... (gdb) b main Breakpoint 1 at 0x4000a60:0: file execpath.c, line 7 from a.out. (gdb) r Starting program: a.out Breakpoint 1, main () at execpath.
Chapter 14: HP-UX Configuration-Specific Information 171 Size: 3 \*Total Number of Branch Paths in Current Function Effective entries: 2 \*Number of Branches executed till this instant Current entry: 2 \* Last executed branch number (gdb) i gep Global execution path table: G0 0x4000a80:2 main (execpath.c:10) G1 0x4000bd0:2 main (execpath.
172 Debugging with GDB (gdb) run Starting program: ./address_error Breakpoint 1, main () at ./address_error.c:41 41 fun (count, count*1.1); (gdb) p fun(10, 1.1) Program received signal SIGBUS, Bus error si_code: 0 - BUS_UNKNOWN - Unknown Error. 0x2c38 in fun (i=10, f=0) at ./address_error.c:37 37 count = *p; The program being debugged was signaled while in a function called from GDB. GDB remains in the frame where the signal was received.
Chapter 14: HP-UX Configuration-Specific Information 173 14.19.1 Deferred watchpoints When you try to set a watchpoint in an expression, HP WDB places a deferred watchpoint if HP WDB cannot evaluate the expression. The watchpoint is automatically enabled whenever the expression can be evaluated during the programs execution. This is especially useful when placing the watchpoints on unallocated addresses. 14.19.2 Hardware watchpoints HP WDB provides support for hardware watchpoints on HP-UX 11.x. 14.19.
174 Debugging with GDB • rdp: Deletes all the breakpoints set by the rbp command. This example shows how to set a breakpoint at the start of each procedure that displays information at the breakpoint: (gdb) file a.out Reading symbols from a.out...done. (gdb) rbp Breakpoints set from 170 to 211 Type commands to execute when the breakpoint is hit (one command per line). End with a line saying just "end". >info break >end (gdb) 14.19.5 Support for template breakpoints With HP WDB 5.
Chapter 14: HP-UX Configuration-Specific Information 175 (gdb) symbol-file main.sl Load new symbol table from "main.sl"? (y or n) y Reading symbols from main.sl done. Things don’t appear to work. This command is not the correct thing to do. This command assumes that main.sl is loaded at its link time address. This is not not true for shared libraries. Do not use symbol-file with shared libraries.
176 Debugging with GDB 14.20.4 Privately mapping shared libraries In cases where you attach to a running program and you try to set a breakpoint in a shared library, GDB may generate the following message: The shared libraries were not privately mapped; setting a breakpoint in a shared library will not work until you rerun the program. GDB generates this message because the debugger sets breakpoints by replacing an instruction with a BREAK instruction.
Chapter 14: HP-UX Configuration-Specific Information 177 (gdb) set mapshared off The -mapshared option is implemented on both PA-RISC and Itanium platforms in HP WDB 5.2. This option is provided in the WDB GUI and HP WDB. The default behavior does not change if the -mapshared option for all shared libraries in processes started under the debugger, or dynamically loaded after an attach, are mapped private. 14.20.
178 Debugging with GDB java args Prints the current or specified Java frame arguments information java bytecodes Disassembles the given Java method bytecode java heap-histogram Displays the Java heap object histogram java instances Locates the instances of the given klassOop in the Java heap.
Chapter 14: HP-UX Configuration-Specific Information 179 14.21.4 Support for 64-bit Java, C, aC++ stack unwinding This release of HP WDB can show stack traces of mixed Java, C, and C++ programs in the 64-bit mode. The stack trace functionality requires Java SDK version 1.4 or later for HP-UX. Please check the HP web site for Java, http://www.hp.com/go/ java, for availability of Java SDK version 1.4 or later.
180 Debugging with GDB /* off 480 bits, len 32 bits */ 14.21.6 Support for __fpreg data type on IPF WDB internally converts __fpreg data type to long double data type to evaluate an expression or to print the value of the expression. Since long double data type has only 15 bit exponent as opposed to 17 bit exponent of __fpreg, some precision is lost when the exponent is larger than that can fit in 15 bits. 14.21.
Chapter 14: HP-UX Configuration-Specific Information 181 The debugger recognizes using declarations, using directives, namespace aliases, nested namespaces, and unqualified lookup within a namespace. It also recognizes using directives and aliases, and using declarations within namespaces. When the debugger has a list of possible resolutions for a given symbol, it displays a menu that shows all names fully qualified whenever namespaces are involved. You can choose the appropriate symbol from the list.
182 Debugging with GDB When you use the log command, the debugger saves a snapshot of the current session, from the start of the session to the point where you issued the log command. Each time you use the log command, HP WDB overwrites the specified log file with a new snapshot from the start of the session.
Chapter 14: HP-UX Configuration-Specific Information 183 14.23.2 Support for Fortran array slices HP WDB prints Fortran array slices if you specify a range of elements by the Fortran 90 array section syntax. For instance, for an array X declared by REAL, DIMENSION(1:1, 2:10) :: X, you could print all five even-numbered elements of the row with the first dimension equal to 0 by typing the WDB command print X(0,2:10:2). 14.23.
184 Debugging with GDB To execute the steplast command in C++ compiled applications, you must compile the application using the HP aC++ version A.03.50 or later with the -g0 option. In C++, the steplast command is helpful while debugging heavy templated functions, because it directly steps into the call, thus skipping the constructor calls, if any. This behavior is unlike the step command that steps into the constructor itself. Consider the following example: void call_me ( string s ) ...
Chapter 14: HP-UX Configuration-Specific Information 185 The following commands evaluate the name of a function and hence are affected by the optimization level of the program being debugged (in particular, due to inlining): • break • call • clear • disassem • list The following commands evaluate an expression referring to variables in the user program and hence, are affected by the optimization level of the program being debugged: • break • call • cond • jump • return • print • set • watch • whatis
186 Debugging with GDB • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • core delete define detach disable enable * exec file forw handle * help * ignore kill load nexti path quit rev run set args, set env, set show args, show signal source stepi symbol target tty undisplay unset env until 14.25.1 Debugging Optimized Code at Various Optimization Levels The following sections describe debugging optimized code support at each optimization level. 14.25.1.
Chapter 14: HP-UX Configuration-Specific Information 187 local variables may be examined, except for unused variables (which may be eliminated). New values may be assigned to a global and a local variable (set = ) when stepping by line (step/next/break ). However, while stepping by instruction (stepi/nexti) at optimization level +O1, assign a value to a variable only if stopped at the very first instruction. This is a must as local optimizations are performed within a statement.
188 Debugging with GDB of certain instructions, such as wtop, wexit, and frcpa, which modify the processor state even when predicated false. In such cases, the debugger stops at the instructions irrespective of the predicate value of the instructions. Assembly and low-level programmers, who require the old behavior of the debugger to stop at the instructions irrespective of the predicate value of these instructions, can explicitly turn off this feature.
Chapter 14: HP-UX Configuration-Specific Information 189 • Start the process in one terminal and attach to it with Visual Interface for WDB. • Use the ‘tty’ command at the debugger prompt so the program’s input and output are directed to another terminal. Note: if the underlying GDB terminates abnormally when you are using Visual Interface for WDB, do not close the Visual Interface for WDB window. Wait for a minute or two.
190 Debugging with GDB • Two rows of labeled softkeys at the bottom of the display give you quick access to common commands. Visual Interface for WDB GUI display 33 #include 34 #include "Deck.h" 35 #include "Player.h" 36 #include "House.h" 37 38 int main () 39 { *> 40 srand ((int) time(0)); 41 42 Deck theDeck; 43 Player thePlayer (100); 44 House theHouse (16); 45 46 theHouse.Instructions(); 47 } File: BlackJack.
Chapter 14: HP-UX Configuration-Specific Information 191 14.26.3 Specifying foreground and background colors To change the foreground and background colors, update the ‘.Xdefaults’ file in the home directory. The resources are the same as for ‘hpterm’. Here is a sample entry: HPterm*foreground: white HPterm*background: rgb:68/90/C4 14.26.
192 Debugging with GDB If you use xterm and dtterm, update the ‘.Xdefaults’ file with keyboard translations to get the shifted arrows and shifted paging keys to work. For xterm, use the following: XTerm*vt100.
Chapter 14: HP-UX Configuration-Specific Information ‘n’ ‘N’ Repeat search ‘%’ Match braces ‘[[’ ‘]]’ Skip to the next procedure 193 ‘:line number ’ Go to any line number All these commands require you to escape to ‘vi’ command mode first. When you are done, type a for append or i for insert or other ‘vi’ commands to return to text insertion mode. Or you can simply click the Prompt softkey. 14.26.8 Loading source files Escape to ‘vi’ command mode and use the :e command to load a source file.
194 Debugging with GDB 2. Choose "Save Session to vdb.pid" from the pop-up menu. The debugger writes the input and output to a file whose name ends in the pid of the debugger. If you save the session more than once, the new transactions are appended to the file. 14.27 Support for ddd GDB works with ddd, the free GDB GUI shell available at http://mumm.ibr.cs.tu-bs.de/. While this is not formally supported by Hewlett-Packard, these two do work together.
Chapter 14: HP-UX Configuration-Specific Information 195 14.30.1 Support for command line calls in a stripped executable on PA-RISC systems In WDB, to perform command line calls in a shared library without the help of dynamic linker (using end.o), you must execute the following command: chatr -B immediate In addition, modify all the calls to shl_load() to specify BIND_IMMEDIATE.
196 Debugging with GDB • In the +std link mode, GDB supports this feature without any changes. You must export the __wdb_call_dummy symbol as shown in the next line. • In the +compat link mode, execute the following command: cc +DD64-g file.c -Wl,+ee,__wdb_call_dummy -s 14.30.3 Support for debugging stripped binaries HP WDB provides limited support for debugging stripped binaries. 14.30.3.
Chapter 14: HP-UX Configuration-Specific Information 197 The which command does not work for global and type symbols since they do not contain line information. Syntax: which For example : (gdb) which i Line 4 of "example.c" block starts at address 0x29a8 and ends at 0x29e4 14.32 Linux support Linux Runtime Environment (LRE) on HP-UX Itanium enables users to execute Intel Itanium Linux applications on HP-UX.
198 Debugging with GDB
Chapter 15: The HP-UX Terminal User Interface 199 15 The HP-UX Terminal User Interface By default, GDB runs in line mode. For users who prefer an interface similar (though not identical) to that of the XDB debugger, HP provides a terminal user interface (TUI), which appears when you invoke the gdb command with the -tui option. Use the -xdb option to enable the use of a number of XDB commands. See the Chapter 16 [XDB to WDB Transition Guide], page 213. 15.
200 Debugging with GDB The terminal window is divided into two panes: a Source pane at the top and a Command pane at the bottom. In the middle is a locator bar that shows the current file, procedure, line, and program counter (PC) address, when they are known to the debugger. When you set a breakpoint on the main program by issuing the command b main an asterisk (*) appears opposite the first executable line of the program.
Chapter 15: The HP-UX Terminal User Interface 201 15.2 Automatically running a program at startup WDB does not start running the target executable at startup as do ‘xdb’ and HP DDE. This makes it easy to set break points before the target program’s main function. To make WDB automatically start running the target program add these lines to your startup file, ‘.gdbinit’: break main run 15.
202 Debugging with GDB Figure 3 |----------------------------------------------------------------------| |;;; print_average (my_list, first, last); | *>|0x3524 addil L’-0x800,%dp,%r1 | |0x3528 ldo 0x730(%r1),%r26 | |0x352c ldi 9,%r24 | |0x3530 ldi 0,%r25 | |0x3534 ldil L’0x3000,%r31 | |0x3538 be,l 0x498(%sr4,%r31) | |0x353c copy %r31,%rp | |;;; print_average (my_list, first, last - 3); | |0x3540 addil L’-0x800,%dp,%r1 | |0x3
Chapter 15: The HP-UX Terminal User Interface 203 :......................................................................: *>:32 print_average (my_list, first, last); : :33 print_average (my_list, first, last - 3); : :34 } : :35 : :36 : :37 : :......................................................................
204 Debugging with GDB :.........................................................................: :flags 29000041 r1 51a800 rp 7f6ce597 : :r3 7f7f0000 r4 1 r5 7f7f06f4 : :r6 7f7f06fc r7 7f7f0800 r8 7f7f0800 : :r9 40006b10 r10 0 r11 40004b78 : :r12 1 r13 0 r14 0 : :r15 0 r16 40003fb8 r17 4 : :.........................................................................
Chapter 15: The HP-UX Terminal User Interface 205 :.........................................................................: :flags 29000041 r1 51a800 rp 7f6ce597 : :r3 7f7f0000 r4 1 r5 7f7f06f4 : :r6 7f7f06fc r7 7f7f0800 r8 7f7f0800 : :r9 40006b10 r10 0 r11 40004b78 : :r12 1 r13 0 r14 0 : :r15 0 r16 40003fb8 r17 4 : :.........................................................................
206 Debugging with GDB 15.5 Changing pane focus The command pane always has keyboard focus, so that you can enter debugger commands. If there is only one other pane (Source or Disassembly), the other pane has the logical focus, so that you can scroll within that pane by using the arrow keys or the hPage Upi and hPage Downi keys (on some keyboards these are hPrevi and hNexti). Note: In the command pane, the scrolling behavior only works for an ‘hpterm’ and not for an ‘xterm’ or ‘dtterm’.
Chapter 15: The HP-UX Terminal User Interface 207 :.........................................................................: :flags 29000041 r1 51a800 rp 7f6ce597 : :r3 7f7f0000 r4 1 r5 7f7f06f4 : :r6 7f7f06fc r7 7f7f0800 r8 7f7f0800 : :r9 40006b10 r10 0 r11 40004b78 : :r12 1 r13 0 r14 0 : :r15 0 r16 40003fb8 r17 4 : :.........................................................................
208 Debugging with GDB |-------------------------------------------------------------------------| |flags 29000041 r1 51a800 rp 7f6ce597 | |r3 7f7f0000 r4 1 r5 7f7f06f4 | |r6 7f7f06fc r7 7f7f0800 r8 7f7f0800 | |r9 40006b10 r10 0 r11 40004b78 | |r12 1 r13 0 r14 0 | |r15 0 r16 40003fb8 r17 4 | |-------------------------------------------------------------------------| *>:32 print_average (my_list, first, last); : :33 print_average (my_list, first, last - 3); : :34 } : :35 : :36 : :37 : :..................
Chapter 15: The HP-UX Terminal User Interface 209 fr display $fregs Display the floating-point registers. sr display $sregs Display the special registers. gr display $gregs Display the general registers.
210 Debugging with GDB The window looks like this: Figure 10 |-------------------------------------------------------------------------| |fpsr 0 fpe1 0 | |fpe2 0 fpe3 0 | |fpe4 0 fpe5 0 | |fpe6 0 fpe7 0 | |fr4 0 fr4R 0 | |fr5 1.0000000000000011 fr5R 7.00649232e-45 | |-------------------------------------------------------------------------| *>:32 print_average (my_list, first, last); : :33 print_average (my_list, first, last - 3); : :34 } : :35 : :36 : :37 : :..........................................
Chapter 15: The HP-UX Terminal User Interface 211 wh src +3 increases the size of the source pane, and decreases the size of the command pane, by 3 lines. To find out the current sizes of all panes, use the info win command.
212 Debugging with GDB
Chapter 16: XDB to WDB Transition Guide 213 16 XDB to WDB Transition Guide This transition aid is designed for XDB users who are learning WDB, an HP-supported version of the industry-standard GDB debugger. Select one of these lists for a table that shows WDB equivalents for many common XDB commands and other features. Invoke WDB with the command gdb -tui to obtain a terminal user interface (TUI) similar to that provided by XDB. Commands marked "(with -tui)" are valid when you use the -tui option.
214 Debugging with GDB • Section 16.2.5 [Global Breakpoint Commands], page 225. • Section 16.2.6 [Assertion Control Commands], page 225. • Section 16.2.7 [Record and Playback Commands], page 225. • Section 16.2.8 [Macro Facility Commands], page 226. • Section 16.2.9 [Signal Control Commands], page 226. • Section 16.2.10 [Miscellaneous Commands], page 227. 16.1.1 Invocation commands By default, HP WDB runs in line mode. To run it with a terminal user interface similar to that of XDB, use the -tui option.
Chapter 16: XDB to WDB Transition Guide 215 {+ | -}r {+ | -}r (with -xdb -tui), {+ | -} data (with -tui) Scroll floating-point registers forward or backward (src, cmd, and asm are also valid window names) fr fr (with -xdb -tui), display $fregs (with -tui) Display registers gr gr (with -xdb -tui), display $regs (with -tui) Display general registers sr sr (with -xdb -tui), display $sregs (with -tui) Display special registers td td (with -xdb -tui) Toggle mode tf tf (with -xdb -tui), toggle $
216 Debugging with GDB search Search source forward for [last] string ?[string] ?[string] (with -xdb), rev regexp Search source backward for [last] string D "dir" D "dir" /[string] /[string] (with -xdb), regexp, forw regexp (with -xdb), dir pathname L L (with -xdb) ld ld (with Add a directory search path for source files Show current viewing location or current point of execution directories List source directory search path (list all directories) lf lf (with -xdb), info sources List
Chapter 16: XDB to WDB Transition Guide 217 16.1.4 Source directory mapping commands Use the D or dir command to add new directories to be searched for source files. See See Section 16.1.3 [XDB-fil], page 215. GDB does not provide a source directory mapping capability and therefore does not have any equivalent of the apm, dpm, and lpm commands. 16.1.5 Data Viewing and modification commands There are many info commands in addition to those shown here. Use help info to get a list.
218 lr string Debugging with GDB lr string (with -xdb), info reg List matching registers string ls [string] No equivalent List all (or matching) special variables mm info sharedlibrary Show memory map of all loaded shared libraries mm string No equivalent Show memory map of matching loaded shared libraries p expr[\format p[/format expr [Note: The count and size portions of formats are not allowed in the p (print) command.
Chapter 16: XDB to WDB Transition Guide pq {+ | 219 No equivalent Evaluate next/previous memory location using format -}[\format 16.1.6 Stack viewing commands The GDB concept of the top and bottom of the stack is the opposite of XDB, so the XDB up is GDB down.
220 Debugging with GDB XDB Command WDB Equivalent Meaning I info (many kinds), show (many Display state of debugger and program kinds) 16.1.
Chapter 16: XDB to WDB Transition Guide 221 r [arguments] r [arguments] Run with last arguments [or with new arguments] R R (with -xdb), r Rerun with no arguments s s, si Single step (into procedures) (si: step by instruction) s number s number, si number Single step number steps (into procedures) (si: step by instruction) S S (with -xdb), n, ni Step over (ni: step over by instruction) S number S number (with -xdb), n number, Step over by number statements or instructions (ni: step over b
222 Debugging with GDB "any string" p "any string" Print any string if expr if expr cmds [else cmds] end Conditionally execute cmds Q (with -xdb), silent (must be Quiet breakpoints {cmds} [{cmds}] Q first command in a commands list) 16.2.2 Breakpoint creation commands The GDB equivalent of the count and cmds arguments is to use the commandsbnum command to set an ignore count and/or to specify commands to be executed for that breakpoint.
Chapter 16: XDB to WDB Transition Guide 223 bi -C expr No equivalent Set an instance breakpoint at first executable line of all nonstatic member functions of the instance’s class (base classes included) bpc -c class rb ^class::* Set a class breakpoint at first executable line of all member functions of the instance’s class (no base classes) bpc -C class Use rb ^class::* for base classes also Set a class breakpoint at first executable line of all member functions of the class (base classes included
224 Debugging with GDB XDB Command WDB Equivalent Meaning ab number enable number Activate suspended breakpoint of the given number ab * enable Activate all suspended breakpoints ab @sharedlibrary No equivalent Activate suspended breakpoints in named shared library bc number expr bc number expr (with -xdb), ignorenumber expr (within a Set a breakpoint count commands list) db clear Delete breakpoint at current line db number delete number Delete breakpoint of the given number db * del
Chapter 16: XDB to WDB Transition Guide 225 Dpx 16.2.5 Global breakpoint commands The following table lists the XDB and equivalent WDB commands for setting global breakpoints: XDB Command WDB Equivalent Meaning abc cmds No exact equivalent, but display expr is equivalent to abc print Set or delete cmds to execute at every stop expr dbc undisplay Stop displaying values at each stop 16.2.6 Assertion control commands GDB does not provide the ability to trace by instruction.
226 Debugging with GDB To display the current history status, use show history. For an equivalent of the XDB record-all facility, pipe the output of the gdb command to the tee(1) command. For example: gdb a.out | tee mylogfile This solution works with the default line-mode user interface, not with the terminal user interface. 16.2.8 Macro facility commands Use the show user or help user-defined command to obtain a list of all user-defined commands.
Chapter 16: XDB to WDB Transition Guide z number r 227 z number r (with -xdb), handle number print, handle number Toggle report flag for signal number noprint z number Q z number Q (with -xdb), handle number noprint Do not print the new state of the signal 16.2.
228 Debugging with GDB q q Quit debugger sm sm (with -xdb), set height 0 Suspend more (turn off pagination) ss file No equivalent Save (breakpoint, macro, assertion) state tc No equivalent Toggle case sensitivity in searches 16.3 XDB data formats and HP WDB equivalents The format of the print command is different in XDB and GDB: XDB: GDB: p expr \fmt p/fmt expr Use the set print pretty command to obtain a structured display similar to the default XDB display.
Chapter 16: XDB to WDB Transition Guide 229 E (1) No equivalent e floating-point notation as double f No equivalent f floating-point notation as float F (1) No equivalent f floating-point notation as double g f g floating-point notation as float G (1) f g floating-point notation as double i Use x/i command Machine instruction (disassembly) k No equivalent Formatted structure display K (1) No equivalent Formatted structure display with base classes n print Normal (default) format,
230 Debugging with GDB t whatis, ptype Show type of the expression T (1) ptype Show type of expression, including base class information u u Expression in unsigned decimal format U (1) u Expression in long unsigned decimal format w No equivalent Wide character string W (1) No equivalent Address of wide character string x x Print in hexadecimal X (1) x Print in long hexadecimal z t Print in binary Z (1) t Print in long binary (1) HP WDB will display data in the size appropriat
Chapter 16: XDB to WDB Transition Guide 231 proc proc Procedure name [file:]proc[:proc[...]][:line] No equivalent Source line and code address [file:]proc[:proc[...
232 Debugging with GDB 16.6 XDB special variables and HP WDB equivalents GDB does not provide special variables of the kind that XDB has, but you can use show and set to display and modify many debugger settings.
Chapter 16: XDB to WDB Transition Guide 233 $step No equivalent Number of instructions debugger will step in non-debuggable procedures before free-running $var $var Define or use special variable (convenience variable) 16.
234 Debugging with GDB • Section 16.8.9 [U through Z], page 242. • Section 16.8.10 [Symbols], page 244. 16.8.1 A XDB Command Equivalent WDB Command a [cmds] No equivalent aa number No equivalent aa * No equivalent ab number enable number ab * enable ab @shared-library No equivalent abc cmds No exact equivalent, but display expr is equivalent to abc print expr am am (with -xdb), set height num apm oldpath [newpath] No equivalent apm "" [newpath] No equivalent 16.8.
Chapter 16: XDB to WDB Transition Guide 235 b b ba address ba address (with -xdb), b *address bb [depth] No equivalent (use b proc) bc number expr bc number expr (with -xdb), ignore number expr (within a commands list) bi expr.
236 Debugging with GDB bpx cmds No equivalent bt [depth] No equivalent bt proc b proc commands bnum finish c end bu [depth] bu [depth] (with -xdb). The finish command is equivalent to the sequence bu, c, db (to continue out of the current routine). bx [depth] bx [depth] (with -xdb) 16.8.
Chapter 16: XDB to WDB Transition Guide db number delete number db * delete dbc undisplay def name replacement-text def name [GDB prompts for commands] down up down number up number dp No equivalent dpm index No equivalent dpm * No equivalent Dpt No equivalent Dpx No equivalent 16.8.
238 Debugging with GDB g #label No equivalent g {+ | -}lines g {+ | -}lines (with -xdb), go {+ | -}lines tb {+ | -}lines followed by jump {+ | -}lines g {+ | -} g {+ | -} (with -xdb), go {+ | -}1, tb {+ | -}1 followed by jump {+ | -}1 gr gr (with -xdb -tui), display $regs (with -tui) h h if expr {cmds} [{cmds}] if expr cmds [else cmds] end I info (many kinds), show (many kinds) k k 16.8.
Chapter 16: XDB to WDB Transition Guide 239 ld ld (with -xdb), show directories lf lf (with -xdb), info sources lf [string] No equivalent lg [string] lg [string] (with -xdb), info variables [string] ll [string] info functions [string], print msymbols file lm [string] show user [string] lo [[class]::][string] info func [[class]::][string] lp info functions lp [[class]::]string info func [[class]::]string info addr [[class]::]string lpm No equivalent lr lr (with -xdb), info all-reg lr
240 Debugging with GDB M[{t | c} [expr[; expr...]]] No equivalent mm info sharedlibrary mm string No equivalent N fo or rev n fo or rev p expr[\format] p[/format] expr [Note: The count and size portions of formats are not allowed in the p (print) command. They are allowed in the x command (examine memory).
Chapter 16: XDB to WDB Transition Guide 241 XDB Command Equivalent WDB Command q q Q Q (with -xdb), silent (must be first command in a commands list) r [arguments] r [arguments] R R (with -xdb), r s s, si s number s number, si number S S (with -xdb), n, ni S number S number (with -xdb), n number, ninumber sa number No equivalent sa * No equivalent sb number disable number sb * disable sb @shared-library No equivalent sm sm (with -xdb), set height 0 sr sr (with -xdb -tui), di
242 ss file Debugging with GDB No equivalent 16.8.8 T XDB Command Equivalent WDB Command t [depth] t [depth] (with -xdb), bt [depth] T [depth] T [depth] (with -xdb), bt full [depth] ta No equivalent tb No equivalent tc No equivalent td td (with -xdb -tui) tf tf (with -xdb -tui), toggle $fregs (with -tui) tm No equivalent top frame 0 tr [@] No equivalent ts ts (with -xdb -tui) 16.8.
Chapter 16: XDB to WDB Transition Guide 243 u u (with -xdb -tui), update (with -tui) U U (with -xdb -tui), refresh (with -tui) undef name def name [follow with empty command list] undef * No equivalent up down up number down number v v (with -xdb), list v location v location (with -xdb), list location V [depth] V [depth] (with -xdb), frame [depth] va address va address (with -xdb), disas address va label va label (with -xdb), disas label va label + offset va label + offset (with -xd
244 Debugging with GDB xdb -d dir gdb -xdb -d dir xdb -P pid program gdb -xdb program pid xdb -i (after starting) run < file xdb -o (after starting) run > file z number s z number s (with -xdb), handle number stop, handle number nostop z number i z number i (with -xdb), handle number nopass, handle number pass z number r z number r (with -xdb), handle number print, handle number noprint z number Q z number Q (with -xdb), handle number noprint 16.8.
Chapter 16: XDB to WDB Transition Guide 245 [class]::proc [class]::proc [class]::proc[:line] No equivalent [class]::proc[#label] No equivalent proc#line No equivalent [class]::proc#line No equivalent name@shared-library No equivalent var var class::var class::var (bug: not yet) [[class]::]proc:[class::]var proc::var (static variables only) [[class]::]proc:depth:[class::]var No equivalent Return Return "any string" p "any string" .
246 Debugging with GDB {+ | -}[number] {+ | -}[ number] (with -tui; note that a space is required between + or - and the number) /[string] /[string] (with -xdb), search regexp, forw regexp ?[string] ?[string] (with -xdb), rev regexp ; No equivalent (one command per line in command list) :var or ::var ::var ! cmd line ! cmd line (with -xdb), she cmd line {cmd list} commands [number] ...
Chapter 16: XDB to WDB Transition Guide 247 >@file No equivalent >> No equivalent >>file No equivalent >>@ No equivalent >>@file No equivalent Control-C Control-C # [text] # [text] #label No equivalent
248 Debugging with GDB
Chapter 17: Controlling GDB 249 17 Controlling GDB You can alter the way GDB interacts with you by using the set command. For commands controlling how GDB displays data, see Section 8.7 [Print settings], page 70. Other settings are described here. 17.1 Setting the GDB Prompt GDB indicates its readiness to read a command by printing a string called the prompt. This string is normally ‘((gdb))’. You can change the prompt string with the set prompt command.
250 Debugging with GDB set editing-mode vi The readline interface uses the ‘.inputrc’ file to control the settings. set history filename fname Set the name of the GDB command history file to fname. This is the file where GDB reads an initial command history list, and where it writes the command history from this session when it exits. You can access this list through history expansion or through the history command editing characters listed below.
Chapter 17: Controlling GDB 251 show commands Display the last ten commands in the command history. show commands n Print ten commands centered on command number n. show commands + Print ten commands just after the commands last printed. 17.4 Setting the GDB Screen Size Certain commands to GDB may produce large amounts of information output to the screen. To help you read all of it, GDB pauses and asks you for input at the end of each page of output.
252 Debugging with GDB set radix 012 set radix 10. set radix 0xa sets the base to decimal. On the other hand, ‘set radix 10’ leaves the radix unchanged no matter what it was. set output-radix base Set the default base for numeric display. Supported choices for base are decimal 8, 10, or 16. base must itself be specified either unambiguously or using the current default radix. show input-radix Display the current default base for numeric input.
Chapter 17: Controlling GDB 253 Start it from the beginning? (y or n) If you are willing to unflinchingly face the consequences of your own commands, you can disable this “feature”: set confirm off Disables confirmation requests. set confirm on Enables confirmation requests (the default). show confirm Displays state of confirmation requests. 17.7 Optional messages about internal happenings set debug arch Turns on or off display of gdbarch debugging info.
254 Debugging with GDB show debug serial Displays the current state of displaying GDB serial debugging info. set debug target Turns on or off display of GDB target debugging info. This info includes what is going on at the target level of GDB, as it happens. The default is off. show debug target Displays the current state of displaying GDB target debugging info. set debug varobj Turns on or off display of GDB variable object debugging info. The default is off.
Chapter 18: Canned Sequences of Commands 255 18 Canned Sequences of Commands In addition to breakpoint commands (see Section 5.1.6 [Breakpoint command lists], page 41), GDB provides the following two ways to store sequence of commands for execution as a unit: • user-defined commands • command files 18.1 User-defined commands A user-defined command is a sequence of GDB commands to which you assign a new name as a command. This is done with the define command.
256 Debugging with GDB You may use the document command again to change the documentation of a command. Redefining the command with define does not change the documentation. help user-defined List all user-defined commands, with the first line of the documentation (if any) for each. show user show user commandname Display the GDB commands used to define commandname (but not its documentation). If no commandname is given, display the definitions for all userdefined commands.
Chapter 18: Canned Sequences of Commands 257 If you try to define a hook which does not match any known command, GDB issues a warning from the define command. 18.3 Command files A command file for GDB is a file of lines that are GDB commands. Comments (lines starting with #) may also be included. An empty line in a command file does nothing; it does not mean to repeat the last command, as it would from the terminal. When you start GDB, it executes commands from its init files. These are files named ‘.
258 Debugging with GDB 18.4 Commands for controlled output During the execution of a command file or a user-defined command, normal GDB output is suppressed; the only output that appears is what is explicitly printed by the commands in the definition. This section describes three commands useful for generating exactly the output you want. echo text Print text. Nonprinting characters can be included in text using C escape sequences, such as ‘\n’ to print a newline.
Chapter 19: Using GDB under gnu Emacs 259 19 Using GDB under gnu Emacs A special interface allows you to use gnu Emacs to view (and edit) the source files for the program you are debugging with GDB. To use this interface, use the command M-x gdb in Emacs. Give the executable file you want to debug as an argument. This command starts GDB as a subprocess of Emacs, with input and output through a newly created Emacs buffer.
260 Debugging with GDB C-h m Describe the features of Emacs’ GDB Mode. M-s Execute to another source line, like the GDB step command; also update the display window to show the current file and location. M-n Execute to next source line in this function, skipping all function calls, like the GDB next command. Then update the display window to show the current file and location. M-i Execute one instruction, like the GDB stepi command; update display window accordingly.
Chapter 20: GDB Annotations 261 20 GDB Annotations This chapter describes annotations in GDB. Annotations are designed to interface GDB to graphical user interfaces or other similar programs which want to interact with GDB at a relatively high level. 20.1 What is an annotation? To produce annotations, start GDB with the --annotate=2 option. Annotations start with a newline character, two ‘control-z’ characters, and the name of the annotation.
262 Debugging with GDB The server prefix does not affect the recording of values into the value history; to print a value without recording it into the value history, use the output command instead of the print command. 20.3 Values When a value is printed in various contexts, GDB uses annotations to delimit the value from the surrounding text.
Chapter 20: GDB Annotations 263 ^Z^Zarray-section-begin array-index value-flags where array-index is the index of the first element being annotated and value-flags has the same meaning as in a value-history-begin annotation.
264 Debugging with GDB • A normal frame.
Chapter 20: GDB Annotations 265 ^Z^Zdisplay-number-end number-separator ^Z^Zdisplay-format format ^Z^Zdisplay-expression expression ^Z^Zdisplay-expression-end expression-separator ^Z^Zdisplay-value value ^Z^Zdisplay-end where number is the number of the display, number-separator is intended to separate the number from what follows for the user, format includes information such as the size, format, or other information about how the value is being displayed, expression is the expression being displayed, e
266 Debugging with GDB ^Z^Zerror This annotation occurs right before GDB responds to an error. Quit and error annotations indicate that any annotations which GDB was in the middle of may end abruptly. For example, if a value-history-begin annotation is followed by a error, one cannot expect to receive the matching value-history-end. One cannot expect not to receive it either; however, an error annotation does not necessarily mean that GDB is immediately returning all the way to the top level.
Chapter 20: GDB Annotations 267 20.9 Invalidation notices The following annotations say that certain pieces of state may have changed: ^Z^Zframes-invalid The frames (for example, output from the backtrace command) may have changed. ^Z^Zbreakpoints-invalid The breakpoints may have changed. For example, the user just added or deleted a breakpoint. 20.10 Running the program When the program starts executing due to a GDB command such as step or continue, ^Z^Zstarting is output.
268 Debugging with GDB 20.
Chapter 21: The gdb/mi Interface 269 21 The gdb/mi Interface Function and purpose gdb/mi is a line based machine oriented text interface to GDB. It is specifically intended to support the development of systems which use the debugger as just one small component of a larger system. This chapter is a specification of the gdb/mi interface. It is written in the form of a reference manual. Notation and terminology This chapter uses the following notation: • | separates two alternatives.
270 Debugging with GDB operation 7→ any of the operations described in this chapter non-blank-sequence 7→ anything, provided it doesn’t contain special characters such as "-", nl, """ and of course " " c-string 7→ """ seven-bit-iso-c-string-content """ nl 7→ CR | CR-LF Notes: • The CLI commands are still handled by the mi interpreter; their output is described below. • The token , when present, is passed back when the command finishes.
Chapter 21: The gdb/mi Interface 271 async-output 7→ async-class ( "," result )* nl result-class 7→ "done" | "running" | "connected" | "error" | "exit" async-class 7→ "stopped" | others (where others will be added depending on the needs—this is still in development).
272 Debugging with GDB • target-stream-output is the output produced by the target program. All the target output is prefixed by ‘@’. • log-stream-output is output text coming from GDB’s internals, for instance messages that should be displayed as part of an error log. All the log output is prefixed by ‘&’. • New gdb/mi commands should only output lists containing values. See Section 21.3.2 [gdb/mi Stream Records], page 273, for more details about the various output records. 21.1.
Chapter 21: The gdb/mi Interface 273 21.2 gdb/mi compatibility with CLI To help users get familiar with GDB CLI, GBB/MI accepts existing CLI commands. As specified by the syntax, such commands can be directly entered into the gdb/mi interface and GDB will respond. This mechanism is provided as an aid to developers of gdb/mi clients and not as a reliable interface into the CLI.
274 Debugging with GDB 21.3.3 gdb/mi out-of-band records Out-of-band records are used to notify the gdb/mi client of additional changes that have occurred. Those changes can either be a consequence of gdb/mi (e.g., a breakpoint modified) or a result of target activity (e.g., target stopped). The following is a preliminary list of possible out-of-band records. "*" "stop" 21.4 gdb/mi command description format The remaining sections describe blocks of commands.
Chapter 21: The gdb/mi Interface 275 Example 21.5 gdb/mi breakpoint table commands This section documents gdb/mi commands for manipulating breakpoints. The -break-after Command Synopsis -break-after number count The breakpoint number number is not in effect until it has been hit count times. To see how this is reflected in the output of the ‘-break-list’ command, see the description of the ‘-break-list’ command below. GDB command The corresponding GDB command is ‘ignore’.
276 Debugging with GDB Synopsis -break-condition number expr Breakpoint number will stop the program only if the condition in expr is true. The condition becomes part of the ‘-break-list’ output (see the description of the ‘-break-list’ command below). GDB command The corresponding GDB command is ‘condition’.
Chapter 21: The gdb/mi Interface 277 -break-delete 1 ^done (gdb) -break-list ^done,BreakpointTable={nr_rows="0",nr_cols="6", hdr=[{width="3",alignment="-1",col_name="number",colhdr="Num"}, {width="14",alignment="-1",col_name="type",colhdr="Type"}, {width="4",alignment="-1",col_name="disp",colhdr="Disp"}, {width="3",alignment="-1",col_name="enabled",colhdr="Enb"}, {width="10",alignment="-1",col_name="addr",colhdr="Address"}, {width="40",alignment="2",col_name="what",colhdr="What"}], body=[]} (gdb) The -br
278 Debugging with GDB Synopsis -break-enable ( breakpoint )+ Enable (previously disabled) breakpoint(s). GDB command The corresponding GDB command is ‘enable’.
Chapter 21: The gdb/mi Interface 279 Synopsis -break-insert [ -t ] [ -h ] [ -r ] [ -c condition ] [ -i ignore-count ] [ -p thread ] [ line | addr ] If specified, line, can be one of: • function • filename:linenum • filename:function • *address The possible optional parameters of this command are: ‘-t’ Insert a temporary breakpoint. ‘-h’ Insert a hardware breakpoint. ‘-c condition ’ Make the breakpoint conditional on condition. ‘-i ignore-count ’ Initialize the ignore-count.
280 Debugging with GDB ^done,bkpt=number="2",type="breakpoint",disp="keep",enabled="y",addr="0x00010774", file="recursive2.
Chapter 21: The gdb/mi Interface 281 ^done,BreakpointTable={nr_rows="2",nr_cols="6", hdr=[{width="3",alignment="-1",col_name="number",colhdr="Num"}, {width="14",alignment="-1",col_name="type",colhdr="Type"}, {width="4",alignment="-1",col_name="disp",colhdr="Disp"}, {width="3",alignment="-1",col_name="enabled",colhdr="Enb"}, {width="10",alignment="-1",col_name="addr",colhdr="Address"}, {width="40",alignment="2",col_name="what",colhdr="What"}], body=[bkpt={number="1",type="breakpoint",disp="keep",enabled="y
282 Debugging with GDB ^running (gdb) *stopped,reason="watchpoint-trigger",wpt=number="2",exp="i",value=old="0",new="7" ,thread-id="1",frame=addr="0x000029c4",func="main",args=[],file="hello.c",line="8" (gdb) Setting a watchpoint on a variable local to a function. GDB will stop the program execution twice: first for the variable changing value, then for the watchpoint going out of scope.
Chapter 21: The gdb/mi Interface 283 -exec-continue ^running (gdb) *stopped,reason="watchpoint-scope",wpnum="2",thread-id="1",frame=addr="0x000029ec", func="main",args=[],file="hello.
284 Debugging with GDB Result The output for each instruction is composed of four fields: • Address • Func-name • Offset • Instruction Note that whatever included in the instruction field, is not manipulated directly by gdb/mi, i.e. it is not possible to adjust its format. GDB command There is no direct mapping from this command to the CLI.
Chapter 21: The gdb/mi Interface 285 inst="save %sp, -112, %sp"}, {address="0x000107c0",func-name="main",offset="4", inst="mov 2, %o0"}, {address="0x000107c4",func-name="main",offset="8", inst="sethi %hi(0x11800), %o2"}] (gdb) Disassemble 3 instructions from the start of main in mixed mode: (gdb) -data-disassemble -f basics.c -l 32 -n 3 -- 1 ^done,asm_insns=[ src_and_asm_line={line="31", file="/kwikemart/marge/ezannoni/flathead-dev/devo/gdb/ \ testsuite/gdb.mi/basics.
286 Debugging with GDB 411^done,value="4" (gdb) 511-data-evaluate-expression "A + 3" 511^done,value="4" (gdb) The -data-list-changed-registers Command Synopsis -data-list-changed-registers Display a list of the registers that have changed. GDB command GDB doesnot have a direct analog for this command; gdbtk has the corresponding command ‘gdb_changed_register_list’.
Chapter 21: The gdb/mi Interface 287 GDB command GDB does not have a command which corresponds to ‘-data-list-register-names’. In gdbtk there is a corresponding command ‘gdb_regnames’.
288 Debugging with GDB Example For a PPC MBX board (note: line breaks are for readability only, they donot appear in the actual output): (gdb) -data-list-register-values r 64 65 ^done,register-values=[{number="64",value="0xfe00a300"}, {number="65",value="0x00029002"}] (gdb) -data-list-register-values x ^done,register-values=[{number="0",value="0xfe0043c8"}, {number="1",value="0x3fff88"},{number="2",value="0xfffffffe"}, {number="3",value="0x0"},{number="4",value="0xa"}, {number="5",value="0x3fff68"},{numbe
Chapter 21: The gdb/mi Interface 289 nr-rows nr-cols [ aschar ] where: ‘address ’ An expression specifying the address of the first memory word to be read. Complex expressions containing embedded white space should be quoted using the C convention. ‘word-format ’ The format to be used to print the memory words. The notation is the same as for GDB print command (see Section 8.4 [Output formats], page 66). ‘word-size ’ The size of each memory word in bytes. ‘nr-rows ’ The number of rows in the output table.
290 Debugging with GDB Read two bytes of memory starting at address shorts + 64 and display as a single word formatted in decimal. (gdb) 5-data-read-memory shorts+64 d 2 1 1 5^done,addr="0x00001510",nr-bytes="2",total-bytes="2", next-row="0x00001512",prev-row="0x0000150e", next-page="0x00001512",prev-page="0x0000150e",memory=[ {addr="0x00001510",data=["128"]}] (gdb) Read thirty two bytes of memory starting at bytes+16 and format as eight rows of four columns.
Chapter 21: The gdb/mi Interface GDB command The corresponding GDB command is ‘disable display’. Example N.A. The -display-enable command Synopsis -display-enable number Enable display number. GDB command The corresponding GDB command is ‘enable display’. Example N.A. The -display-insert Command Synopsis -display-insert expression Display expression every time the program stops. GDB command The corresponding GDB command is ‘display’. Example N.A.
292 Debugging with GDB Synopsis -display-list List the displays. Do not show the current values. GDB command The corresponding GDB command is ‘info display’. Example N.A. The -environment-cd command Synopsis -environment-cd pathdir Set the GDB working directory. GDB command The corresponding GDB command is ‘cd’.
Chapter 21: The gdb/mi Interface Example (gdb) -environment-directory /kwikemart/marge/ezannoni/flathead-dev/devo/gdb ^done (gdb) The -environment-path command Synopsis -environment-path ( pathdir )+ Add directories pathdir to beginning of search path for object files. GDB command The corresponding GDB command is ‘path’.
294 Debugging with GDB 21.7 gdb/mi program control Program termination As a result of execution, the inferior program can run to completion, if it doesnot encounter any breakpoints. In this case the output will include an exit code, if the program has exited exceptionally.
Chapter 21: The gdb/mi Interface 295 The -exec-arguments command Synopsis -exec-arguments args Set the inferior program arguments, to be used in the next ‘-exec-run’. GDB command The corresponding GDB command is ‘set args’. Example Donot have one around. The -exec-continue command Synopsis -exec-continue Asynchronous command. Resumes the execution of the inferior program until a breakpoint is encountered, or until the inferior exits. GDB command The corresponding GDB is ‘continue’.
296 Debugging with GDB GDB command The corresponding GDB command is ‘finish’. Example Function returning void. -exec-finish ^running (gdb) @hello from foo *stopped,reason="function-finished",thread-id="1",frame=addr="0x000029ec", func="main",args=[],file="hello.c",line="7file="hello.c",line="7"} (gdb) Function returning other than void. The name of the internal GDB variable storing the result is printed, together with the value itself.
Chapter 21: The gdb/mi Interface 297 (gdb) 222-exec-interrupt 222^done (gdb) 111*stopped,signal-name="SIGINT",signal-meaning="Interrupt", frame={addr="0x00010140",func="foo",args=[],file="try.c",line="13"} (gdb) (gdb) -exec-interrupt ^error,msg="mi_cmd_exec_interrupt: Inferior not executing." (gdb) The -exec-next command Synopsis -exec-next Asynchronous command. Resumes execution of the inferior program, stopping when the beginning of the next source line is reached.
298 Debugging with GDB Example (gdb) -exec-next-instruction ^running (gdb) *stopped,reason="end-stepping-range",threadid="1",frame=addr="0x00002a14",func="main",args=[],file="hello.c",line="24" (gdb) The -exec-return command Synopsis -exec-return Makes current function return immediately. Doesn’t execute the inferior. Displays the new current frame. GDB command The corresponding GDB command is ‘return’.
Chapter 21: The gdb/mi Interface 299 Asynchronous command. Starts execution of the inferior from the beginning. The inferior executes until either a breakpoint is encountered or the program exits. GDB command The corresponding GDB command is ‘run’. Example (gdb) -break-insert main ^done,bkpt=number="1",type="breakpoint",disp="keep",enabled="y",addr="0x00002a08", func="main",file="hello.
300 Debugging with GDB GDB command The corresponding GDB command is ‘step’. Example Stepping into a function: -exec-step ^running (gdb) ~"2" ~"3" *stopped,reason="end-stepping-range",thread-id="1",frame=addr="0x000029d0", func="call",args=[name="a",name="b"],file="hello.c",line="15" (gdb) Regular stepping: -exec-step ^running (gdb) ~"2" ~"3" *stopped,reason="end-stepping-range",thread-id="1",frame=addr="0x000029d8", func="call",args=[name="a",name="b"],file="hello.
Chapter 21: The gdb/mi Interface 301 (gdb) -exec-step-instruction ^running (gdb) *stopped,reason="end-stepping-range", frame={addr="0x000100f4",func="foo",args=[],file="try.c",line="10"} (gdb) The -exec-until command Synopsis -exec-until [ location ] Asynchronous command. Executes the inferior until the location specified in the argument is reached. If there is no argument, the inferior executes until a source line greater than the current one is reached.
302 Debugging with GDB Example (gdb) -file-exec-and-symbols /kwikemart/marge/ezannoni/TRUNK/mbx/hello.mbx ^done (gdb) The -file-exec-file command Synopsis -file-exec-file file Specify the executable file to be debugged. Unlike ‘-file-exec-and-symbols’, the symbol table is not read from this file. If used without argument, GDB clears the information about the executable file. No output is produced, except a completion notification. GDB command The corresponding GDB command is ‘exec-file’.
Chapter 21: The gdb/mi Interface 303 Synopsis -file-list-exec-source-files List the source files for the current executable. GDB command There’s no GDB command which directly corresponds to this one. gdbtk has an analogous command ‘gdb_listfiles’. Example N.A. The -file-list-shared-libraries Command Synopsis -file-list-shared-libraries List the shared libraries in the program. GDB command The corresponding GDB command is ‘info shared’. Example N.A.
304 Debugging with GDB The -file-symbol-file Command Synopsis -file-symbol-file file Read symbol table info from the specified file argument. When used without arguments, clears GDB’s symbol table info. No output is produced, except for a completion notification. GDB command The corresponding GDB command is ‘symbol-file’. Example (gdb) -file-symbol-file /kwikemart/marge/ezannoni/TRUNK/mbx/hello.mbx ^done (gdb) 21.
Chapter 21: The gdb/mi Interface GDB command The corresponding GDB command is ‘set’. Example (gdb) -gdb-set $foo=3 ^done (gdb) The -gdb-show command Synopsis -gdb-show Show the current value of a GDB variable. GDB command The corresponding GDB command is ‘show’. Example (gdb) -gdb-show annotate ^done,value="0" (gdb) The -gdb-version Command Synopsis -gdb-version Show version information for GDB. Used mostly in testing. GDB command The corresponding GDB command is ‘show version’.
306 Debugging with GDB ~GDB is free software, covered by the GNU General Public License, and ~you are welcome to change it and/or distribute copies of it under ~ certain conditions. ~Type "show copying" to see the conditions. ~There is absolutely no warranty for GDB. Type "show warranty" for ~ details. ~This GDB was configured as "--host=sparc-sun-solaris2.5.1 --target=ppc-eabi". ^done (gdb) 21.
Chapter 21: The gdb/mi Interface 307 Example For a stack with frame levels 0 through 11: (gdb) -stack-info-depth ^done,depth="12" (gdb) -stack-info-depth ^done,depth="4" (gdb) -stack-info-depth ^done,depth="12" (gdb) -stack-info-depth ^done,depth="11" (gdb) -stack-info-depth ^done,depth="12" (gdb) 4 12 11 13 The -stack-list-arguments Command Synopsis -stack-list-arguments show-values [ low-frame high-frame ] Display a list of the arguments for the frames between low-frame and high-frame (inclusive).
308 Debugging with GDB frame={level="2 ",addr="0x0001078c",func="callee2", file="../../../devo/gdb/testsuite/gdb.mi/basics.c",line="22"}, frame={level="3 ",addr="0x000107b4",func="callee1", file="../../../devo/gdb/testsuite/gdb.mi/basics.c",line="27"}, frame={level="4 ",addr="0x000107e0",func="main", file="../../../devo/gdb/testsuite/gdb.mi/basics.
Chapter 21: The gdb/mi Interface 309 ‘level ’ The frame number, 0 being the topmost frame, i.e. the innermost function. ‘addr ’ The $pc value for that frame. ‘func ’ Function name. ‘file ’ File name of the source file where the function lives. ‘line ’ Line number corresponding to the $pc. If invoked without arguments, this command prints a backtrace for the whole stack. If given two integer arguments, it shows the frames whose levels are between the two arguments (inclusive).
310 Debugging with GDB file="recursive2.c",line="14"}, frame={level="4 ",addr="0x000107a4",func="foo", file="recursive2.c",line="14"}, frame={level="5 ",addr="0x000107a4",func="foo", file="recursive2.c",line="14"}] (gdb) Show a single frame: (gdb) -stack-list-frames 3 3 ^done,stack= [frame={level="3 ",addr="0x000107a4",func="foo", file="recursive2.c",line="14"}] (gdb) The -stack-list-locals command Synopsis -stack-list-locals print-values Display the local variable names for the current frame.
Chapter 21: The gdb/mi Interface Example (gdb) -stack-select-frame 2 ^done (gdb) 21.10 gdb/mi Symbol query commands The -symbol-info-address Command Synopsis -symbol-info-address symbol Describe where symbol is stored. GDB command The corresponding GDB command is ‘info address’. Example N.A. The -symbol-info-file Command Synopsis -symbol-info-file Show the file for the symbol. GDB command There is no equivalent GDB command. gdbtk has ‘gdb_find_file’. Example N.A.
312 Debugging with GDB Synopsis -symbol-info-function Show which function the symbol lives in. GDB command ‘gdb_get_function’ in gdbtk. Example N.A. The -symbol-info-line command Synopsis -symbol-info-line Show the core addresses of the code for a source line. GDB command The corresponding GDB comamnd is ‘info line’. gdbtk has the ‘gdb_get_line’ and ‘gdb_get_file’ commands. Example N.A. The -symbol-info-symbol command Synopsis -symbol-info-symbol addr Describe what symbol is at location addr.
Chapter 21: The gdb/mi Interface The -symbol-list-functions command Synopsis -symbol-list-functions List the functions in the executable. GDB command ‘info functions’ in GDB, ‘gdb_listfunc’ and ‘gdb_search’ in gdbtk. Example N.A. The -symbol-list-types command Synopsis -symbol-list-types List all the type names. GDB command The corresponding commands are ‘info types’ in GDB, ‘gdb_search’ in gdbtk. Example N.A.
314 Debugging with GDB Example N.A. The -symbol-locate command Synopsis -symbol-locate GDB command ‘gdb_loc’ in gdbtk. Example N.A. The -symbol-type command Synopsis -symbol-type variable Show type of variable. GDB command The corresponding GDB command is ‘ptype’, gdbtk has ‘gdb_obj_variable’. Example N.A. 21.11 gdb/mi Target Manipulation Commands The -target-attach command Synopsis -target-attach pid | file Attach to a process pid or a file file outside of GDB.
Chapter 21: The gdb/mi Interface 315 GDB command The corresponding GDB command is ‘attach’. Example N.A. The -target-compare-sections command Synopsis -target-compare-sections [ section ] Compare data of section section on target to the exec file. Without the argument, all sections are compared. GDB command The GDB equivalent is ‘compare-sections’. Example N.A. The -target-detach command Synopsis -target-detach Disconnect from the remote target. There is no output.
316 Debugging with GDB Synopsis -target-download Loads the executable onto the remote target. It prints out an update message every half second, which includes the fields: ‘section’ The name of the section. ‘section-sent’ The size of what has been sent so far for that section. ‘section-size’ The size of the section. ‘total-sent’ The total size of what was sent so far (the current and the previous sections). ‘total-size’ The size of the overall executable to download.
Chapter 21: The gdb/mi Interface 317 total-sent="2560",total-size="9880"} +download,{section=".text",section-sent="3072",section-size="6668", total-sent="3072",total-size="9880"} +download,{section=".text",section-sent="3584",section-size="6668", total-sent="3584",total-size="9880"} +download,{section=".text",section-sent="4096",section-size="6668", total-sent="4096",total-size="9880"} +download,{section=".
318 Debugging with GDB Synopsis -target-list-available-targets List the possible targets to connect to. GDB command The corresponding GDB command is ‘help target’. Example N.A. The -target-list-current-targets command Synopsis -target-list-current-targets Describe the current target. GDB command The corresponding information is printed by ‘info file’ (among other things). Example N.A. The -target-list-parameters command Synopsis -target-list-parameters GDB command No equivalent. Example N.A.
Chapter 21: The gdb/mi Interface 319 The -target-select command Synopsis -target-select type parameters ... Connect GDB to the remote target. This command takes two args: ‘type ’ The type of target, for instance ‘async’, ‘remote’, etc. ‘parameters ’ Device names, host names and the like. See Section 13.2 [Commands for managing targets], page 109, for more details.
320 Debugging with GDB The -thread-list-all-threads Command Synopsis -thread-list-all-threads GDB command The equivalent GDB command is ‘info threads’. Example N.A. The -thread-list-ids command Synopsis -thread-list-ids Produces a list of the currently known GDB thread ids. At the end of the list it also prints the total number of such threads. GDB command Part of ‘info threads’ supplies the same information.
Chapter 21: The gdb/mi Interface 321 Synopsis -thread-select threadnum Make threadnum the current thread. It prints the number of the new current thread, and the topmost frame for that thread. GDB command The corresponding GDB command is ‘thread’. Example (gdb) -exec-next ^running (gdb) ~"0x7f7f0aec" *stopped,reason="end-stepping-range",thread-id="2",frame=addr="0x00002ca4",func ="printme",args=[name="ip"],file="multithread.
322 • • • • Debugging with GDB -gdb-show output-radix -stack-list-arguments -stack-list-locals -stack-select-frame Introduction to variable objects in gdb/mi The basic idea behind variable objects is the creation of a named object to represent a variable, an expression, a memory location or even a CPU register. For each object created, a set of operations is available for examining or changing its properties. Furthermore, complex data types, such as C structures, are represented in a tree format.
Chapter 21: The gdb/mi Interface 323 Synopsis -var-create {name | "-"} {frame-addr | "*"} expression This operation creates a variable object, which allows the monitoring of a variable, the result of an expression, a memory cell or a CPU register. The name parameter is the string by which the object can be referenced. It must be unique. If ‘-’ is specified, the varobj system will generate a string “varNNNNNN” automatically. It will be unique provided that one does not specify name on that format.
324 Debugging with GDB The -var-show-format command Synopsis -var-show-format name Returns the format used to display the value of the object name.
Chapter 21: The gdb/mi Interface 325 Synopsis -var-info-expression name Returns what is represented by the variable object name: lang=lang-spec,exp=expression where lang-spec is {"C" | "C++" | "Java"}. The -var-show-attributes command Synopsis -var-show-attributes name List attributes of the specified variable object name: status=attr [ ( ,attr )* ] where attr is { { editable | noneditable } | TBD }.
326 Debugging with GDB
Chapter 22: Reporting Bugs in GDB 327 22 Reporting Bugs in GDB Your bug reports play an essential role in making GDB reliable. Reporting a bug may help you by bringing a solution to your problem, or it may not. But in any case the principal function of a bug report is to help the entire community by making the next version of GDB work better. Bug reports are your contribution to the maintenance of GDB.
328 Debugging with GDB Sometimes people give a few sketchy facts and ask, “Does this ring a bell?” Those bug reports are useless, and we urge everyone to refuse to respond to them except to chide the sender to report bugs properly. To enable us to fix the bug, you should include all these things: • The version of GDB. GDB announces it if you start with no arguments; you can also print it at any time using show version.
Chapter 22: Reporting Bugs in GDB 329 • A patch for the bug. A patch for the bug does help us if it is a good one. But do not omit the necessary information, such as the test case, on the assumption that a patch is all we need. We might see problems with your patch and decide to fix the problem another way, or we might not understand it at all. Sometimes with a program as complicated as GDB it is very hard to construct an example that will make the program follow a certain path through the code.
330 Debugging with GDB
Appendix A: Installing GDB 331 Appendix A Installing GDB If you obtain GDB (WDB) as part of the HP ANSI C, HP ANSI C++ Developer’s Kit for HP-UX Release 11.x, or HP Fortran, you do not have to take any special action to build or install GDB. If you obtain GDB (WDB) from an HP web site, you may download either an swinstall package or a source tree, or both. Most customers will want to install the GDB binary that is part of the swinstall package.
332 Debugging with GDB gdb-gdb-199991101/glob source for the gnu filename pattern-matching subroutine gdb-gdb-199991101/mmalloc source for the gnu memory-mapped malloc package The simplest way to configure and build GDB is to run configure from the ‘gdb-version-number ’ source directory, which in this example is the ‘gdb-gdb-199991101’ directory. First switch to the ‘gdb-version-number ’ source directory if you are not already in it; then run configure.
Appendix A: Installing GDB 333 easy by allowing you to generate each configuration in a separate subdirectory, rather than in the source directory. If your make program handles the ‘VPATH’ feature (gnu make does), running make in each of these directories builds the gdb program specified there. To build gdb in a separate directory, run configure with the ‘--srcdir’ option to specify where to find the source. (You also need to specify a path to find configure itself from your working directory.
334 Debugging with GDB config.sub to map abbreviations to full names; you can read the script, if you wish, or you can use it to test your guesses on abbreviations—for example: % sh config.sub i386-linux i386-pc-linux-gnu % sh config.sub alpha-linux alpha-unknown-linux-gnu % sh config.sub hp9k700 hppa1.1-hp-hpux % sh config.sub sun4 sparc-sun-sunos4.1.1 % sh config.sub sun3 m68k-sun-sunos4.1.1 % sh config.sub i986v Invalid configuration ‘i986v’: machine ‘i986v’ not recognized config.
Appendix A: Installing GDB 335 --norecursion Configure only the directory level where configure is executed; do not propagate configuration to subdirectories. --target=target Configure GDB for cross-debugging programs running on the specified target. Without this option, GDB is configured to debug programs that run on the same machine (host) as GDB itself. There is no convenient way to generate a list of all available targets. host ... Configure GDB to run on the specified host.
336 Debugging with GDB
Index Index (Index is nonexistent) 337
338 Debugging with GDB The body of this manual is set in cmr10 at 10.95pt, with headings in cmb10 at 10.95pt and examples in cmtt10 at 10.95pt. cmti10 at 10.95pt, cmb10 at 10.95pt, and cmsl10 at 10.95pt are used for emphasis.