Debugging with GDB Manual The GNU Source-Level Debugger HP Part Number: 5992-4701 Published: February 2009 Edition: 19
© Copyright 2009 Hewlett-Packard Development Company, L.P. Confidential computer software. Valid license from HP required for possession, use or copying. Consistent with FAR 12.211 and 12.212, Commercial Computer Software, Computer Software Documentation, and Technical Data for Commercial Items are licensed to the U.S. Government under vendor's standard commercial license. The information contained herein is subject to change without notice.
Table of Contents Summary of GDB........................................................................................................................15 Free Software......................................................................................................................15 Contributors to GDB...........................................................................................................15 1 A Sample GDB Session.......................................................................
.9 Debugging programs with multiple threads................................................................46 4.10 Debugging programs with multiple processes...........................................................49 5 Stopping and Continuing..........................................................................................................51 5.1 Breakpoints....................................................................................................................51 5.1.
8.11 Printing Floating Point Values....................................................................................99 8.12 Floating point hardware..............................................................................................99 9 Using GDB with Different Languages........................................................................................101 9.1 Switching between source languages..........................................................................101 9.1.
13 Specifying a Debugging Target..............................................................................................133 13.1 Active targets.............................................................................................................133 13.2 Commands for managing targets..............................................................................133 13.3 Choosing target byte order........................................................................................
14.10.8 Scenarios in memory debugging.....................................................................174 14.10.8.1 Stop when freeing unallocated or deallocated blocks.............................174 14.10.8.2 Stop when freeing a block if bad writes occurred outside block boundary................................................................................................................174 14.10.8.3 Stop when a specified block address is allocated or deallocated............175 14.10.8.
14.15.2 Support for the info target Command.....................................................201 14.15.3 Support for the dumpcore command.............................................................202 14.15.3.1 Enhancements to the dumpcore command............................................202 14.15.4 Support for display of run time type information..........................................203 14.16 Printing the Execution Path Entries for the Current Frame or Thread...................203 14.16.
14.25.3 Support for _ _fpreg data type on IPF.........................................................222 14.25.4 Support for _Complex variables in HP C........................................................222 14.25.5 Support for debugging namespaces................................................................222 14.25.6 Command for evaluating the address of an expression..................................223 14.26 Viewing Wide Character Strings...........................................................
14.35.3.1 Printing of locals and globals in a stripped module...............................240 14.35.3.2 Backtrace on stripped frames..................................................................240 14.35.3.3 Command line calls to non-stripped library...........................................240 14.35.3.4 Setting breakpoints in unstripped shared library...................................240 14.36 Displaying the current block scope information.....................................................241 14.
16.2.10 Miscellaneous commands................................................................................265 16.3 XDB data formats and HP WDB equivalents............................................................266 16.4 XDB location syntax and HP WDB equivalents........................................................268 16.5 XDB special language operators and HP WDB equivalents.....................................268 16.6 XDB special variables and HP WDB equivalents...................................
20.7 Errors.........................................................................................................................302 20.8 Information on breakpoints.......................................................................................302 20.9 Invalidation notices...................................................................................................303 20.10 Running the program..............................................................................................303 20.
List of Tables 14-1 16-1 16-2 16-3 16-4 16-5 16-6 16-7 16-8 16-9 16-10 16-11 16-12 16-13 16-14 16-15 16-16 16-17 16-18 16-19 16-20 16-21 16-22 16-23 16-24 16-25 16-26 16-27 16-28 16-29 16-30 21-1 Memory Debugging Commands in Interactive and Batch Mode.............................177 Invocation commands...............................................................................................254 Window mode commands........................................................................................
List of Examples 14-1 14-2 14 Sample Output for the find command....................................................................198 Sample Commands to Print NaT Registers...............................................................
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.
Plea: Additions to this section are particularly welcome. If you or your friends (or enemies, to be evenhanded) have been unfairly omitted from this list, we would like to add your names! So that they may not regard their many labors as thankless, we particularly thank those who 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.
Brian Fox is the author of the readline libraries providing command-line editing and command history. Andrew Beers of SUNY Buffalo wrote the language-switching code, the Modula-2 support, and contributed the Languages chapter of this manual. Fred Fish wrote most of the support for Unix System Vr4. He also enhanced the command-completion support to cover C++ overloaded symbols. Hitachi America, Ltd. sponsored the support for H8/300, H8/500, and Super-H processors.
1 A Sample GDB Session This chapter describes the most common GDB commands with the help of an example.
$ (gdb) m4 HP gdb 3.0 for PA-RISC 1.1 or 2.0 (narrow), HP-UX 11.00. Copyright 1986 - 2001 Free Software Foundation, Inc. Hewlett-Packard Wildebeest 3.0 (based on GDB ) is covered by the GNU General Public License. Type "show copying" to see the conditions to change it and/or distribute copies. Type "show warranty" for warranty/support. GDB reads only enough symbol data to know where to find the rest when needed; as a result, the first prompt comes up very quickly. 1.
((gdb)) n 882 set_quotes((argc >= 2) ? TOKEN_DATA_TEXT(argv[1])\ : nil, 1.6 Stepping into a subroutine The set_quotes looks like a promising subroutine. We can go into it by using the command s (step) instead of next. step goes to the next line to be executed in any subroutine, so it steps into set_quotes. ((gdb)) s set_quotes (lq=0x34c78 "", rq=0x34c88 "") at input.c:530 530 if (lquote != def_lquote) 1.
((gdb)) p lquote $1 = 0x35d40 "" ((gdb)) p rquote $2 = 0x35d50 "" 1.9 Listing Source Code lquote and rquote are indeed the new left and right quotes. To look at some context, we can display ten lines of source surrounding the current line with the l (list) command.
((gdb)) c Continuing. define(baz,defn(foo)) baz 0000 Success! The new quotes now work just as well as the default ones. The problem seems to have been just the two typos defining the wrong lengths. We allow m4 to exit by giving it an EOF as input: C-d Program exited normally. The message `Program exited normally.' is from GDB; it indicates m4 has finished executing. We can end our GDB session with the GDB quit command. ((gdb)) quit 1.
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.
All options and command-line arguments you give are processed in sequential order. The order makes a difference when the `-x' option is used. 2.1.1 Choosing files When GDB starts, it reads any arguments other than options as specifying an executable file and core file (or process ID). This is the same as if the arguments were specified by the '-se' and '-c' options respectively.
-m, -mapped Warning: this option depends on operating system facilities that are not supported on all systems. If memory-mapped files are available on your system through the mmap system call, you can use this option to have GDB write the symbols from your program into a reusable file in the current directory. If the program you are debugging is called '/tmp/fred', the mapped symbol file is '/tmp/fred.syms'.
'-n'). Exit with nonzero status if an error occurs in executing the GDB commands in the command files. Batch mode may be useful for running GDB as a filter, for example to download and run a program on another computer; in order to make this more useful, the message Program exited normally. (which is ordinarily issued whenever a program running under GDB control terminates) is not issued when running in batch mode. 28 -nowindows, -nw “No windows”.
print routines so as to allow Epoch to display values of expressions in a separate window. -annotate level This option sets the annotation level inside GDB. Its effect is identical to using `set annotate level' (see “GDB Annotations” (page 297)). Annotation level controls how much information does GDB print together with its prompt, values of expressions, source lines, and other types of output.
'xdb_trans.html', which is usually installed in the directory /opt/langtools/wdb/doc on HP-UX systems. -interpreter interp Use the interpreter interp for interface with the controlling program or device. This option is meant to be set by programs which communicate with GDB using it as a back end. For example, '--interpreter=mi' causes GDB to use the gdbmi interface (see “The GDB/MI Interface” (page 307)). -write Open the executable and core files for both reading and writing.
type the interrupt character at any time because GDB does not allow it to take effect until a time when it is safe. You can use the detach command to release an attached process or device. 2.3 Shell commands If you need to execute occasional shell commands during your debugging session, there is no need to leave or suspend GDB; you can just use the shell command. shell command string Invoke a standard shell to execute command string.
3 GDB Commands You can abbreviate a GDB command to the first few letters of the command name, if that abbreviation is unambiguous; and you can repeat certain GDB commands by typing just RET ). You can also use the TAB key to get GDB to fill out the rest of a word in a command (or to show you the alternatives available, if there is more than one possibility). 3.1 Command syntax • • • • • • A GDB command is a single line of input. There is no limit on how long it can be.
GDB fills in the rest of the word 'breakpoints', since that is the only info subcommand beginning with 'bre': ((gdb)) info breakpoints You can either press RET at this point, to run the info breakpoints command, or backspace and enter something else, if 'breakpoints' does not look like the command you expected. (If you were sure you wanted info breakpoints in the first place, you might as well just type RET immediately after 'info bre', to exploit command abbreviations rather than command completion.
bubble(double,double) bubble(int,int) ((gdb)) b 'bubble( In some cases, GDB can tell that completing a name requires using quotes.
help class Using one of the general help classes as an argument, you can get a list of the individual commands in that class. For example, here is the help display for the class status: ((gdb)) help status Status inquiries. List of commands: info -- Generic command for showing things about the program being debugged show -- Generic command for showing things about the debugger Type "help" followed by command name for full documentation. Command name abbreviations are allowed if unambiguous.
listings under info and under show in the Index point to all the sub-commands. See ???. info This command (abbreviated i) is for describing the state of your program. For example, you can list the arguments given to your program with info args, list the registers currently in use with info registers, or list the breakpoints you have set with info breakpoints. You can get a complete list of the info sub-commands with help info.
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.
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 “Arguments To Your Program” (page 41). 40 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. See“Program Environment” (page 41). working directory.
program. See “Program Input and Output” (page 43). WARNING! You can redirect input and output, but you cannot use pipes to pass the output of the program you are debugging to another program; if you attempt this, GDB is likely to wind up debugging the wrong program. NOTE: • When you issue the run command, your program begins to execute immediately. See Chapter 5 (page 51), for discussion of how to arrange for your program to stop.
programs you run. When debugging, it can be useful to try running your program with a modified environment without having to start GDB over again. show envvar List all the environment variables used by GDB. show paths Display the list of search paths for executables (the PATH environment variable). show environment [varname] Print the value of environment variable varname to be given to your program when it starts.
You can use the string '$cwd' to refer to whatever is the current working directory at the time GDB searches the path. If you use '.' instead, it refers to the directory where you executed the path command. GDB replaces '.' in the directory argument (with the current path) before adding directory to the search path. 4.5 Working directory Each time you start your program with run, it inherits its working directory from the current working directory of GDB.
NOTE: • You can redirect your program input and output using shell redirection with the run command. For example, run > outfile starts your program, diverting its output to the file 'outfile'. • • An explicit redirection in run overrides the tty command's effect on the input/output device, but not its effect on the controlling terminal. When you use the tty command or redirect input in the run command, only the input for your program is affected. The input for GDB still comes from your terminal. 4.
NOTE: • To use attach, your program must be running in an environment which supports processes; for example, attach does not work for programs on bare-board targets that lack an operating system. • You must also have permission to send the process a signal. • When you use attach, the debugger finds the program running in the process first by looking in the current working directory, then (if the program is not found) by using the source file search path (see “Specifying source directories” (page 79)).
On some operating systems, a program cannot be executed outside GDB while you have breakpoints set on it inside GDB. You can use the kill command in this situation to permit running your program outside the debugger. The kill command is also useful if you wish to recompile and relink your program, since on many systems it is impossible to modify an executable file while it is running in a process.
thread identifier whose form varies depending on the particular system. For example, on LynxOS, you might see [New process 35 thread 27] when GDB notices a new thread. In contrast, on an SGI system, the systag is simply something like 'process 368', with no further qualifier. For debugging purposes, GDB associates its own thread number―always a single integer―with each thread in your program. info threads Display a summary of all threads currently in your program.
show threadverbose Display whether set threadverbose is on or off. Here are commands to get more information about threads: info threads Display a summary of all threads currently in your program. GDB displays for each thread (in this order): 1. the thread number assigned by GDB 2. the target system's thread identifier (systag) 3. the current stack frame summary for that thread 4. the priority of a thread An asterisk '*' to the left of the GDB thread number indicates the current thread.
threadno is the internal GDB thread number, as shown in the first field of the 'info threads' display. To apply a command to all threads, use thread apply all args. Whenever GDB stops your program, due to a breakpoint or a signal, it automatically selects the thread where that breakpoint or signal happened. GDB alerts you to the context switch with a message of the form '[Switching to systag]' to identify the thread.
set follow-fork-mode mode Set the debugger response to a program call of fork or vfork. A call to fork or vfork creates a new process. The mode can be: parent The original process is debugged after a fork. The child process runs unimpeded. This is the default. child show follow-fork-mode The new process is debugged after a fork. The parent process runs unimpeded. Display the current debugger response to a fork or vfork call.
5 Stopping and Continuing The principal purpose of a debugger is to let you stop your program before it terminates abnormally or runs into trouble, so that you can investigate and determine the reason. Inside GDB, your program can stop for several reasons, such as a signal, a breakpoint, or reaching a new line after a GDB command such as step. You can then examine and change variables, set new breakpoints or remove old ones, and then continue execution.
5.1.1 Setting breakpoints Breakpoints are set with the break command (abbreviated b). The debugger convenience variable '$bpnum' records the number of the breakpoint you have set most recently; see “Convenience variables” (page 96), for a discussion of what you can do with convenience variables. You have several ways to say where the breakpoint should go. 52 break function Set a breakpoint at entry to function function.
does not leave an active breakpoint. If you use break without an argument in the innermost frame, GDB stops the next time it reaches the current location; this may be useful inside loops. GDB normally ignores breakpoints when it resumes execution, until at least one instruction has been executed. If it did not do this, you would be unable to proceed past a breakpoint without first disabling the breakpoint. This rule applies whether or not the breakpoint already existed when your program stopped. break ...
are used. Delete or disable unused hardware breakpoints before setting new ones (see “Disabling breakpoints” (page 58)). See “Break conditions” (page 59). thbreak args Set a hardware-assisted breakpoint enabled only for one stop. args are the same as for the hbreak command and the breakpoint is set in the same way. However, like the tbreak command, the breakpoint is automatically deleted after the first time your program stops there.
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. If a breakpoint is conditional, info break shows the condition on the line following the affected breakpoint; breakpoint commands, if any, are listed after that.
GDB itself sometimes sets breakpoints in your program for special purposes, such as proper handling of longjmp (in C programs). These internal breakpoints are assigned negative numbers, starting with -1; 'info breakpoints' does not display them. You can see these breakpoints with the GDB maintenance command 'maint info breakpoints'. maint info breakpoints Using the same format as 'info breakpoints', display both the breakpoints you have set explicitly, and those GDB is using for internal purposes.
tcatch event vfork A call to vfork. This is currently only available for HP-UX. load, load libname The dynamic loading of any shared library, or the loading of the library libname. This is currently only available for HP-UX. unload, unload libname The unloading of any dynamically loaded shared library, or the unloading of the library libname. This is currently only available for HP-UX. Set a catchpoint that is enabled only for one stop.
5.1.3 Deleting breakpoints It is often necessary to eliminate a breakpoint, watchpoint, or catchpoint once it has done its job and you no longer want your program to stop there. This is called deleting the breakpoint. A breakpoint that has been deleted no longer exists; it is forgotten. With the clear command you can delete breakpoints according to where they are in your program.
• • Enabled once. The breakpoint stops your program, but then becomes disabled. Enabled for deletion. The breakpoint stops your program, but immediately after it does so it is deleted permanently. A breakpoint set with the tbreak command starts out in this state. You can use the following commands to enable or disable breakpoints, watchpoints, and catchpoints: disable [breakpoints] [range...] Disable the specified breakpoints―or all breakpoints, if none are listed.
say, to just set a watchpoint on a variable name, and specify a condition that tests whether the new value is an interesting one. Break conditions can have side effects, and may even call functions in your program. This can be useful, for example, to activate functions that log program progress, or to use your own print functions to format special data structures. The effects are completely predictable unless there is another enabled breakpoint at the same address.
instead of stopping, it just decrements the ignore count by one and continues. As a result, if the ignore count value is n, the breakpoint does not stop the next n times your program reaches it. ignore bnum count Set the ignore count of breakpoint number bnum to count. The next count times the breakpoint is reached, your program's execution does not stop; other than to decrement the ignore count, GDB takes no action. To make the breakpoint stop the next time it is reached, specify a count of zero.
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.
always '[0] cancel' and '[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.
When this message is printed, you need to disable or remove some of the hardware-assisted breakpoints and watchpoints, and then continue. 5.2 Continuing and stepping Continuing means resuming program execution until 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).
step Continue running your program until control reaches a different source line, then stop it and return control to GDB. This command is abbreviated s. WARNING! If you use the step command while control is within a function that was compiled without debugging information, execution proceeds until control reaches a function that does have debugging information. Likewise, it will not step into a function which is compiled without debugging information.
until, u Continue running until a source line past the current line, in the current stack frame, is reached. This command is used to avoid single stepping through a loop more than once. It is like the next command, except that when until encounters a jump, it automatically continues execution until the program counter is greater than the address of the jump. This means that when you reach the end of a loop after single stepping though it, until makes your program continue execution until it exits the loop.
stepi, stepi arg, Execute one machine instruction, then stop and return to the debugger. si It is often useful to do 'display/i $pc' when stepping by machine instructions. This makes GDB automatically display the next instruction to be executed, each time your program stops. See “Automatic display” (page 89). An argument is a repeat count, as in step. nexti, nexti arg, Execute one machine instruction, but if it is a function call, proceed until the function returns.
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.
pass GDB should allow your program to see this signal; your program can handle the signal, or else it may terminate if the signal is fatal and not handled. nopass GDB should not allow your program to see this signal. When a signal stops your program, the signal is not visible to the program until you continue. Your program sees the signal then, if pass is in effect for the signal in question at that time.
Whenever your program stops under GDB for any reason, all threads of execution stop, not just the current thread. This allows you to examine the overall state of the program, including switching between threads, without worrying that things may change underfoot. Conversely, whenever you restart the program, all threads start executing. This is true even when single-stepping with commands like step or next. In particular, GDB cannot single-step all threads in lockstep.
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. The stack frames are allocated in a region of memory called the call stack.
6.2 Stacks Without frames Some compilers provide a way to compile functions so that they operate without stack frames. (For example, the gcc option '-fomit-frame-pointer' generates functions without a frame.) This is occasionally done with heavily used library functions to save the frame setup time. GDB has limited facilities for dealing with these function invocations.
The names where and info stack (abbreviated info s) are additional aliases for backtrace. Each line in the backtrace shows the frame number and the function name. The program counter value is also shown―unless you use set print address off. The backtrace also shows the source file name and line number, as well as the arguments to the function. The program counter value is omitted if it is at the beginning of the code for that line number. Here is an example of a backtrace.
NOTE: • On the SPARC architecture, frame needs two addresses to select an arbitrary frame: a frame pointer and a stack pointer. • On the MIPS and Alpha architecture, it needs two addresses: a stack pointer and a program counter. • On the 29k architecture, it needs three addresses: a register stack pointer, a program counter, and a memory stack pointer. up n Move n frames up the stack.
info frame, info f This command prints a verbose description of the selected stack frame, including: • the address of the frame • the address of the next frame down (called by this frame) • the address of the next frame up (caller of this frame) • the language in which the source code corresponding to this frame is written • the address of the frame's arguments • the address of the frame's local variables • the program counter saved in it (the address of execution in the caller frame) • which registers wer
7 Examining Source Files GDB can print parts of the source code of your program, since the debugging information recorded in the program tells GDB what source files were used to build it. When your program stops, GDB spontaneously prints the line where it stopped. Likewise, when you select a stack frame (see “Selecting a frame” (page 73)), GDB prints the line where execution in that frame has stopped. You can print other portions of source files by explicit command.
The following arguments can be given to the list command: list linespec Print lines centered around the line specified by linespec. list first,last Print lines from first to last. Both arguments must be linespecs. list, last Print lines ending with last. list first, Print lines starting with first. list + Print lines just after the lines last printed. list - Print lines just before the lines last printed. list As described in the preceding table.
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. Even when they do, the directories can be moved between the compilation and your debugging session.
Print the source path and display the directories it contains. show directories If your source path is cluttered with directories that are no longer of interest, GDB can end up detecting the wrong version of the source. To correct this situation, follow these steps: 1. 2. Use directory with no arguments to reset the source path to empty. Use directory with suitable arguments to reinstall the directories you want in the source path. You can add all the directories in one command. 7.
The following example shows the disassembly of a range of addresses of HP PA-RISC 2.0 code: ((gdb)) disas 0x32c4 0x32e4 Dump of assembler code from 0x32c4 to 0x32e4: 0x32c4 : addil 0,dp 0x32c8 : ldw 0x22c(sr0,r1),r26 0x32cc : ldil 0x3000,r31 0x32d0 : ble 0x3f8(sr4,r31) 0x32d4 : ldo 0(r31),rp 0x32d8 : addil -0x800,dp 0x32dc : ldo 0x588(r1),r26 0x32e0 : ldil 0x3000,r31 End of assembler dump.
8 Examining Data The usual way to examine data in your program is with the print command (abbreviated p), or its synonym inspect. It evaluates and prints the value of an expression of the language your program is written in (see Chapter 9 (page 101)). The following forms of print command are supported: print expr, print /f expr expr is an expression (in the source language).
:: '::' allows you to specify a variable in terms of the file or function where it is defined. See “Program variables” (page 84). {type} addr Refers to an object of type type stored at address addr in memory. addr may be any expression whose value is an integer or pointer (but parentheses are required around binary operators, just as in a cast). This construct is allowed regardless of what kind of data is normally supposed to reside at addr. 8.
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.
p *array@len The left operand of '@' must reside in memory. Array values made with '@' in this way behave just like other arrays in terms of subscripting, and are coerced to pointers when used in expressions. Artificial arrays most often appear in expressions via the value history (see “Value history” (page 95)), after printing one out. Another way to create an artificial array is to use a cast. This re-interprets a value as if it were an array.
t a 2 Print as integer in binary. The letter 't' stands for “two”2. Print as an address, both absolute in hexadecimal and as an offset from the nearest 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.
w Words (four bytes). This is the initial default. 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.
available for use in expressions in the convenience variable $_. The contents of that address, as examined, are available in the convenience variable $__. If the x command has a repeat count, the address and contents saved are from the last memory unit printed; this is not the same as the last address printed if several units were printed on the last line of output. 8.
disable display dnums... Disable the display of item numbers dnums. A disabled display item is not printed automatically, but is not forgotten. It may be enabled again later. enable display dnums... Enable display of item numbers dnums. It becomes effective once again in auto display of its expression, until you specify otherwise. display Display the current values of the expressions on the list, just as is done when your program stops.
set print address off Do not print addresses when displaying their contents. For example, this is the same stack frame displayed with set print address off: ((gdb)) set print addr off ((gdb)) f #0 set_quotes (lq="<<", rq=">>") at input.c:530 530 if (lquote != def_lquote) You can use 'set print address off' to eliminate all machine dependent displays from the GDB interface.
If you have a pointer and you are not sure where it points, try 'set print symbol-filename on'. Then you can determine the name and source file location of the variable where it points, using 'p/a pointer'. This interprets the address in symbolic form. For example, here GDB shows that a variable ptt points at another variable t, defined in 'hi2.c': ((gdb)) set print symbol-filename on ((gdb)) p/a ptt $4 = 0xe008
}, meat = 0x54 "Pork" } set print pretty off Cause GDB to print structures in a compact format, like this: $1 = {next = 0x0, flags = {sweet = 1, sour = 1}, \ meat = 0x54 "Pork"} This is the default format. show print pretty Show which format GDB is using to print structures. set print sevenbit-strings on Print using only seven-bit characters; if this option is set, GDB displays any eight-bit characters (in strings or character values) using the notation \nnn.
} form; }; struct thing foo = {Tree, {Acorn}}; with set print union on in effect 'p foo' would print $1 = {it = Tree, form = {tree = Acorn, bug = Cocoon}} and with set print union off in effect it would print $1 = {it = Tree, form = {...}} These settings are of interest when debugging C++ programs: set print demangle, set print demangle on Print C++ names in their source form rather than in the encoded (“mangled”) form passed to the assembler and linker for type-safe linkage. The default is on.
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. show demangle-style Display the encoding style currently in use for decoding C++ symbols.
re-read or discarded (for example with the file or symbol-file commands). When the symbol table changes, the value history is discarded, since the values may contain pointers back to the types defined in the symbol table. The values printed are given history numbers by which you can refer to them. These are a range of integers starting with one. print shows you the history number assigned to a value by printing '$num = ' before the value; here num is the history number.
Convenience variables are prefixed with '$'. Any name preceded by '$' can be used for a convenience variable, unless it is one of the predefined machine-specific register names (see “Registers” (page 98)). (Value history references, in contrast, are numbers preceded by '$'. See “Value history” (page 95).) You can save a value in a convenience variable with an assignment expression, just as you would set a variable in your program.
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 ...
Some registers have distinct raw and virtual data formats. This means that the data format in which the register contents are saved by the operating system is not the same one that your program normally sees. For example, the registers of the 68881 floating point coprocessor are always saved in “extended” (raw) format, but all C programs expect to work with “double” (virtual) format.
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'.
'.cxx', '.c++' '.f', '.F', Fortran source file. GDB does not distinguish between Fortran 77 and Fortran 90 files. '.f90' '.s', '.S' 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 “Displaying the language” (page 103). 9.1.
9.2 Displaying the language The following commands help you find out which language is the working language, and also what language source files were written in. 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.
error 1 + 2.3 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.
For expressions you use in GDB commands, you can tell GDB to treat range errors in one of three ways: ignore them, always treat them as errors and abandon the expression, or issue warnings but evaluate the expression anyway. 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.
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.
==, != 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 “Expressions” (page 83)). +, - Addition and subtraction.
:: C++ scope resolution operator. Defined on struct, union, and class types. :: Double colons also represent the GDB scope operator (see “Expressions” (page 83)). Same precedence as ::, above. If an operator is redefined in the user code, GDB usually attempts to invoke the redefined version instead of using the original meaning. 9.4.1.2 C and C++ constants GDB allows you to express the constants of C and C++ in the following ways: • • • • • • • 108 Integer constants are a sequence of digits.
9.4.1.3 C++ expressions GDB expression handling can interpret most C++ expressions. WARNING! GDB can only debug C++ code if you use the proper compiler. Typically, C++ debugging depends on the use of additional debugging information in the symbol table, and thus requires special support. In particular, if your compiler generates a.out, MIPS ECOFF, RS/6000 XCOFF, or ELF with stabs extensions to the symbol table, these facilities are all available.
references are often used for large structures. The address of a reference variable is always shown, unless you have specified 'set print address off'. 5. GDB supports the C++ name resolution operator ::―your expressions can use it just as expressions in your program do. Since one scope may be defined in another, you can use :: repeatedly if necessary, for example in an expression like 'scope1::scope2::name'.
Range checking, if turned on, is done on mathematical operations. Array indices are not checked, since they are often used to index a pointer that is not itself an array. 9.4.1.6 GDB and C The set print union and show print union commands apply to the union type. When set to 'on', any union that is inside a struct or class is also printed. Otherwise, it appears as '{...}'. The @ operator aids in the debugging of dynamic arrays, formed with pointers and a memory allocation function.
searches for a function whose signature matches the argument types, using the standard C++ conversion rules (see “C++ expressions” (page 109), for details). If it cannot find a match, it emits a message. set overload-resolution off Disable overload resolution for C++ expression evaluation. For overloaded functions that are not class member functions, GDB chooses the first function of the specified name that it finds in the symbol table, whether or not its arguments are of the correct type.
integer*1, integer*2, integer*4, integer*8 logical*1, logical*2, logical*4, logical*8 byte, real*4, real*8, real*16 complex*8, complex*16 character*len, character*(*) [len is a user supplied length] arrays • allocatable • assumed-size • assumed-shape • adjustable • automatic • explicit-shape Array elements are displayed in column-major order. Use () for array member access (for example, arr(i) instead of arr[i]).
info common Lists values of variables in the named common block. Fortran entry points are supported. You can set a break point specifying an entry point name. 9.4.2.3 Fortran special issues Fortran allows main to be a non-main procedure; therefore, to set a breakpoint in the main program, use break _MAIN_ or break . Do not use break main unless it is the name of a non-main procedure.
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 “Choosing files” (page 26)), or by one of the file-management commands (see “Commands to specify files” (page 125)).
detailed description, instead of just the name of the type. For example, for this variable declaration: struct complex {double real; double imag;} v; the two commands give this output: ((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 functions regexp Print the names and data types of all defined functions whose names contain a match for regular expression regexp. Thus, 'info fun step' finds all functions whose names include step; 'info fun ^step' finds those whose names start with step. info variables Print the names and data types of all variables that are declared outside of functions (that is, excluding local variables).
show Show the current on or off symbol-reloading setting. set opaque-type-resolution on Tell GDB to resolve opaque types. An opaque type is a type declared as a pointer to a struct, class, or union―for example, struct MyType *―that is used in one source file although the full declaration of struct MyType is in another source file. The default is on. A change in the setting of this subcommand will not take effect until the next time symbols for a file are loaded.
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. For example, you can store new values into variables or memory locations, give your program a signal, restart it at a different address, or even return prematurely from a function. 11.
((gdb)) $1 = 1 ((gdb)) ((gdb)) $2 = 1 ((gdb)) p g set g=4 p g 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.
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. jump *address Resume execution at the instruction at address address. On many systems, you can get much the same effect as the jump command by storing a new value into the register $pc.
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. return, return expression 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.
show write Display whether executable files and core files are opened for writing as well as reading. 11.
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“Getting In and Out of GDB” (page 25)). Occasionally it is necessary to change to a different file during a GDB session.
filename means to discard information on the executable file. symbol-file [ filename ] Read symbol table information from file filename. PATH is searched when necessary. Use the file command to get both symbol table and program to run from the same file. symbol-file with no argument clears out GDB information on the symbol table of your program. The symbol-file command causes GDB to forget the contents of its convenience variables, the value history, and all breakpoints and auto-display expressions.
filename [ -readnow ] [ -mapped ] option with any of the commands that load symbol table information, if you want to be sure GDB has the entire symbol table available. If memory-mapped files are available on your system through the mmap system call, you can use another option, `-mapped', to cause GDB to write the symbols for your program into a reusable file.
To do this, use the kill command (see “Killing the child process” (page 45)). 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 -section address The add-symbol-file command reads additional symbol table information from the file filename. You would use this command when filename has been dynamically loaded (by some other means) into the program that is running.
info files, info target info files and info target are synonymous; both commands print the current target (see Chapter 13 (page 133)), including the names of the executable and core dump files currently in use by GDB, and the files from which symbols were loaded. Both the commands list all possible targets rather than the current targets. All file-specifying commands allow both absolute and relative file names as arguments.
show auto-solib-add Display the current autoloading size threshold, in megabytes. 12.2 Specifying shared library locations On HP-UX, when the shared libraries your program uses are in a different directory than the path specified in the source or object files, specify the correct files to use with one of two environment variables. `GDB_SHLIB_PATH' Set this variable to a colon-separated list of directory path names where the desired shared libraries reside.
For example, if you want to use /tmp/usr/lib/libsubs.sl and /tmp/usr/share/ lib/libsubs.sl, you can set GDB_SHLIB_ROOT' to /tmp. Now whenever GDB encounters a library with the name /usr/lib/libsubs.sl and /usr/share/lib/ libsubs.sl, GDB looks at /tmp/usr/lib/libsubs.sl and /tmp/usr/share/ lib/libsubs.sl respectively. 12.3 Errors reading symbol files While reading a symbol file, GDB occasionally encounters problems, such as symbol types it does not recognize, or known bugs in compiler output.
the preceding source line. This is known to occur in the SunOS 4.1.1 (and earlier) C compiler. GDB circumvents the problem by treating the symbol scope block as starting on the previous source line. bad string table offset in symbol n Symbol number n contains a pointer into the string table which is larger than the size of the string table. GDB circumvents the problem by considering the symbol to have the name foo, which may cause other problems if many symbols end up with this name.
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 undefined [HP-UX Targets], page undefined.
names or host names to connect with, process numbers, and baud rates. The target command does not repeat if you press RET again after executing the command. help target Displays the names of all targets available. To display targets currently selected, use either info target or info files (see “Commands to specify files” (page 125)). 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.
target sim Builtin CPU simulator. GDB includes simulators for most architectures. In general,the following commands work: target sim load run However, you cannot assume that a specific memory map, device drivers, or even basic I/O is available, although some simulators do provide these. Some configurations may include these targets as well: target nrom dev NetROM ROM emulator. This target only supports downloading.
set endian big Instruct GDB to assume the target is big-endian. set endian little Instruct GDB to assume the target is little-endian. set endian auto Instruct GDB to use the byte order associated with the executable. show endian Display GDB's current idea of the target byte order. Note that these commands merely adjust interpretation of symbolic data on the host, and that they have absolutely no effect on the target system.
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.
• • • • • • • • • • • • • • • • • • • • • • 138 Serial debugging of a parent and child process. Support for Parallel Processing limited to pthread parallelism, but not the compiler generated parallelism, for example, with directives. Implementation of ask mode for set follow-fork-mode. Support for setting breakpoints using shared library name. Support for core file commands packcore, unpackcore, getcore, dumpcore and info rtti address.
• • • • • • • • • • • • • • • • • • • • • • • • • Enhanced info symbol ADDRESS command. The info symbol ADDRESS command has been enhanced to search for a symbol at the given address. Previously, the info symbol command could be used only to search the global namespace. Enhanced Java debugging support. Support for debugging C++ programs running under Linux Runtime Environment. Support for stop in/at dbx commands. Support for GNU GDB logging commands.
• • • • • • • • • • Support for evaluating macros. Support for printing the execution path entries in the current frame, or thread.
the standard library routines under libc.so and libdld.so.
14.3 Supported Platforms and Modes • Supported Platforms HP WDB supports source-level debugging of programs written in HP C, HP aC++, and Fortran 90 on Integrity systems running on HP-UX 11i v2 or later and PARISC systems running HP-UX 11i v1 and later. • Support for assembly-level debugging HP WDB provides support for assembly-level debugging.
NOTE: HP WDB cannot be attached to a process that is traced by tools which use ttrace, such as Caliper, adb, and tusc. The debugger displays the following error message on attempting to attach to such a process: Attaching to process failed. Hint: Check if this process is already being traced by another gdb or other trace tools like caliper and tusc. Hint: Check whether program is on an NFS-mounted file-system.
librtc.sl location $WDB_ROOT/bin None $WDB_ROOT/bin /opt/langtools/ $WDB_ROOT/lib bin /opt/langtools/ n/a bin n/a GDB_SERVER n/a $LIBRTC_SERVER NOTE: If you define WDB_ROOT or GDB_ROOT but do not create the correct directory structure below it, the debugger may fail. 14.6 Specifying object file directories GDB enables automatic loading of debug information from object modules when an application is compiled with the +objdebug option.
however, may not find source files if the object files are not available. This minimizes or eliminates the need to specify multiple objectdir commands when object files are moved from the compilation directories or when compilation directories are mounted over NFS. 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, perform the following steps: 1. 2.
The advantages include: • • • • You do not have to recompile and relink the entire program. You do not have to reload the program into the debugger. You can resume execution of the program from the x location. You can speed up the development cycle. NOTE: 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.
• • • You cannot add an alloca() function to a frame that did not previously use alloca(). New structure fields can be added at the end of a structure object, not in the middle of a structure. New fields are only accessible by the modified files. Old structure fields remain intact; no swapping of them is permitted. If the redefined function is in the call stack but not on the top of the call stack, the modified code will not be executed when the execution resumes.
NOTE: You must rebuild the program after you use the fix command because the changes you make are temporarily patched into the executable image. The changes are lost if you load a different executable and are not re ected in the original executable when you exit the debugger. 14.7.4 Example Fix and Continue session This example shows how you can make and test changes to a function without leaving the debugger session.
The problem might be that there is no return for the num function. You can correct this without leaving the debugger. 4. Set a break point at main: (gdb) b main Breakpoint 1 at 0x23f8: file sum.c, line 11. 5. Run the program: (gdb) run Starting program: /tmp/hmc/mysum Breakpoint 1, main () at sum.c:11 11 int num = 10; 6. When the program stops at the break point, use the edit command to make changes to the source file.
10. When you finish with the debugging session, you can exit the debugger normally: (gdb) q The following modules in /dev/src/mysum have been fixed: /dev/src/sum.c Remember to remake the program. The debugger message lists the source files that you have changed during the debugging session. NOTE: You must rebuild the program after you use the fix command because the changes you make are temporarily patched into the executable image.
3. You can use the following commands for debugging inline functions in HP 9000 systems: step next list backtrace frame info locals info args The following commands are not available for debugging inline functions in HP 9000 systems: breakpoint info frame disassembly NOTE: Inline debugging commands are not available for inlined template functions and inlined functions which are defined after the call site. 14.8.
The set inline-debug off command disables the inline debugging feature. You can disable inline debugging by entering this command before attaching the debugger to the application. The set inline-debug inline_bp_all command enables you to set and modify break- points on all instances of a particular inline function. It also enables the inline debugging feature.
(gdb) set inline-debug inline_bp_all or $ gdb --inline = inline_bp_all • To set and modify individual breakpoints on specific instances of inline functions and enable inline debugging, enter either of the following commands be- fore debugging the application: (gdb) set inline-debug inline_bp_individual or $ gdb --inline = inline_bp_individual • To disable inline debugging, enter either of the following commands be- fore debugging the application: (gdb) set inline-debug off or $ gdb --inline= off 3.
- show macro [macro-name] or info macro [macro-name] Displays the macro definition, source file name, and the line number. For example: (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 ...
The macro debugging features are supported for +objdebug and +noobjdebug compiler options. 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
(gdb) b 13 Breakpoint 1 at 0x40007d0:0: file scope.c, (gdb) b 23 Breakpoint 2 at 0x40007d0:2: file scope.c, (gdb) b 30 Breakpoint 3 at 0x40007e0:0: file scope.c, (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.c:5 #define USED2 200 (gdb) c Continuing. Breakpoint 2, main () at scope.
Breakpoint 2 at 0x40007d0:2: file scope.c, line 23 from sc1. (gdb) b 30 Breakpoint 3 at 0x40007e0:0: file scope.c, line 30 from sc1. (gdb) r Starting program: sc1 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 The macro `USED2' has no definition in the current scope. (gdb) c Continuing. Breakpoint 2, main () at scope.
For more information on memory debugging with WDB, see the Debugging Dynamic Memory Usage Errors Using HP WDB whitepaper at the HP WDB Documentation webpage at: http://www.hp.com/go/wdb. 14.10.1 When to suspect a memory leak You should suspect a memory leak in the code when you notice that the system is running out of swap space or running slower, or both. Applications or non-kernel code (including daemons) that have memory leaks can eventually use up all swap space.
HP WDB offers the following memory-debugging capabilities: • • • • • • • • • • • • Reports memory leaks Reports heap allocation profile Stops program execution if bad writes occur with string operations such as strcpy and memcpy Stops program execution when freeing unallocated or de-allocated blocks Stops program execution when freeing a block if bad writes occur outside block boundary Stops program execution conditionally based on whether a specified block address is allocated or de-allocated Scrambles pr
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. set heap-check interval < nn > This command starts incremental heap growth profile. All allocations prior to the execution of this command are ignored from report.
info leaks filename Writes the complete leak report output to the specified file. 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.
and, bcopy. WDB 5.6 and later versions of the debugger also validates calls to strcat and strncat. NOTE: HP WDB 6.0 and later versions of the debugger improves performance of memory debugging when the string option is set for 32-bit applications on HP-UX 11i v2 and later on Itanium systems. However, the performance degrades for 64-bit applications on HP-UX 11i v2 and later on Itanium systems.
for the footer is 16 bytes if this option is not used. If the user specifies a value less than 16 for the number of bytes, the debugger ignores it and takes the default of 16 bytes. If the user specifies more than 16 bytes, then the debugger considers the largest and closest 16 byte integral from the user-specified value. Example: If the user specifies 60 bytes, the debugger takes it as 48 bytes. If the user specifies 65, the debugger considers 64 bytes.
The debugger assigns each leak a numeric identifier. 7. To display a stack trace for a specific leak, use the info leak command and specify the number from the list associated with a leak: (gdb) info leak 2 245 bytes leaked in 8 blocks (10.05% of all bytes leaked) These range in size from 26 to 36 bytes and are allocated in strdup () in link_the_list () at test.c:55 in main () at test.c:13 in _start () 14.10.
frame_count=no_frames (or) set heap-check frame-count Sets the number of frames to be printed for leak context. min_heap_size=block_size (or) set heap-check min-heap-size Sets the minimum block size to use for heap reporting. min_leak_size=block_size (or) set heap-check min-leak-size Sets the minimum block size to use for leak detection. output_dir=output_data_dir Specifies the name of the output data directory.
4. Complete one of the following steps to preload the librtc runtime library: • Set the target application to preload librtc by using the +rtc option for the chatr command. In addition to automatically loading the librtc library, the +rtc option for the chatr command also maps the shared libraries as private.
LD_PRELOAD=/opt/langtools/lib/librtc.sl – For 64-bit IPF applications, LD_PRELOAD=/opt/langtools/lib/pa20_64/librtc.sl If LD_PRELOAD and chatr +rtc are used to preload the librtc runtime library , the librtc runtime library is loaded from the path specified by LD_PRELOAD. NOTE: Batch Mode RTC displays one of the following errors and causes the program to temporarily hang if the version of WDB and librtc.
has the filename rtcconfig. If user prefers to set this option, it must include the filename. ◦ Incorrect usage: export GDBRTC_CONFIG=./ export GDBRTC_CONFIG=/tmp ◦ Correct usage: export GDBRTC_CONFIG=/tmp/yet_another_config export GDBRTC_CONFIG=/tmp/rtcconfig • • • BATCH_RTC enables or disables batch memory leak detection. GDB_SERVER is used to override the default path from where the gdb executable is used to provide the information on memory leak.
mem_logfile=stderr[+]filename heap_logfile=stderr[+]filename ◦ • Specify config_strings for +check=malloc on Itanium or WDB memory check batch mode on Integrity systems. RTC_PROCESS_GDBINIT is an optional environment variable used to enable processing of the .gdbinit file. You can use the .
4. Complete one of the following steps: – Map the shared libraries privately using chatr, as follows: chatr +dbg enable On HP-UX 11i v3 Integrity systems, WDB enables automatic debugging of shared libraries without them being mapped private while attaching to a running program. For enabling automatic debugging of shared libraries, you must install the kernel patches PHKL_38651 and PHKL_38778.
2. The rtcconfig file should contain entries such as the following: check_heap=on check_leaks=on check_free=on files=exec1:exec2:exec3 output_dir=/tmp/results 3. Set the following environment variables as follows: export BATCH_RTC=on 4.
1. Complete one of the following steps to preload the librtc runtime library: – Set the target application to preload librtc by using the +rtc option for the chatr command.In addition to automatically loading the librtc library, the +rtc option for the chatr command also maps the shared libraries as private.
2. 3. Run the program. Start a debugging session as follows: gdb -leaks 4. Use info heap and info leaks commands to obtain a memory analysis report of the application. NOTE: From HP WDB 5.7 onwards, the archive version of the run time check library, librtc.a, is not available. You must use the shared version of the library, librtc.[sl|so], instead. 14.10.
set heap-check min-leak-size num For example, if you use, set heap-check min-leak-size 100 WDB does not collect stack traces for allocations smaller than 100 bytes. HP WDB still reports leaks smaller than this size, but does not include a stack trace. 14.10.7.
Syntax: info corruption [] The run time memory checking must be enabled before using the info corruption command to detect memory corruption. The corruption information is written to a file specified in the .file name argument if provided. Otherwise, it is printed to the stdout. NOTE: Turning on bounds checking increases the program's memory requirements because the extra guard bytes must be allocated at the beginning and end of each block. 14.10.8.
NOTE: Software literature names this concept as premature free or Reading/writing freed memory using a pointer. WDB tracks the dangling pointers and dangling blocks using a modified version of Garbage collection. The enabler for doing this is by retaining all the freed blocks internally within RTC without actually freeing it as long as possible. It displays all the potential pointers to the freed dangling blocks, in the application data space.
Table 14-1 Memory Debugging Commands in Interactive and Batch Mode Command Description Interactive mode Batch mode Toggles heap profiling and detection set heap-check [on of leaks, bounds, and double free | off] check_heap= [on | off] (or) set heap-check [on | off] Toggle the leak detection capability set heap-check leaks [on |off] check_leaks =[on | off] (or) set heap-check leaks [on |off] Toggle validation of calls to strcpy, set heap-check strncpy, memcpy, memccpy, string [on | off] memset, memmov
Table 14-1 Memory Debugging Commands in Interactive and Batch Mode (continued) Command Description Specifies the random range to be used by random-range. Interactive mode set heap-check random-range Batch mode Not supported in batch mode Specifies the time interval to be used set heap-check for incremental memory profile. interval Not supported in batch mode Perform incremental profile for interval periods where each period duration is defined by set heap-check interval command.
show heap-check Displays all current settings for memory checking. 14.10.10.2 info heap arena The info heap arena command enables the user to view high level memory usage details of each arena. The info heap arena is not supported in batch mode. This command is available only for applications running on 11i v3 or later. 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.
4. When the program is stopped at a breakpoint, use the info heap command: (gdb) info heap Analyzing heap ...done Actual Heap Usage: Heap Start = 0x40408000 Heap End = 0x4041a900 Heap Size = 76288 bytes Outstanding Allocations: 41558 bytes allocated in 28 blocks No. Total bytes Blocks Address Function 0 34567 1 0x40411000 foo() 1 4096 1 0x7bd63000 bar() 2 1234 1 0x40419710 baz() 3 245 8 0x404108b0 boo() [...] The display shows the currently allocated heap blocks.
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.11 Thread Debugging Support HP WDB provides thread-debugging support for kernel, user, and MxN threads. You can exclusively disable or enable specific thread execution.
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. The bt command only provides the stack trace of the current thread under execution.
• • • 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.
features are available as options to the set thread-check command. The syntax for the set thread-check command is as follows: 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.
uses the same condition variable in multiple calls, by different threads to pthread_cond_wait() or pthread_cond_timedwait(), but specifies different mutexes. The debugger transfers the execution control to the user and prints a warning message when this condition is detected. All threads that concurrently wait on any single condition variable must specify the same associated mutex.
read-write locks that are associated with the thread. The debugger transfers the execution control to the user and prints a warning message when this condition is detected. This situation can result in deadlocks if other threads are waiting to acquire the locked mutexes or read-write locks.
num-waiters [num] The set thread-check num-waiters [num] command checks if the number of threads waiting on any pthread object exceeds the specified threshold number [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.
1. Set LD_LIBRARY_PATH to include the appropriate directory, by entering one of the following commands: • For 32 bit IPF applications, LD_LIBRARY_PATH=/opt/langtools/wdb/lib/hpux32 • For 64 bit IPF applications, LD_LIBRARY_PATH=/opt/langtools/wdb/lib/hpux64 • For 32 bit PA applications, LD_LIBRARY_PATH=/opt/langtools/wdb/lib • For 64-bit PA applications, LD_LIBRARY_PATH=/opt/langtools/wdb/lib/pa20_64 2.
$ chatr +dbg enable ./ (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.
NOTE: Use the set frame-count setting in the rtconfig file to control the depth of the stack trace file. This command controls the depth of the call stack collected. Larger values increase the run time. 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.
NOTE: The configuration file contains lines of the following form: set thread-check [on|off] | [option] [on|off] | [option] [num] And/Or set frame-count [num] And/Or files= For more information, see “Enabling and Disabling Advanced Thread Debugging Features” (page 183). 4. Set the environment variable BATCH_RTC to on as: Set BATCH_RTC=on 14.
5. Complete one of the following steps to preload the librtc runtime library: • Set the target application to preload librtc by using the +rtc option for the chatr command. In addition to automatically loading the librtc library, the +rtc option for the chatr command also maps the shared libraries as private.
If LD_PRELOAD and chatr +rtc are used to preload the librtc runtime library , the librtc runtime library is loaded from the path specified by LD_PRELOAD. 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.
Behavior of the +check=thread option can be changed by users by providing their own rtcconfig file. The user specified rtcconfig file can be in the current directory or in a directory specified by the GDBRTC_CONFIG environment variable. If any thread error condition is detected during the application run, the error log will be output to a file in the current working directory. The output file will have the following naming convention: ..threads, where is the process identifier.
14.13 Debugging multiple processes ( programs with fork and vfork calls) 14.13.1 Ask mode for set follow-fork-mode The ask command prompts the user to select between parent and child as the debugger response to a program call of fork/vfork. Based on the user selection, the parent or the child process is debugged. For example, (gdb) set follow-fork-mode ask (gdb) show follow-fork-mode The debugger response to a program call to fork or vfork is ask.
0x40172b27: 0x40172b29: 0x40172b2b: 0x40172b2c: 0x40172b2e: 0x40172b2f: (b2) (61) (81) (c0) (00) (00) P3lc_gr gr=40 R3body rlen=33 B1label_state label=1 B2epilogue t=44 R1prologue rlen=0 R1prologue rlen=0 14.13.4 Printing CFM and PFS registers On Integrity systems, HP WDB prints Current Frame Marker (CFM) and Previous Frame State (PFS) ar64 registers in two different formats: • • raw values special formats identifying the size of rotating registers, frame and locals.
+length Specifies the length of the memory address range. This parameter is mandatory when end-address is not specified. expr1, expr2, .... Specifies a variable or pattern to be searched. The pattern can be a variable, hexadecimal character, a character, or a string value. The character pattern must be enclosed within single quotes. The string pattern must be enclosed within double quotes. This parameter is mandatory.
Example 14-1 Sample Output for the find command $ cat example.c #include #include int main() { char *str; str = (char *) malloc (15); strcpy(str,"hihi-hikh"); return 0; } (gdb) find &str[0], &str[15], "hi" 0x400123e0 0x400123e2 0x400123e5 3 patterns found. (gdb) find/2 &str[0], &str[15], "hi" 0x400123e0 0x400123e2 2 patterns found. (gdb) find/2b &str[0], &str[15], 0x68 0x400123e0 0x400123e2 2 patterns found. (gdb) find/2b &str[0], +10, 0x68 0x400123e0 0x400123e2 2 patterns found.
where: • &a[0] Specifies the start address of the memory address range. &a[10] Specifies the end address of the memory address range. “el”, 'l' Specifies the pattern. Using the start address (start-address), length (+length) parameter, and a pattern (expr1) find &str[0], +11, "hihi" • &str[0] Specifies the starting address. +11 Specifies the length of the memory address range, starting from &str[0]. "hihi" Specifies the pattern (expr1).
NOTE: Following are different ways of representing the /size-char and /max-count parameters: /1b /b1 /b /1 /1 /b where: 1 Specifies that find must display 1 matching pattern. b Specifies that the size of the pattern is 8 bits. 14.15 Debugging Core Files 14.15.1 Generating core files with packcore /unpackcore/getcore The contents of a core file can be viewed only on a system which has all the shared libraries that were in use on the system on which the core file was generated.
the core file to be used if the packcore directory does not contain a core file. If used, this second argument causes a symbolic link to be created in the packcore directory in place of the missing core file. The getcore command can be used to examine a packcore directory which was previously created by unpackcore. It takes one optional argument, the name of the packcore directory, which defaults to packcore. 14.15.
NOTE: Limitations for the enhanced info target command on corefile are as follows: • The enhanced info target command is not supported when the expanded_node_host_names kernel parameter is set. It is supported only for the default utsname. • The heap segment listed in the memory segment does not contain mmapped memory for the given core file. 14.15.
To analyze this core file with HP WDB on HP-UX 11i version 2, you must do the following: • When starting from HP WDB command line: (gdb) core-file [core.pid | core-filename] • When starting from shell prompt: $ gdb -core a.out [core.pid | core-filename] 14.15.4 Support for display of run time type information HP WDB enables you to view the run time type information for C++ polymorphic object. info rtti address This command displays run time type information for C++ polymorphic object.
For example, (gdb) i ep 4 10 • info exec-path summary Prints the summary information about all the local execution path entries in the current frame. This command displays the total number of branches for the frame, the number of branches executed in this frame in the last iteration, and the last executed branch number. • info global-exec-path [start_index] [end_index](aliased to info gep) Lists all the global execution path entries for the current thread.
For more information on this feature, see the following example. 14.16.2 Example Illustrating Execution Path Recovery The following example illustrates the use of the execution path recovery feature in HP WDB: Sample Program: $cat execpath.c #include #include #include
(gdb) i ep Local execution path table for main(): 0 0x4000a80:2 (execpath.c:10) (gdb) i gep Global execution path table: G0 0x4000a80:2 main (execpath.c:10) (gdb) n 15 if (c) (gdb) i ep Local execution path table for main(): 0 0x4000a80:2 (execpath.c:10) (gdb) i gep Global execution path table: G0 0x4000a80:2 main (execpath.
14.18 Invoking GDB Before a Program Aborts This -crashdebug option enables GDB to monitor the execution of a process or a program. It invokes GDB when the program execution is about to abort. Once the debugger is invoked, you can debug the application using the normal debugger commands. This option enables you to debug a live process instead of getting a core dump if the program is about to abort.
Abort gdb command line call? (y or n) y #0 main () at ./address_error.c:41 41 fun (count, count*1.1); (gdb) bt #0 main () at ./address_error.c:41 (gdb) quit The program is running. Exit anyway? (y or n) y 14.20 Instruction Level Stepping During instruction level stepping with nexti and stepi, WDB prints the assembly instruction along with the next source line. (gdb) stepi 0x101530:0 st4 [r9]=r34 1337 args.
14.21.3.1 Setting breakpoints in unstripped shared library GDB will not be able to put breakpoints using symbolic names(of the symbols not in export list) or line numbers in the stripped modules. GDB will be able to place breakpoints using symbol names in the unstripped shared libraries loaded into the stripped executable. 14.21.4 Support for procedural breakpoints HP WDB enables you to set breakpoints at the beginning (first executable line) of every function that can be debugged.
Setting a breakpoint on a template method with multiple instantiations displays a menu showing all instantiations and the user can choose to set breakpoints on all or any one or none. For example, (gdb) file test Reading symbols from test...done. (gdb) b MyClass::MyMember [0] cancel [1] all [2] MyClass::MyMember(int, int) at test.C:14 [3] MyClass::MyMember(int, float) at test.C:14 [4] MyClass::MyMember(int, double) at test.C:14 14.
14.22.2 Setting Deferred Breakpoints in Shared Library On HP-UX, GDB automatically loads symbol definitions from shared libraries when you use the run command, or when you examine a core file. (Before you issue the run command, GDB does not understand references to a function in a shared library| unless you are debugging a core file.
To set the breakpoint you must kill the program and then rerun it so that the dynamic linker maps a copy of the shared library privately. There are two ways to run the program: • • Rerun the program under GDB to have the debugger cause dld to map all shared libraries as private, enabling breakpoint debugging.
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.22.6 Setting breakpoints in shared library Breakpoints can be set on functions in a shared library, by specifying the library name with the function name. (gdb) b libutil.
14.23.1.1 Printing Decimal floating point constant (gdb) print df, DF - _Decimal32 dd, DD - _Decimal64 dl, DL - _Decimal128 This prints the decimal floating point constant based on the data type. 14.23.1.2 Printing Decimal floating point variable (gdb) print/ = df, dd, dl - variable name This prints the decimal floating point variable. If you specify format then it prints the variable based on its data type. 14.23.
HP WDB supports: • • • • • Evaluation of expressions with decimal floating point constants and variables. Setting or assignment of decimal floating point constant or variable. Arithmetic operations such as addition, subtraction, multiplication, division, and negation with decimal floating point constants or variables. Comparison operations such as ==,!=, >, >=, <, <= with decimal floating point constants or variables.
Conversion of types: GDB handles conversion of data types during assignment, printing, and arithmetic and comparison operation. (gdb) p 1.2df +1.2dd This converts double data type (1.2) to _Decimal64 data type and performs addition operation with _Decimal64 data type (1.2dd) and prints value in _Decimal64 type. HP WDB handles exceptions such as overflow, infinity and division by zero for Decimal Floating Point data type. (gdb) print 1.
14.25 Language support 14.25.1 Enhanced Java Debugging Support HP WDB shows stack traces of mixed Java, C, and C++ programs. It supports unwinding across Java frames and provides an effective way to examine stack traces containing mixed language frames (Java and C/C++) of both live Java processes and core files. This has been implemented by adding subcommands for Java VM debugging to gdb. The stack trace functionality requires Java SDK version 1.3.1.02 or later versions, for HP-UX.
Additional stack unwind features are available starting with SDK 1.4.2. These features fall into three categories: Java stack unwind enhancements, Java heap support, and Java threads support. These additional features are available as part of the Java stack unwind enhancements: • • • • • View Java compiled frame inlined methods. View Java interpreted or compiled frame specific information. View Java interpreted or compiled frame arguments and local variables. Disassemble Java method bytecodes.
Java VM Debugging Commands The following commands have been added to enhance Java debugging support: brbacktrace Prints backtrace of mixed Java and native frames. Standard backtrace command of GDB has been enhanced to work with mixed Java and native stack frames. info frame Prints Java frame specific information for a Java frame. Standard frame command of GDB has been enhanced to interpret a Java stack frame. info threads Prints state information for Java threads.
14.25.1.3 Java corefile debugging support HP WDB shows stack traces of mixed Java, C, and C++ programs for java corefile. GDB_JAVA_UNWINDLIB environment variable must be set to the path name of the Java unwind library as explained above. Following are examples that illustrate the gdb command-line options for invoking gdb on a core file: 1. Invoke gdb on a core file generated when running a 32-bit Java application on an Integrity system with /opt/java1.4/bin/java: $ gdb /opt/java1.4/bin/IA64N/java core.
2. Attach gdb to the running process: $ gdb -p 23989 HP gdb 5.0 for HP Itanium (32 or 64 bit) and target HP-UX 11.2x. Copyright 1986 - 2001 Free Software Foundation, Inc. Hewlett-Packard Wildebeest 5.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. Reading symbols from /opt/java1.4/bin/IA64N/java... (no debugging symbols found)...done. Attaching to program: /opt/java1.
/* off 453 bits, len 27 bits */ float f; /* off 480 bits, len 32 bits */ 14.25.3 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 t in 15 bits. 14.25.
You do not need to use fully qualified names to access symbols within a namespace. The debugger can compile a list of namespaces active in the scope that you are in and, when possible, choose an appropriate symbol. 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.
14.27 Support for output logging The Visual Interface for HP WDB terminal user interface (TUI) mode supports the command, log logfile_name, that saves the content of a session to the specified log file. 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.
where, ARRAY is the name of the array, and its size is 5x5. The first two lines are comments about this file and the array. The third line denotes the array coordinates. From the fourth line, the elements of the array are listed. Note: This feature is not supported for the Fortran array slices. 14.27.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.
"Steplast is not meaningful for the current line." For example, (gdb) 4 int k = 10; (gdb) sl ---> alias to "steplast" command error: Steplast is not meaningful for the current line 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.
14.29 Debugging optimized code HP WDB supports debugging of optimized code (compiled with both -g and -O) for HP aC++, HP ANSI C and HP WDB for HP Itanium.
The following commands are not affected by the optimization level of the program being debugged: • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • • 228 attach catch commands continue core delete define detach disable enable * 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 HP-UX Configuration-Specific Information
14.29.1 Debugging Optimized Code at Various Optimization Levels The following sections describe debugging optimized code support at each optimization level. 14.29.1.1 +O0 and +O1 At +O1 level, optimizations that affect the user visible state of a program are avoided. Line numbers are accurately associated with each machine instruction. Global or local variables may be examined, except for unused variables (which may be eliminated).
and later versions provide support to prevent the debugged program from stopping at instructions that are predicated false. The program execution can be stopped by a software breakpoint, a hardware breakpoint, or an asynchronous signal. In the case of optimizations such as if-conversion, the predicated false instructions indicate that an alternate source path is executed.
execution pattern and translates only the frequently executed code into native Itanium (R)code at runtime. 14.30.1 Debugging the application using GDB under ARIES ARIES supports debugging of HP 9000 HP-UX applications on HP-UX 11i Integrity servers using the HP 9000 HP-UX GDB. • • • • • Both the GDB and the application run under ARIES. No change in GDB user interface (including WDB GUI). Negligible loss of performance in interactive mode.
• • identically. The exact behavior shown by HP 9000 GDB under ARIES may differ from that on a HP 9000 HP-UX server. If the debugged process is blocking in a system call, any attempt to get to the GDB command prompt by pressing ctrl-C does not work. The process needs to be killed from a different shell. ARIES does not provide true emulation of MxN threads, and thus does not support debugging of HP 9000 applications that are linked with pthreads library and create threads in MxN model.
14.31 Visual Interface for WDB WDB includes an HP-supported Visual Interface for WDB with both graphical and terminal modes. The interface is based on Vim 5.7 and WDB. This interface replaces the -tui mode on Itanium-based systems. When you use the interface you are actually using vim, which is a vi-compatible editor. With the interface you can use vi commands to browse in the WDB display. Most of Visual Interface for WDB functionality is also available for emacs users.
(wdb) quit 14.31.2 Navigating the Visual Interface for WDB display The Visual Interface for WDB window consists of two areas: • • Source pane at the top Debugger pane at the bottom You can use the arrow and pagination keys on the keyboard to move the cursor: • • • • • • Pagination keys move the cursor in the source window, at the top, above the status line. Holding the shift key down while using the pagination keys moves the cursor in the debugger window.
Run Resume Stop Up Faq Stop Next Down Visual Finish Interface for WDB Prompt Print Type List Print* Edit Credits You can click the softkey or press a function key on the keyboard to invoke the command. The function keys F1 through F8 correspond to the bottom row of softkeys. The function keys F9 and up correspond to the top row. 14.31.3 Specifying foreground and background colors To change the foreground and background colors, update the `.Xdefaults' file in the home directory.
14.31.5 Using the TUI mode To start Visual Interface for WDB in terminal user interface (TUI) mode, run Visual Interface for WDB with the command: /opt/langtools/bin/vdb -tui This mode works well with hpterm and xterm and fairly well with dtterm and VT100 (telnet) terminals. NOTE: A defect in dtterm may truncate the display of lines that do not t within the window. To work around this defect, refresh the display with CTRL-L or widen the terminal window so source lines do not wrap.
14.31.7 Using commands to browse through source files browse. For example, CTRL-B, CTRL-F, CTRL-D, CTRL-U are useful for browsing the debugger window. These commands work whether or not you escape to `vi' mode. These `vim' commands require you to escape to `vi' mode.
To save a session to a file: 1. 2. Right-click an empty region of the source or debugger pane. 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.32 Support for ddd GDB works with ddd, the free GDB GUI shell available at http://mumm.ibr.cs.tu-bs.de/.
14.35.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.
14.35.2.2 For 64-bit applications To perform command line calls in a stripped executable, linked with end.o, you need to do the following: • • 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.35.3 Support for debugging stripped binaries HP WDB provides limited support for debugging stripped binaries. 14.35.3.
14.36 Displaying the current block scope information The which command takes a symbol as an argument and prints the information on a given symbol. It prints the following information: • • • current block scope addresses line information of the definition of the symbol filename in which the definition of the symbol occurs 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.
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 “XDB to WDB Transition Guide” (page 253). 15.1 Starting the TUI Invoke the debugger using a command like the following: gdb -xdb -tui a.
When you execute the program up to the first breakpoint by issuing the command run a right angle bracket (>) points to the current location. So after you issue those commands, the window looks something like this: |----------------------------------------------------------------------| |27 } | |28 | |29 int main(void) | |30 { | |31 /* Try two test cases.
The Command pane is always present. The possible configurations of the other panes are: • • • • • Source Disassembly Source/Disassembly Disassembly/Register Source/Register The layout command (abbreviated la) enables you to change from one window configuration to another. NOTE: You can abbreviate any command to its shortest unambiguous form. 15.3.1 Source pane The Source pane, Figure 1, appears by default when you invoke the debugger. You can also make it appear by issuing the command la src 15.3.
15.3.3 Source/Disassembly pane The Source/Disassembly pane appears when you issue the command: la split You can also reach this pane from the Source pane with the XDB command: td The window looks like this: :......................................................................: *>:32 print_average (my_list, first, last); : :33 print_average (my_list, first, last - 3); : :34 } : :35 : :36 : :37 : :......................................................................
|;;; 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 | |----------------------------------------------------------------------| File: average.c Procedure: main Line: 32 pc: 0x3524 (gdb) r Starting program: /home/work/wdb/a.out Breakpoint 1, main () at average.c:32 (gdb) la asm (gdb) la split (gdb) la regs (gdb) 15.3.
15.4 Cycling through the panes Use the commands la next and la prev to move from one pane to another without specifying a window name. If you specify la next repeatedly, the order the debugger uses is: • • • • • Source (src) Disassembly (asm) Source/Disassembly (split) Source/Register Disassembly/Register If you invoked the gdb command with the -xdb option as well as the -tui option, you can also use the following commands: td Toggle between Source and Disassembly/Register panes.
:.........................................................................: :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 : :.........................................................................
(gdb) (gdb) (gdb) (gdb) (gdb) Focus (gdb) la split la regs la src la regs foc next set to REGS window. 15.6 Scrolling panes To scroll within a pane, you can use the arrow keys or the Page Up and Page Down keys (on some keyboards these are Prev and Next). You can also use the following commands: {+ | -} [num_lines] [win_name] Vertically scroll the pane forward (+) or backward (-). + or - with no arguments scrolls the pane forward or backward one page.
*>:32 print_average (my_list, first, last); : :33 print_average (my_list, first, last - 3); : :34 } : :35 : :......................................................................: File: average.c Procedure: main Line: 32 pc: 0x3524 (gdb) la regs (gdb) la src (gdb) la regs (gdb) foc next Focus set to REGS window. (gdb) fr #0 main () at average.c:32 (gdb) The default floating-point register display is single-precision.
winheight [win_name] [+ | -] num_lines If you omit win_name, the pane with logical focus is resized. When you increase the height of a pane, the height of the Command pane is decreased by the same amount, and vice versa. The height of any other panes remains unchanged. For example, the command wh src +3 increases the size of the source pane, and decreases the size of the command pane, by 3 lines. To nd out the current sizes of all panes, use the info win command.
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.
• • • • • “Assertion control commands” “Record and playback commands” “Macro facility commands” “Signal control commands” “Miscellaneous commands” 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.
Table 16-2 Window mode commands (continued) XDB Command WDB Equivalent Meaning gr Display general registers gr (with -xdb -tui), display $regs (with -tui) sr sr (with -xdb -tui), display $sregs (with -tui) Display special registers td td (with -xdb -tui) Toggle disassembly mode tf Toggle float register display tf (with -xdb -tui), toggle $fregs (with -tui) precision ts ts (with -xdb -tui) Toggle split-screen mode u u (with -xdb -tui), update (with -tui) Update screen to current execution p
Table 16-3 File viewing commands (continued) XDB Command WDB Equivalent Meaning ld ld (with -xdb), show directories List source directory search path (list all directories) lf lf (with -xdb), info sources List all source files lf [string] No equivalent List matching files n fo or rev Repeat previous search N fo or rev Repeat previous search in opposite direction v v (with -xdb), list Show one source window forward from current v location v location (with -xdb), list location View sour
Table 16-4 Data viewing and modification commands XDB Command WDB Equivalent Meaning l l (with -xdb), info args followed by info locals Move view location forward or backward in source file number lines lc [string] lc [string] (with -xdb), info common string Search source forward for [last] string lg [string] lg [string] (with -xdb), info variables [string] Search source backward for [last] string ll [string] info functions [string], Add a directory search path for info variables [string], sour
Table 16-4 Data viewing and modification commands (continued) XDB Command WDB Equivalent Meaning p expr?format p/format &expr Print address using specified format p class:: No equivalent Print static members of class p $lang show language Inquire what language is used p {+ | -}[\format Print value of next/previous Use x/format command to memory location using format obtain initial value, then use x with no argument to obtain value of next memory location.
Table 16-5 Stack viewing commands (continued) XDB Command WDB Equivalent Meaning up down View procedure one level nearer innermost frame of stack (lower number) up number down number View procedure number levels nearer innermost frame of stack V [depth] V [depth] (with -xdb), frame [depth] Display text for current active procedure or at specified depth on stack 16.1.7 Status-viewing command Type the show command with no arguments to get a list of current debugger settings.
Table 16-7 Job control commands (continued) XDB Command WDB Equivalent Meaning g {+ | -}lines g {+ | -}lines (with Go forward or back given # lines -xdb), go {+ | -}lines, tb {+ | -}lines followed by jump {+ | -}lines g {+ | -} g {+ | -} (with -xdb), go Go forward or back 1 line {+ | -}1, tb {+ | -}1 followed by jump {+ | -}1 k k Detach and terminate target 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
Table 16-9 Auxillary breakpoint commands XDB Command WDB Equivalent Meaning Print any string any_string p "any string" if expr {cmds} [{cmds}] if expr cmds [else cmds] Conditionally execute cmds end Q Q (with -xdb), silent (must Quiet breakpoints be 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.
Table 16-10 Breakpoint creation commands (continued) XDB Command WDB Equivalent Meaning 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 executableUse rb ^class::* for base classes also line of all member functions of the class (base classes included).
Table 16-11 Overall breakpoint commands (continued) XDB Command WDB Equivalent Meaning bc number expr bc number expr (with -xdb), Set a breakpoint count ignorenumber expr (within a commands list) db clear Delete breakpoint at current line db number delete number Delete breakpoint of the given number db * delete Delete all breakpoints sb number disable number Suspend breakpoint of the given number sb * disable Suspend all breakpoints sb @shared- library No equivalent Suspend breakpoints
16.2.6 Assertion control commands GDB does not provide the ability to trace by instruction. Watchpoints, however, provide similar functionality to xdb assertions. For example, watchpoints can be: • • • • Enabled (corresponds to aa) Disabled (corresponds to da) Listed (corresponds to info watch) Added (corresponds to x) WDB does not have explicit equivalents for the following commands: a aa da la sa ta x 16.2.7 Record and playback commands Use the source command to read commands from a file.
Table 16-13 Macro facility commands XDB Command WDB Equivalent Meaning def name replacement-text def name [GDB prompts for commands] Define a user-defined command tm No equivalent Toggle the macro substitution mechanism undef name def name [follow with empty command list] Remove the macro definition for name undef * No equivalent Remove all macro definitions 16.2.
Table 16-15 Miscellaneous commands (continued) XDB Command WDB Equivalent Meaning ! cmd line ! cmd line (with -xdb), she cmd line Invoke a shell {cmd list} commands [number] ... end Execute command list (group commands) Control-C Control-C Interrupt the program # [text] # [text] A comment am am (with -xdb), set height num Activate more (turn on pagination) f ["printf-style- fmt"] No equivalent Set address printing format h h Help M[{t | c} [expr[; expr...
Table 16-16 Data format commands (continued) XDB Command WDB Equivalent Meaning d d Decimal integer D (1) d Long decimal integer e No equivalent e Floating-point notation as float E (1) No equivalent e Foating-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
Table 16-16 Data format commands (continued) XDB Command WDB Equivalent Meaning z t Print in binary Z (1) t Print in long binary (1) HP WDB will display data in the size appropriate for the data. It will not extend the length displayed in response to one of the uppercase formchars (for example, O, D, F). 16.
Table 16-18 Special language operators XDB Language Operator WDB Equivalent Meaning $addr Depends on language Unary operator, address of object $in No equivalent Unary Boolean operator, execution in procedure $sizeof sizeof Unary operator, size of object 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.
16.7 XDB variable identifiers and HP WDB equivalents Table 16-20 Variable Identifiers XDB Variable Identifier WDB Equivalent Meaning var var Search for var class:: class:: Search class for var (bug: not yet) [[class]::]proc:[class::]var proc::var Search proc for var (static variables only) [[class]::]proc:depth:[class::] No equivalent Search proc for depth on stack . (dot) Empty string; for example, p is the equivalent of p .
Table 16-21 A (continued) XDB Command Equivalent WDB Command 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.
Table 16-22 B (continued) XDB Command Equivalent WDB Command 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.
16.8.
Table 16-25 L (continued) XDB Command Equivalent WDB Command 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 string lr string (with -xdb), info reg string ls [string] No equivalent lz lz (with -xdb), info signals 16.8.
Table 16-26 M through P (continued) XDB Command Equivalent WDB Command pq class:: No equivalent pq [+ | -][\format No equivalent 16.8.
Table 16-28 T (continued) XDB Command Equivalent WDB Command 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.
Table 16-29 U through Z (continued) XDB Command Equivalent WDB Command xdb program corefile gdb -xdb program -c corefile 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 numb
Table 16-30 Symbols (continued) XDB Command 278 Equivalent WDB Command Return Return "any string" p "any string" . (dot) Empty string; for example, p is the equivalent of p .
Table 16-30 Symbols (continued) XDB Command Equivalent WDB Command Control-C Control-C # [text] # [text] #label No equivalent 16.
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 “Print settings” (page 90). 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.
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. This file defaults to the value of the environment variable GDBHISTFILE, or to ./.
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.
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. show output-radix Display the current default base for numeric display. 17.
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. The default is off show debug arch Displays the current state of displaying gdbarch debugging information. set debug event Turns on or o display of GDB event debugging information. The default is o.
show debug varobj 286 Controlling GDB Displays the current state of displaying GDB variable object debugging info.
18 Canned Sequences of Commands In addition to breakpoint commands (see “Breakpoint command lists” (page 61)), 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. User commands may accept up to 10 arguments separated by whitespace.
are executed repeatedly as long as the expression evaluates to true. document commandname Document the user-defined command commandname, so that it can be accessed by help. The command commandname must already be defined. This command reads lines of documentation just as define reads the lines of the command definition, ending with end. After the document command is finished, help on command commandname displays the documentation you have written.
end define hook-continue handle SIGLARM pass end You can define a hook for any single-word command in GDB, and not for command aliases; Also you should define a hook for the basic command name, for example, backtrace rather than bt. If an error occurs during the execution of your hook, execution of GDB commands stops and GDB issues a prompt (before the command that you actually typed had a chance to run).
• • • VxWorks (Wind River Systems real-time OS): .vxgdbinit OS68K (Enea Data Systems real-time OS): .os68gdbinit ES-1800 (Ericsson Telecom AB M68000 emulator): .esgdbinit You can also request the execution of a command file with the source command: source filename Execute the command file filename. The lines in a command file are executed sequentially. They are not printed as they are executed. An error in any command terminates execution of the command file.
not entered in the value history either. See “Expressions” (page 83). output/fmt expression Print the value of expression in format fmt. You can use the same formats as for print. See “Output formats” (page 86). printf string, expressions... Print the values of the expressions under the control of string. The expressions are separated by commas and may be either numbers or pointers.
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.
In the GDB I/O buffer, you can use these special Emacs commands in addition to the standard Shell mode commands: Describe the features of Emacs' GDB Mode. C-h m 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.
is formatted using the Emacs function format; otherwise the number is passed as an argument to the corresponding list element. In any source file, the Emacs command C-x SPC (gdb-break) tells GDB to set a break- point on the source line point is on.
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.
command history, nor will it affect GDB's notion of which command to repeat if RET is pressed on a line by itself. 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.
^Z^Zfield-value the-value ^Z^Zfield-end where field-name is the name of the field, separator-string is text which separates the name from the value for the user's benefit (such as `='), and value-flags and the-value have the same meanings as in a value-history-begin annotation.
• ^Z^Zfunction-call function-call-string where function-call-string is text designed to convey to the user that this frame is associated with a function call made by GDB to a function in the program being debugged.
where source-intro-string separates for the user's benefit the reference from the text which precedes it, filename is the name of the source file, and line-number is the line number within that file (the first line is line 1). If GDB prints some information about where the frame is from (which library, which load segment, etc.
^Z^Zpre-prompt ^Z^Zprompt ^Z^Zpost-prompt The input types are: prompt When GDB is prompting for a command (the main GDB prompt). commands When GDB prompts for a set of commands, like in the commands command. The annotations are repeated for each command which is input. overload-choice When GDB wants the user to select between various overloaded functions. query When GDB wants the user to confirm a potentially dangerous operation.
where header-entry has the same syntax as an entry (see below) but instead of containing data, it contains strings which are intended to convey the meaning of each field to the user. This is followed by any number of entries. If a field does not apply for this entry, it is omitted. Fields may contain trailing whitespace.
is output. Before the stopped annotation, a variety of annotations describe how the program stopped. ^Z^Zexited exit-status The program exited, and exit-status is the exit status (zero for successful exit, otherwise nonzero). ^Z^Zsignalled The program exited with a signal.
20.12 Annotations We Might Want in the Future • target-invalid the target might have changed (registers, heap contents, or execution status). For performance, we might eventually want to hit registers-invalid and all-registers-invalid with greater precision • • systematic annotation for set/show parameters (including invalidation notices). similarly, `info' returns a list of candidates for invalidation notices. 20.
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.
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. • Some MI commands accept optional arguments as part of the parameter list. Each option is identified by a leading `-' (dash) and may be followed by an optional argument parameter. Options occur first in the parameter list and can be delimited from normal parameters using `--' (this is useful when some parameters begin with a dash).
value const | tuple | list const c-string tuple → "{}" | "{" result ( "," result )* "}" list "[]" | "[" value ( "," value )* "]" | "[" result ( "," result )* "]" stream-record console-stream-output | target-stream-output | log-stream-output console-stream-output "~" c-string target-stream-output "@" c-string log-stream-output "&" c-string nl CR | CR-LF token any sequence of digits. Notes: • All output sequences end in a single line containing a period.
21.1.3 Simple examples of GDB/MI interaction This subsection presents several simple examples of interaction using the GDB/MI interface. In these examples, '->' means that the following line is passed to GDB/MI as input, while '<-' means the output received from GDB/MI. Evaluate expression Here is an example to evaluate an expression: -> <<<- -data-evaluate-expression 2+3 (gdb) ^done,value="5" (gdb) and later: <- *stop,reason="stop",address="0x123",source="a.
21.3 GDB/MI output records 21.3.1 GDB/MI result records In addition to a number of out-of-band notifications, the response to a GDB/MI command includes one of the following result indications: "^done" [ "," results ] The synchronous operation was successful, results are the return values. "^running" The asynchronous operation was successfully started. The target is running. "^error" "," c-string The operation failed. The c-string contains the corresponding error message. 21.3.
Note the line breaks shown in the examples are here only for readability. They do not appear in the real output. Also note that the commands with a non-available example (N.A.) are not yet implemented. Motivation The motivation for this collection of commands. Introduction A brief introduction to this collection of commands as a whole. Commands For each command in the block, the following is described: Synopsis -command args... GDB command The corresponding GDB CLI command.
Example (gdb) -break-insert main ^done,bkpt=number="1",type="breakpoint",disp="keep",enabled="y", addr="0x000100d0",func="main",file="hello.
addr="0x000100d0",func="main",file="hello.c",line="5",cond="1", times="0",ignore="3"}]} (gdb) The -break-delete command Synopsis -break-delete ( breakpoint )+ Delete the breakpoint(s) whose number(s) are specified in the argument list. This is obviously reflected in the breakpoint list. GDB command The corresponding GDB command is 'delete'.
-break-list ^done,BreakpointTable={nr_rows="1",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="2",type="breakpoint",disp="keep",enabled="n", addr="0x000100d0",func="
Example N.A. The -break-insert command 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.
^done,bkpt=number="1",type="breakpoint",disp="keep",enabled="y",addr="0x0001072c", file="recursive2.c",line="4",times="0" (gdb) -break-insert -t foo ^done,bkpt=number="2",type="breakpoint",disp="keep",enabled="y",addr="0x00010774", file="recursive2.
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", addr="0x000100d0",func="main",file="hello.
(gdb) -exec-continue ^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.
^done,BreakpointTable=nr_rows="1",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",addr="0x000029b4", func="call",file="hello.
GDB command There is no direct mapping from this command to the CLI.
^done,asm_insns=[ src_and_asm_line={line="31", file="/kwikemart/marge/ezannoni/flathead-dev/devo/gdb/ \ testsuite/gdb.mi/basics.c",line_asm_insn=[ {address="0x000107bc",func-name="main",offset="0", inst="save %sp, -112, %sp"}]}, src_and_asm_line={line="32", file="/kwikemart/marge/ezannoni/flathead-dev/devo/gdb/ \ testsuite/gdb.mi/basics.
The -data-list-changed-registers Command Synopsis -data-list-changed-registers Display a list of the registers that have changed. GDB command GDB does not have a direct analog for this command; gdbtk has the corresponding command 'gdb_changed_register_list'. Example On a PPC MBX board: (gdb) -exec-continue ^running (gdb) *stopped,reason="breakpoint-hit",bkptno="1",frame={func="main", args=[],file="try.
(gdb) -data-list-register-names ^done,register-names=["r0","r1","r2","r3","r4","r5","r6","r7", "r8","r9","r10","r11","r12","r13","r14","r15","r16","r17","r18", "r19","r20","r21","r22","r23","r24","r25","r26","r27","r28","r29", "r30","r31","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9", "f10","f11","f12","f13","f14","f15","f16","f17","f18","f19","f20", "f21","f22","f23","f24","f25","f26","f27","f28","f29","f30","f31", "", "pc","ps","cr","lr","ctr","xer"] (gdb) -data-list-register-names 1 2 3 ^done,registe
^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"},{number="6",value="0x3fff58"}, {number="7",value="0xfe011e98"},{number="8",value="0x2"}, {number="9",value="0xfa202820"},{number="10",value="0xfa202808"}, {number="11",value="0x1"},{number="12",value="0x0"}, {number="13",value="0x4544"},{number="14",value="0xffdfffff"}, {number="15",value="0xffffffff"},{number=
'word-format' The format to be used to print the memory words. The notation is the same as for GDB print command (see“Output formats” (page 86)). 'word-size' The size of each memory word in bytes. 'nr-rows' The number of rows in the output table. 'nr-cols' The number of columns in the output table. 'aschar' If present, indicates that each row should include an ASCII dump.
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. Include a string encoding with 'x' used as the non-printable character.
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. The -display-list command Synopsis -display-list List the displays. Do not show the current values. GDB command The corresponding GDB command is 'info display'.
Set the GDB working directory. GDB command The corresponding GDB command is 'cd'. Example (gdb) -environment-cd /kwikemart/marge/ezannoni/flathead-dev/devo/gdb ^done (gdb) The -environment-directory command Synopsis -environment-directory pathdir Add directory pathdir to the beginning of search path for source files. GDB command The corresponding GDB command is 'dir'.
The -environment-pwd command Synopsis -environment-pwd Show the current working directory. GDB command The corresponding GDB command is 'pwd'. Example (gdb) -environment-pwd ~Working directory /kwikemart/marge/ezannoni/flathead-dev/devo/gdb. ^done (gdb) 21.7 GDB/MI program control Program termination As a result of execution, the inferior program can run to completion, if it does not encounter any breakpoints. In this case the output will include an exit code, if the program has exited exceptionally.
The -exec-abort command Synopsis -exec-abort Kill the inferior running program. GDB command The corresponding GDB command is 'kill'. Example N.A. 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 Do not have one around. The -exec-continue command Synopsis -exec-continue Asynchronous command.
The -exec-finish command Synopsis -exec-finish Asynchronous command. Resumes the execution of the inferior program until the current function is exited. Displays the results returned by the function. 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.
Example (gdb) 111-exec-continue 111^running (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.
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. Does not execute the inferior. Displays the new current frame. GDB command The corresponding GDB command is return'.
Example (gdb) -break-insert main ^done,bkpt=number="1",type="breakpoint",disp="keep",enabled="y",addr="0x00002a08", func="main",file="hello.c",line="23",times="0" (gdb) -exec-run ^running (gdb) *stopped,reason="breakpoint-hit",bkptno="1",thread-id="1",frame=addr="0x00002a08", func="main",args=[],file="hello.c",line="23" (gdb) The -exec-show-arguments command Synopsis -exec-show-arguments Prints the arguments of the program. GDB command The corresponding GDB command is 'show args'. Example N.A.
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.c",line="16" (gdb) The -exec-step-instruction command Synopsis -exec-step-instruction Asynchronous command. Resumes the inferior which executes one machine instruction. The output, once GDB has stopped, will vary depending on whether we have stopped in the middle of a source line or not.
greater than the current one is reached. The reason for stopping in this case will be 'location-reached'. GDB command The corresponding GDB command is 'until'. Example (gdb) -exec-until recursive2.c:6 ^running (gdb) x = 55 *stopped,reason="location-reached",thread-id="1",frame=addr="0x00002a24",func="main",args=[], file="recursive2.c",line="6" (gdb) The -file-exec-and-symbols command Synopsis -file-exec-and-symbols file Specify the executable file to be debugged.
GDB command The corresponding GDB command is 'exec-file'. Example (gdb) -file-exec-file /kwikemart/marge/ezannoni/TRUNK/mbx/hello.mbx ^done (gdb) The -file-list-exec-sections command Synopsis -file-list-exec-sections List the sections of the current executable file. GDB command The GDB command 'info file' shows, among the rest, the same information as this command. gdbtk has a corresponding command 'gdb_load_info'. Example N.A.
GDB command The corresponding GDB command is info shared. Example N.A. The -file-list-symbol-files command Synopsis -file-list-symbol-files List symbol files. GDB command The corresponding GDB command is 'info file' (part of it). Example N.A. 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.
Exit GDB immediately. GDB command Approximately corresponds to 'quit'. Example (gdb) -gdb-exit The -gdb-set command Synopsis -gdb-set Set an internal GDB variable. 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'.
Show version information for GDB. Used mostly in testing. GDB command The corresponding GDB command is 'show version'. Example (gdb) -gdb-version ~GNU gdb 5.2.1 ~Copyright 2000 Free Software Foundation, Inc. ~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.
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).
file="../../../devo/gdb/testsuite/gdb.mi/basics.c",line="27"}, frame={level="4 ",addr="0x000107e0",func="main", file="../../../devo/gdb/testsuite/gdb.mi/basics.
arguments (inclusive). If the two arguments are equal, it shows the single frame at the corresponding level. GDB command The corresponding GDB commands are 'backtrace' and 'where'. Example Full stack backtrace: (gdb) -stack-list-frames ^done,stack= [frame={level="0 ",addr="0x0001076c",func="foo", file="recursive2.c",line="11"}, frame={level="1 ",addr="0x000107a4",func="foo", file="recursive2.c",line="14"}, frame={level="2 ",addr="0x000107a4",func="foo", file="recursive2.
(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. With an argument of 0 prints only the names of the variables, with argument of 1 prints also their values. GDB command 'info locals' in GDB, 'gdb_get_locals' in gdbtk.
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. The -symbol-info-function command Synopsis -symbol-info-function Show which function the symbol lives in.
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 command 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. GDB command The corresponding GDB command is 'info symbol'. Example N.A.
List all the type names. GDB command The corresponding commands are 'info types' in GDB, 'gdb_search' in gdbtk. Example N.A. The -symbol-list-variables command Synopsis -symbol-list-variables List all the global and static variable names. GDB command 'info variables' in GDB, 'gdb_search' in gdbtk. 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.
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. 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.
Example (gdb) -target-detach ^done (gdb) The -target-download command 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).
+download,{section=".text",section-sent="1536",section-size="6668", total-sent="1536",total-size="9880"} +download,{section=".text",section-sent="2048",section-size="6668", total-sent="2048",total-size="9880"} +download,{section=".text",section-sent="2560",section-size="6668", total-sent="2560",total-size="9880"} +download,{section=".text",section-sent="3072",section-size="6668", total-sent="3072",total-size="9880"} +download,{section=".
Example N.A. The -target-list-available-targets command 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-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', and so on. 'parameters' Device names, host names and the like. See “Commands for managing targets” (page 133), for more details.
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.
^running (gdb) ~"0x7f7f0aec" *stopped,reason="end-stepping-range",thread-id="2",frame=addr="0x00002ca4",func ="printme",args=[name="ip"],file="multithread.c",line="9" (gdb) -thread-list-ids ^done,thread-ids=thread-id="2",thread-id="1",number-of-threads="2" (gdb) -thread-select 1 ^done,new-thread-id="1",frame=level="0 ",addr="0x7ad47d70",func="_lwp_create"," +0x10",args=[],from="/usr/lib/libpthread.1" (gdb) 21.13 GDB/MI tracepoint commands The tracepoint commands are not yet implemented. 21.
binary, decimal, hexadecimal, octal, and natural. Natural refers to a default format automatically chosen based on the variable type (like decimal for an int, hex for pointers, and so on.).
The frame under which the expression should be evaluated can be specified by frame-addr. A '*' indicates that the current frame should be used. expression is any expression valid on the current language set (must not begin with a '*'), or one of the following: • • • '*addr', where addr is the address of a memory cell '*addr-addr' ― a memory address range (TBD) '$regname' ― a CPU register name Result This operation returns the name, number of children and the type of the object created.
Returns the number of children of a variable object name: numchild=n The -var-list-children command Synopsis -var-list-children name Returns a list of the children of the specified variable object: numchild=n,children={{name=name, numchild=n,type=type},(repeats N times)} The -var-info-type command Synopsis -var-info-type name Returns the type of the specified variable name.
value=value The -var-assign command Synopsis -var-assign name expression Assigns the value of expression to the variable object specified by name. The object must be 'editable'. The -var-update command Synopsis -var-update {name | "*"} Update the value of the variable object name by evaluating its expression after fetching all the new values from memory or registers. A '*' causes all existing variable objects to be updated. 21.
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. In order for a bug report to serve its purpose, you must include the information that enables us to x the bug. 22.
Keep in mind that the purpose of a bug report is to enable us to x the bug. It may be that the bug has been reported previously, but neither you nor we can know that unless your bug report is complete and self-contained. 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.
• A description of the envelope of the bug. Often people who encounter a bug spend a lot of time investigating which changes to the input file will make the bug go away and which changes will not affect it. This is often time consuming and not very useful, because the way we will nd the bug is by running a single example under the debugger with breakpoints, not by pure deduction from a series of examples. We recommend that you save your time for something else.
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.
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. Pass the identifier for the platform on which GDB will run as an argument. For example: cd gdb-gdb-199991101 .
(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. If the path to configure would be the same as the argument to --srcdir, you can leave out the --srcdir option; it is assumed.
% 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.sub is also distributed in the GDB source directory (gdb-gdb-199991101, for version gdb-199991101). A.
--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.