Debugging with GDB Manual The GNU Source-Level Debugger HP Part Number: 5900-2180 Published: August 2012 Edition: 23
© Copyright 2012 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.
Contents Summary of GDB........................................................................................13 Free Software.........................................................................................................................13 Contributors to GDB................................................................................................................13 1 A Sample GDB Session.............................................................................17 1.
5.1.5 Break conditions........................................................................................................45 5.1.6 Breakpoint command lists............................................................................................46 5.1.7 Breakpoint menus.......................................................................................................47 5.1.8 Cannot insert breakpoints...........................................................................................48 5.
9.4.1.5 C and C++ type and range checks.......................................................................84 9.4.1.6 GDB and C.......................................................................................................84 9.4.1.7 GDB features for C++.........................................................................................84 9.4.2 Fortran.....................................................................................................................85 9.4.2.1 Fortran types..
14.10.1 When to suspect a memory leak.............................................................................120 14.10.2 Memory debugging restrictions..............................................................................121 14.10.3 Memory Debugging Methodologies........................................................................121 14.10.4 Debugging Memory in Interactive Mode.................................................................121 14.10.4.
14.15 Debugging Core Files...................................................................................................153 14.15.1 Generating core files with packcore /unpackcore/getcore..........................................153 14.15.2 Support for the info target Command......................................................................154 14.15.3 Support for the dumpcore command.......................................................................155 14.15.3.
14.26.5 Support for debugging namespaces.......................................................................176 14.26.6 Command for evaluating the address of an expression.............................................176 14.27 Viewing Wide Character Strings...................................................................................176 14.28 Support for output logging...........................................................................................177 14.28.
15 The HP-UX Terminal User Interface...........................................................193 15.1 Starting the TUI..............................................................................................................193 15.2 Automatically running a program at startup......................................................................194 15.3 Screen Layouts..............................................................................................................194 15.3.1 Source pane......
17 Controlling GDB...................................................................................225 17.1 Setting the GDB Prompt..................................................................................................225 17.2 Setting Command Editing Options in GDB........................................................................225 17.3 Setting Command History Feature in GDB.........................................................................225 17.4 Setting the GDB Screen Size.......
21.14 GDB/MI variable objects...............................................................................................282 22 Reporting Bugs in GDB.........................................................................287 22.1 Have you found a bug?..................................................................................................287 22.2 How to report bugs.......................................................................................................287 A Installing GDB.......
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.
Michael Tiemann is the author of most of the GNU C++ support in GDB, with significant additional contributions from Per Bothner. James Clark wrote the GNU C++ demangler. Early work on C++ was by Peter TerMaat (who also did much general update work leading to release 3.0). GDB 4 uses the BFD subroutine library to examine multiple object-file formats; BFD was a joint project of David V. Henkel-Wallace, Rich Pixley, Steve Chamberlain, and John Gilmore.
Nag, Muthuswami, Dennis Handly, Subash Babu and Dipshikha Basu provided HP-specific information in this manual. Cygnus Solutions has sponsored GDB maintenance and much of its development since 1991.
1 A Sample GDB Session This chapter describes the most common GDB commands with the help of an example.
GDB reads only enough symbol data to know where to find the rest when needed; as a result, the first prompt comes up very quickly. 1.2 Setting Display width We now tell GDB to use a narrower display width than usual, so that examples fit in this manual. ((gdb)) set width 70 We need to see how the m4 built-in changequote works. Having looked at the source, we know the relevant subroutine is m4_changequote, so we set a breakpoint there with the GDB break command. 1.
(which can also be spelled bt), to see where we are in the stack as a whole: the backtrace command displays a stack frame for each active subroutine. ((gdb)) bt #0 set_quotes (lq=0x34c78 "", rq=0x34c88 "") at input.c:530 #1 0x6344 in m4_changequote (argc=3, argv=0x33c70) at builtin.c:882 #2 0x8174 in expand_macro (sym=0x33320) at macro.c:242 #3 0x7a88 in expand_token (obs=0x0, t=209696, td=0xf7fffa30) at macro.c:71 #4 0x79dc in expand_input () at macro.
((gdb)) p len_rquote $4 = 7 1.10 Setting Variable Values During a Session That certainly looks wrong, assuming len_lquote and len_rquote are meant to be the lengths of lquote and rquote respectively. We can set them to better values using the p command, since it can print the value of any expression―and that expression can include subroutine calls and assignments.
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.
Many options have both long and short forms; both are shown in the following list. GDB also recognizes the long forms if you truncate them, so long as enough of the option is present to be unambiguous. (If you prefer, you can flag option arguments with `--' rather than `-', though we illustrate the more usual convention.) -symbols file -s file Read symbol table from file file.
-quiet, -silent, -q “Quiet”. Do not print the introductory and copyright messages. These messages are also suppressed in batch mode. -batch Run in batch mode. Exit with status 0 after processing all the command files specified with '-x' (and all commands from initialization files, if not inhibited with '-n'). Exit with nonzero status if an error occurs in executing the GDB commands in the command files.
-async Use the asynchronous event loop for the command-line interface. GDB processes all events, such as user1 keyboard input, via a special event loop. This allows GDB to accept and process user commands in parallel with the debugged process being run1, so you do not need to wait for control to return to GDB before you type the next command. NOTE: As of version 5.0, the target side of the asynchronous operation is not yet in place, so '-async' does not work fully yet.
$ gdb | tee log1 2.2 Quitting GDB quit [expression], q To exit GDB, use the quit command (abbreviated q), or type an end-of-file character (usually C-d). If you do not supply expression, GDB will terminate normally; otherwise it will terminate using the result of expression as the error code. An interrupt (often C-c) does not exit from GDB, but rather terminates the action of any GDB command that is in progress and returns to GDB command level.
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.
the bell.
internals -- Maintenance commands obscure -- Obscure features running -- Running the program stack -- Examining the stack status -- Status inquiries support -- Support facilities tracepoints -- Tracing of program execution without stopping the program user-defined -- User-defined commands Type "help" followed by a class name for a list of commands in that class. Type "help" followed by command name for full documentation. Command name abbreviations are allowed if unambiguous.
In addition to help, you can use the GDB commands info and show to inquire about the state of your program, or the state of GDB itself. Each command supports many topics of inquiry; this manual introduces each of them in the appropriate context. The listings under info and under show point to all the sub-commands. info This command (abbreviated i) is for describing the state of your program.
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.
standard input and output. Your program as default uses the same device for standard input and standard output as GDB is using. You can redirect input and output in the run command line, or you can use the tty command to set a different device for your program. See “Program Input and Output” (page 33).
variables to be given to your program. You can abbreviate environment as env. set environment varname [=value] Set environment variable varname to value. The value changes for your program only, not for GDB itself. The value may be any string; the values of environment variables are just strings, and any interpretation is supplied by your program itself. The value parameter is optional; if it is eliminated, the variable is set to a null value.
Another way to specify where your program should do input and output is with the tty command. This command accepts a file name as argument, and causes this file to be the default for future run commands. It also resets the controlling terminal for the child process, for future run commands. For example, tty tty /dev/ttyb directs that processes started with subsequent run commands default to do input and output on the terminal '/dev/ttyb' and have that as their controlling terminal.
detached. After the detach command, that process and GDB become completely independent once more, and you are ready to attach another process or start one with run. detach does not repeat if you press RET again after executing the command. If you exit GDB or use the run command while you have an attached process, you kill that process.
Following commands are used to debug multi-threaded programs: • 'thread threadno', a command to switch among threads • 'info threads', a command to inquire about existing threads • 'thread apply [threadno] [all] args', a command to apply a command to a list of threads The GDB thread debugging facility allows you to observe all threads while your program runs―but whenever GDB takes control, one thread in particular is always the focus of debugging. This thread is called the current thread.
For example, ((gdb)) info threads * 3 system thread 26607 worker (wptr=0x7b09c318 "@") \ at quicksort.c:137 2 system thread 26606 0x7b0030d8 in __ksleep () \ from /usr/lib/libc.2 1 system thread 27905 0x7b003498 in _brk () \ from /usr/lib/libc.2 thread threadno Make thread number threadno the current thread. The command argument threadno is the internal GDB thread number, as shown in the first field of the 'info threads' display.
not occur when you do not want to run GDB on the child. While the child is sleeping, use the ps program to get its process ID. Then tell GDB (a new invocation of GDB if you are also debugging the parent process) to attach to the child process (see “Debugging a Running Process” (page 34)). From that point on you can debug the child process just like any other process which you attached to. On HP-UX (11.
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.
selected stack frame. (See “Stack frames” (page 55), for a description of stack frames.) break linenum Set a breakpoint at line linenum in the current source file. The current source file is the last file whose source text was printed. The breakpoint will stop your program just before it executes any of the code on that line. break filename:linenum Set a breakpoint at line linenum in source file filename. break filename:function Set a breakpoint at entry to function function found in file filename.
instruction address that is assigned to the debug registers. However, the hardware breakpoint registers can take a limited number of breakpoints. For example, on the DSU, only two data breakpoints can be set at a time, and GDB will reject this command if more than two are used. Delete or disable unused hardware breakpoints before setting new ones (see “Disabling breakpoints” (page 44)). See “Break conditions” (page 45). thbreak args Set a hardware-assisted breakpoint enabled only for one stop.
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. info break with a breakpoint number n as argument lists only that breakpoint. The convenience variable $_ and the default examining-address for the x command are set to the address of the last breakpoint listed (see “Examining memory” (page 66)).
tcatch event catch The catching of a C++ exception. exec A call to exec. This is currently only available for HP-UX. fork A call to fork. This is currently only available for HP-UX. 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.
With the clear command you can delete breakpoints according to where they are in your program. With the delete command you can delete individual breakpoints, watchpoints, or catchpoints by specifying their breakpoint numbers. It is not necessary to delete a breakpoint to proceed past it. GDB automatically ignores breakpoints on the first instruction to be executed when you continue execution without changing the execution address.
enable [breakpoints] delete Enable the specified breakpoints to work once, then die. GDB deletes any of these breakpoints as soon as your range... program stops there. Except for a breakpoint set with tbreak (see “Setting breakpoints” (page 39)), breakpoints that you set are initially enabled; subsequently, they become disabled or enabled only when you use one of the commands above.
A special case of a breakpoint condition is to stop only when the breakpoint has been reached a certain number of times. This is so useful that there is a special way to do it, using the ignore count of the breakpoint. Every breakpoint has an ignore count, which is an integer. Most of the time, the ignore count is zero, and therefore has no effect. But if your program reaches a breakpoint whose ignore count is positive, then instead of stopping, it just decrements the ignore count by one and continues.
that the breakpoint was reached. silent is meaningful only at the beginning of a breakpoint command list. The commands echo, output, and printf allow you to print precisely controlled output, and are often useful in silent breakpoints. See “Commands for controlled output” (page 231). For example, here is how you could use breakpoint commands to print the value of x at entry to foo whenever x is positive.
5.1.8 “Cannot insert breakpoints” Under some operating systems, breakpoints cannot be used in a program if any other process is running that program. In this situation, attempting to run or continue a program with a breakpoint causes GDB to print an error message: Cannot insert breakpoints. The same program may be running in another process. When this happens, you have three ways to proceed: 1. 2. 3. Remove or disable the breakpoints, then continue.
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.
in the following excerpt from a debugging session, the f (frame) command shows that execution is stopped at line 206; yet when we use until, we get to line 195: ((gdb)) f #0 main (argc=4, argv=0xf7fffae8) at m4.
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.
into the erroneous variables and continue, hoping to see more execution; but your program would probably terminate immediately as a result of the fatal signal once it saw the signal. To prevent this, you can continue with 'signal 0'. See “Giving your program a signal” (page 92). 5.4 Stopping and starting multi-thread programs When your program has multiple threads (see “Debugging programs with multiple threads” (page 35)), you can choose whether to set breakpoints on all threads, or on a particular thread.
will never steal the GDB prompt away from the thread that you are debugging. show scheduler-locking Display the current scheduler locking mode. 5.
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.
number or the address of the frame. With argument, nothing is printed if input is coming from a command file or a user-defined command. select-frame The select-frame command allows you to move from one stack frame to another without printing the frame. This is the silent version of frame. 6.4 Backtraces A backtrace is a report of the active stack frames instantiated by the execution of a program.
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.
The verbose description is useful when something has gone wrong that has made the stack format fail to fit the usual conventions. 58 info frame addr, info f addr Print a verbose description of the frame at address addr, without selecting that frame. The selected frame remains unchanged by this command. This requires the same kind of address (more than one for some architectures) that you specify in the frame command. See “Selecting a frame” (page 56).
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 56)), GDB prints the line where execution in that frame has stopped. You can print other portions of source files by explicit command.
+offset Specifies the line offset lines after the last line printed. When used as the second linespec in a list command that has two, this specifies the line offset lines down from the first linespec. -offset Specifies the line offset lines before the last line printed. filename:number Specifies line number in the source file filename. function Specifies the line that begins the body of the function function. For example: in C, this is the line with the open brace.
working directory. '$cwd' is not the same as '.'. The former tracks the current working directory as it changes during your GDB session, while the latter is immediately expanded to the current directory at the time you add an entry to the source path. directory Reset the source path to empty again. This requires confirmation from the user. show directories Print the source path and display the directories it contains.
0x32e0 : ldil 0x3000,r31 End of assembler dump. Some architectures have more than one commonly-used set of instruction mnemonics or other syntax. set disassembly-flavor instruction-set Select the instruction set to use when disassembling the program via the disassemble or x/i commands. Currently this command is only defined for the Intel x86 family. You can set instruction-set to either intel or att. The default is att, the AT&T flavor used by default by Unix assemblers for x86-based targets.
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 77)). The following forms of print command are supported: print expr, print /f expr expr is an expression (in the source language).
Variables in expressions are understood in the selected stack frame (see “Selecting a frame” (page 56); they must be either: • global (or file-static) or • visible according to the scope rules of the programming language from the point of execution in that frame This means that in the function foo (a) int a; { bar (a); { int b = test (); bar (b); } } you can examine and use the variable a whenever your program is executing within the function foo, but you can only use or examine the variable b while yo
superior to formats such as COFF. You may be able to use DWARF-2 ('-gdwarf-2'), which is also an effective form for debug info. See “Compiling for debugging” (page 31). 8.3 Artificial arrays It is often useful to print out several successive objects of the same type in memory; a section of an array, or an array of dynamically determined size for which only a pointer exists in the program. You can do this by referring to a contiguous span of memory as an artificial array, using the binary operator '@'.
u Print as integer in unsigned decimal. o Print as integer in octal. 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.
value (though it may); it is always interpreted as an integer address of a byte of memory. Refer to See “Expressions” (page 63), for more information on expressions. The default for addr is usually just after the last address examined―but several other commands also set the default address: info breakpoints (to the address of the last breakpoint listed), info line (to the starting address of a line), and print (if you use it to display a value from memory).
display/fmt expr For fmt specifying only a display format and not a size or count, add the expression expr to the auto-display list but arrange to display it each time in the specified format fmt. See“Output formats” (page 65). display/fmt addr For fmt 'i' or 's', or including a unit-size or a number of units, add the expression addr as a memory address to be examined each time your program stops. Examining means in effect doing 'x/fmt addr'. See “Examining memory” (page 66).
at input.c:530 530 if (lquote != def_lquote) 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.
set print array, set print array on Pretty print arrays. This format is more convenient to read, but uses more space. The default is off. set print array off Return to compressed format for arrays. show print array Show whether compressed or pretty format is selected for displaying arrays. set print elements number-of-elements Set a limit on how many elements of an array GDB will print.
typedef enum {Tree, Bug} Species; typedef enum {Big_tree, Acorn, Seedling} Tree_forms; typedef enum {Caterpillar, Cocoon, Butterfly} Bug_forms; struct thing { Species it; union { Tree_forms tree; Bug_forms bug; } 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 = {...
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. set print object, set print object on When displaying a pointer to an object, identify the actual (derived) type of the object rather than the declared type, using the virtual function table. set print object off Display only the declared type of objects, without reference to the virtual function table. This is the default setting.
then the value recorded in the value history by the print command remains 4 even though the value of x has changed. show values Print the last ten values in the value history, with their item numbers. This is like 'p $$9' repeated ten times, except that show values does not change the history. show values n Print ten history values centered on history item number n. show values + Print ten history values following the values last printed.
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 ...
8.11 Printing Floating Point Values You can print the values of floating-point registers in different formats. To print both single and double-precision values: (gdb) info reg $fr5 fr5 (single precision) 10.1444092 fr5 To get the bit pattern, try the following macro: define pbits set *((float *) $sp)=$arg0 p/x *((int *) $sp) end This is what the macro produces: (gdb) pbits $fr6 $1 = 0x4082852d 8.
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'.
If you wish, you may set the language manually. To do this, issue the command 'set language lang', where lang is the name of a language, such as c. For a list of the supported languages, type 'set language'. Setting the language manually prevents GDB from updating the working language automatically. This can lead to confusion if you try to debug a program when the working language is not the same as the source language, when an expression is acceptable to both languages―but means different things.
GDB can check for conditions like the above if you wish. Although GDB does not check the statements in your program, it can check expressions entered directly into GDB for evaluation via the print command, for example. As with the working language, GDB can also decide whether or not to check automatically based on your source language. See “Supported languages” (page 80), for the default settings of supported languages. 9.3.
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. In many implementations of C, mathematical overflow causes the result to “wrap around” to lower values―for example, if m is the largest integer value, and s is the smallest, then m + 1 ⇒ s This, too, is specific to individual languages, and in some cases specific to individual compilers or machines.
For the purposes of C and C++, the following definitions hold: • Integral types include int with any of its storage-class specifiers; char; enum; and, for C++, bool. • Floating-point types include float, double, and long double (if supported by the target platform). • Pointer types include all types defined as (type *). • Scalar types include all of the above. The following operators are supported. They are listed here in order of increasing precedence: , The comma or sequencing operator.
~ Bitwise complement operator. Defined on integral types. Same precedence as ++. ., -> Structure member, and pointer-to-structure member. For convenience, GDB regards the two as equivalent, choosing whether to dereference a pointer based on the stored type information. Defined on struct and union data. .*, ->* Dereferences pointers to members. [] Array indexing. a[i] is defined as *(a+i). Same precedence as ->. () Function parameter list. Same precedence as ->. :: C++ scope resolution operator.
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.
`RWCollectableDate d3(15,5,2001);' printing the variable or class returns: (gdb) p d3 $3 = {} (gdb) ptype RWCollectableDate type = class RWCollectableDate { 9.4.1.4 C and C++ defaults If you allow GDB to set type and range checking automatically, they both default to off whenever the working language changes to C or C++. This happens regardless of whether you or GDB selects the working language.
set print demangle, show print demangle, set print asm-demangle, show print asm-demangle Control whether C++ symbols display in their source form, both when displaying code as C++ source and when displaying disassemblies. See “Print settings” (page 68). set print object, show print Choose whether to print derived (actual) or declared types of objects. See “Print settings” (page 68). object set print vtbl, show print vtbl Control the format for printing virtual function tables.
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]).
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 21)), or by one of the file-management commands (see “Commands to specify files” (page 95)).
info types regexp, info types Print a brief description of all types whose names match regexp (or all types in your program, if you supply no argument). Each complete typename is matched as though it were a complete line; thus, 'i type value' gives information on all types in your program whose names include the string value, but 'i type ^value$' gives information only on types whose complete name is value.
symbol-reloading off, since otherwise GDB may discard symbols when linking large programs, that may contain several modules (from different directories or libraries) with the same name. show Show the current on or off setting. symbol-reloading set opaque-type-resolution on Tell GDB to resolve opaque types.
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.
The steps shown above sets the gnutarget to an invalid value in place of the program variable g. In order to set the variable g, use ((gdb)) set var g=4 GDB allows more implicit conversions in assignments than C; you can freely store an integer value into a pointer variable or vice versa, and you can convert any structure to any other structure that is the same length or shorter. To store values into arbitrary places in memory, use the '{...
Alternatively, if signal is zero, continue execution without giving a signal. This is useful when your program stopped on account of a signal and would ordinary see the signal when resumed with the continue command; 'signal 0' causes it to resume without a signal. signal does not repeat when you press RET a second time after executing the command. Invoking the signal command is not the same as invoking the kill utility from the shell.
show write 94 Altering Execution Display whether executable files and core files are opened for writing as well as reading.
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 21)). Occasionally it is necessary to change to a different file during a GDB session.
environment; you may use either a gnu compiler, or other compilers that adhere to the local conventions. For most kinds of object files, the symbol-file command does not normally read the symbol table in full right away. Instead, it scans the symbol table quickly to find which source files and which symbols are present. The details are read later, one source file at a time, as they are needed. The purpose of this two-stage reading strategy is to make GDB start up faster.
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.
On HP-UX systems, GDB detects the loading of a shared library and automatically reads in symbols from the newly loaded library, up to a threshold that is initially set but that you can modify if you wish. Beyond that threshold, symbols from shared libraries must be explicitly loaded. To load these symbols, use the command sharedlibrary filename. The base address of the shared library is determined automatically by GDB and need not be specified.
For example, if you have more than one shared library with the same name but different path names, you may want to use GDB_SHLIB_ROOT because GDB searches for libraries based on the full path name. Note that GDB_SHLIB_PATH may not give you the results you expect because GDB searches for libraries that match only the name, regardless of the path, and always accepts the first library that matches the name. For example, if you want to use /tmp/usr/lib/libsubs.sl and /tmp/usr/share/lib/ libsubs.
unknown symbol type 0xnn The symbol information contains new data types that GDB does not yet know how to read. 0xnn is the symbol type of the uncomprehended information, in hexadecimal. GDB circumvents the error by ignoring this symbol information. This usually allows you to debug your program, though certain symbols are not accessible.
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.
with gnutarget the target refers to a program, not a machine. Warning: To specify a file format with set gnutarget, you must know the actual BFD name. See “Commands to specify files” (page 95). show gnutarget Use the show gnutarget command to display what file format gnutarget is set to read. If you have not set gnutarget, GDB will determine the file format for each file automatically, and show gnutarget displays `The current BDF target is "auto"'.
Many remote targets require you to download the executable code once you have successfully established a connection. load filename Depending on what remote debugging facilities are configured into GDB, the load command may be available. Where it exists, it is meant to make filename (an executable) available for debugging on the remote system|by downloading, or dynamic linking, for example. load also records the filename symbol table in GDB, like the add-symbol-file command.
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.
• “Support for Fortran array slices” (page 177) • “Displaying enumerators” (page 178) • “Support for debugging typedefs” (page 178) • “Support for steplast command for C and C++” (page 178) • “Getting information from a non-debug executable” (page 179) • “Debugging optimized code” (page 179) • “Debugging with ARIES” (page 182) • “Visual Interface for HP WDB” (page 184) • “Support for ddd” (page 188) • “Support for XDB commands” (page 188) • “GDB Logging Commands” (page 188) • “Support
• Source level debugging of Fortran applications that contain nested routines. • Command watch_target. • Command line option set display-full-path that displays the full pathname of the source file name while printing the frame information. • Command line option set dereference [on |off] when off, HP WDB does not dereference char * variables by default.
strcat() ctime() dlclose() memchr() strrchr() dlgetname() dlget() clock_gettime() strlen() dlhook() dlmodinfo() environ() getenv() strlen() execl() exit() fclose() fork() strdup() fopen() fprintf() fscanf() sscanf() strcasecmp() getcwd() getpagesize() getpid() srand() strcmp() printf() pthread_self() putenv() shmctl() strchr() rand() uwx_self_lookupip() shl_get() shl_unload() shl_findsym () strtok_r() time() uwx_get_reg() shl_get_r() perror() uwx_init() uwx_self_copyin() creat() uwx_step() write() uwx_self
PA-RISC WDB. The PA-RISC version of HP WDB is provided as part of the HP-UX operating system. • Support for debugging large core files (> 2GB) HP WDB supports debugging of core files with sizes more than 2 GB. • Support co-variant type HP WDB can step into a co-variant function. The compiler-generated function called thunks, which is used internally by the compiler to support co-variant return type, is not shown when you do a backtrace or switch from one frame to another frame.
Defined Variable /opt/langtools/binGDB_ROOT $GDB_SERVER WDB Location /opt/langtools/libn/a n/a GDB location WDB_ROOT $GDB_ROOT/bin LIBRTC_SERVER librtc.sl location $WDB_ROOT/bin /opt/langtools/binn/a None $WDB_ROOT/bin GDB_SERVER n/a /opt/langtools/bin$WDB_ROOT/lib 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.
If the debugger cannot find the source files, perform the following steps: 1. 2. Make certain the files were compiled with the -g switch. Type info sources to find the list of files that the debugger knows were compiled with -g. Make certain that the debugger can find the source file. Type show dir to find the list of directories the debugger uses to search for source files and type set dir to change that path.
14.7.1 Fix and Continue compiler dependencies Fix and Continue is supported only for PA-RISC on HP-UX 11.x with these compilers: • HP C/ANSI C A.11.01.20, or later • HP aC++ A.03.25, or later • HP Fortran 90 2.4, or later 14.7.2 Fix and Continue restrictions Fix and Continue has the following restrictions and behaviors: • You cannot recompile code that has been optimized. • You cannot add, delete, or reorder the local variables and parameters in a function currently active on the stack.
changed, HP WDB asks if you want to fix the changed source, allowing you to apply repeated fixes without explicitly entering the fix command. The Fix and Continue facility enables you to make the following changes: • Change existing function definitions. • Disable, reenable, save, and delete redefinitions • Adding global and file static variables. • Add new structure fields to the end of a structure type object. • Set breakpoints in and single-step within redefined code.
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. Because you are going to edit the current file, you do not need to specify a source file name.
option (introduced in the A.03.65 and later versions of the HP aC++ compiler). In Integrity systems, the applications that are compiled with -g option support inline debugging by default and require no additional options. Compiler versions A.06.02 and later support the inline debugging feature in Integrity systems. 14.8.1 Inline Debugging in HP 9000 Systems To debug inline functions in HP 9000 systems, complete the following steps: 1. Compile the source files with the +inline_debug option.
The set inline-debug on command enables the inline debugging feature without the inline breakpoints options in Integrity systems. This command is enabled by default. 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 breakpoints on all instances of a particular inline function.
(gdb) set inline-debug off or $ gdb --inline= off 3. You can use the following commands for debugging inline functions in Integrity systems: step next list backtrace frame info locals info args breakpoint The following commands are not available for debugging inline functions in Integrity systems: info frame disassembly 14.9 Debugging Macros HP WDB 5.7 and later versions of the debugger enable you to display and evaluate macro definitions for programs running on Integrity systems.
14.9.1.1 Compiler Options to Enable Macro Debugging To enable macro debugging, the program must be compiled with the +macro_debug=[all|none|ref] compiler option. Additionally, the program must be compiled with one of the -g options (-g, -g0, or -g1) to enable macro debugging. For example: cc -g +macro_debug=all -o sample sample.
$ cc -g +macro_debug=all -o sc scope.c $ gdb sc HP gdb for HP Itanium (32 or 64 bit) and target HP-UX 11.2x. Copyright 1986 - 2001 Free Software Foundation, Inc. ... (gdb) b 13 Breakpoint 1 at 0x40007d0:0: file scope.c, line 13 from sc. (gdb) b 23 Breakpoint 2 at 0x40007d0:2: file scope.c, line 23 from sc. (gdb) b 30 Breakpoint 3 at 0x40007e0:0: file scope.c, line 30 from sc. (gdb) r Starting program: sc Breakpoint 1, main () at scope.
(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.c:23 23 val = USED1 + USED2; (gdb) info macro USED1 Defined at scope.c:20 #define USED1 101 (gdb) info macro USED2 Defined at scope.c:21 #define USED2 201 (gdb) c Continuing. Breakpoint 3, main () at scope.c:30 30 val = USED1; (gdb) info macro USED1 Defined at scope.
14.10.2 Memory debugging restrictions Programs with these attributes are not supported: • CMA or DCE threaded programs on 11.x (32-bit and 64-bit) • Memory checking features. These features work only in programs that directly or indirectly call malloc, realloc, free, mmap, or munmap from the standard C library libc.sl. • Programs that link the archive version of the standard C library, libc.a, or the core library, libcl.a, on HP-UX 11.x NOTE: Linker with version number B.11.
14.10.4.1 Commands for interactive memory debugging To debug memory problems, use these commands: set heap-check [on|off] This toggles the capability for detection of leaks, heap profiles, bounds checking, and checking for double free. info heap Displays a heap report, listing information such as the start of heap, end of heap, heap size, heap allocations, size of blocks, and number of instances. The report shows heap usage at the point you use the info heap command.
set heap-check block-size num-bytes Instructs HP 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 HP WDB to stop the program whenever it tries to increase the program heap by at least num-bytes.
info dangling Displays a list of all the dangling pointers and dangling blocks that are potential sources of memory corruption( may have false positives). info corruption Checks for corruption in the currently allocated heap blocks.In addition, it lists the potential in-block corruptions in all the freed blocks. set heap-check min-leak-size num Collects a stack trace only when the size of the leak exceeds the number of bytes you specify for this value. Larger values improve run-time performance.
2 245 8 0x40410838 strdup() [...] 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.
scramble_blocks=on|off (or) Enables block scrambling. set heap-check scramble Batch mode leak detection stops the application at the end, when libraries are being unloaded, and invokes HP WDB to print the leak or heap data. NOTE: It is incorrect usage to use spaces before or after the '=' symbol in the batch mode configuration options in the configuration file, rtcconfig. Additionally, it is incorrect usage to use spaces before the batch mode configuration options.
To preload the librtc runtime library from a path that is different from the default paths, you must use the LD_PRELOAD environment variable. • Instead of automatically preloading librtc and mapping the shared libraries, you can explicitly preload the required librtc library after mapping the shared libraries private. In the case of HP 9000 systems, you must explicitly map the share libraries as private by using the +dbg enable option for the chatr command, as follows: $ chatr +dbg enable .
NOTE: During operations such as system(3s) and popen(), which invoke a new shell, librtc.sl|so must not be loaded to the invoked shell. You must use LD_PRELOAD_ONCE, instead of LD_PRELOAD, to exclusively load the librtc.sl|so file to the calling process only. Following is the syntax for using LD_PRELOAD_ONCE: LD_PRELOAD_ONCE= /opt/langtools/lib/librtc.sl 14.10.5.
mem_logfile=stderr[+]filename heap_logfile=stderr[+]filename ◦ • Specify config_strings for +check=malloc on Itanium or HP WDB memory check batch mode on Integrity systems. Processing of the .gdbinit file is not enabled in batch mode from librtc 6.1 version and later. On Itanium system for librtc versions prior to 6.1, 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, HP 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.
3. Set the following environment variables as follows: export BATCH_RTC=on 4. Complete one of the following steps: ◦ Use the +rtc option for the chatr command on each of the required executable files that must be instrumented, as follows: $ chatr +rtc enable exec1 exec2 exec3 OR ◦ Preload the librtc library as follows: export LD_PRELOAD /opt/langtools/lib/hpux32/librtc.so 5. Run the program as follows: .
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.
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. • From HP WDB Version 6.3 and later, you can configure rtcconfig file in attach mode along with batch mode. 14.10.7 Open-files reporting From version 6.2 onwards, HP WDB enables you to obtain a report containing a list of file descriptors corresponding to files open by the application at the point of its exit.
For example, if you use, set heap-check min-leak-size 100 HP 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.8.
set heap-check watch address You can use this to debug situations such as multiple free() calls to the same block. Limitation : This is not supported in batch mode debugging. 14.10.9.4 Scramble previous memory contents at malloc/free calls HP WDB enables you to potentially expose latent memory access defects with the command: – In Interactive debugging mode: set heap-check scramble [on | off] – In batch mode debugging: scramble_blocks [on | off].
14.10.9.7 Specify the amount of guard bytes for every block of allocated memory HP WDB enables you to programmatically control the size of guard bytes for every block of the allocated memory. You can use these guard bytes to spot very rare and non-trivial boundary (buffer over-run and buffer under-run) corruptions. This again is available optionally when the user specifies set heap-check retain-freed-blocks . 14.10.10 Comparison of Memory Debugging Commands in Interactive Mode and Batch Mode HP WDB 5.
Table 2 Memory Debugging Commands in Interactive and Batch Mode (continued) Command Description Interactive mode Batch mode Specifies the random range to be used by set heap-check random-range. random-range Not supported in batch mode Specifies the time interval to be used for incremental memory profile. set heap-check interval Not supported in batch mode Perform incremental profile for interval periods where each period duration is defined by set heap-check interval command.
14.10.11.4 info heap process The info heap process command enables the user to view a high level memory usage report of a process. This command is available only for applications running on 11i v3 or later. 14.10.11.5 Example for heap profiling This example shows how to use this feature on HP-UX 11.x: 1. If the linker version is earlier than B.11.19, link with /opt/langtools/lib/pa20_ 64/ librtc.sl for PA-64 programs. For a 32-bit program, you must link with /opt/langtools/ lib/librtc.sl.
14.10.13 Commands to track the change in data segment value The high water mark records the number of times the brk() value changes. The following commands are supported: info heap high-mem Displays the number of times brk() value changes for a given run. set heap-check high-mem-count X_number Stops when brk() value has moved X_number of times. Limitations: • This feature assumes that an application has a deterministic memory allocation pattern from one run to another.
(gdb) info threadsystem thread 4189 0x7f666da8 in __pthread_create_system+0x3d8 () from /usr/lib/libpthread.1 2 system thread 4188 worker (wptr=0x40004640 ") at quicksort.c:135 1 system thread 4184 0x7f66f728 in _lwp_create+0x10 () from /usr/lib/libpthread.1 To disable a thread, execute the following command: (gdb) thread disable 1 warning: ATTENTION!! Disabling threads may result in deadlocks in the program.
• Different threads non-concurrently wait on the same condition variable, but with different associated mutexes. • The thread terminates execution without unlocking the associated mutexes or read-write locks. • The thread waits on a condition variable for which the associated mutex is not locked. • 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 advanced thread debugging features can be enabled only if the set thread-check [on] command is enabled. The following advanced thread debugging options are available for the set thread-check command: recursive-relock [on|off] This set thread-check recursive-relock [on|off] command checks if a thread has attempted to acquire a non-recursive mutex that it currently holds. Re-locking a non-recursive mutex results in a deadlock.
cv-wait-no-mx [on|off] The set thread-check cv-wait-no-mx [on|off] checks if the associated mutex of a condition variable is locked when the thread calls the pthread_cond_wait() routine. The debugger transfers the execution control to the user and prints a warning message when this condition is detected. This check is not a POSIX.1 standard requirement for the pthread_cond_wait() routine. It is an additional check provided by HP WDB.
14.11.3.3 Commands to view information on pthread primitives HP WDB 5.5 and later versions of the debugger display extended information on pthread primitives for multi-threaded applications running on HP-UX 11i v2, or 11i v3. This feature is available only if the set thread-check [on|off] command is enabled.
◦ For 32 bit IPF applications, /opt/langtools/lib/hpux32/librtc.so ◦ For 64 bit IPF applications, /opt/langtools/lib/hpux64/librtc.so ◦ For 32 bit PA applications, opt/langtools/lib/librtc.sl ◦ For 64-bit PA applications, /opt/langtools/lib/pa20_64/librtc.sl To preload the librtc runtime library from a path that is different from the default paths, you must use the LD_PRELOAD environment variable.
14.11.5 Thread Debugging in Batch Mode HP WDB supports batch mode of debugging threads for HP-UX 11iv2 and later, on Integrity systems and on HP-UX 11i v3 in PA-RISC systems for 64 bit applications. The debugger provides a log file with the list of thread-related errors that occur in the application. In batch mode, the debugger detects the all the thread-conditions that are detected during an interactive debugging session.
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 141). 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.
14.11.5.2 Limitations in Batch mode of thread debugging The feature does not obtain the thread-error information in batch mode for forked process in a multiprocessing application. However, if the librtc.sl library is preloaded, the debugger obtains the thread-error information in the batch mode for exec-ed application. You cannot specify an alternate output directory for the thread-error log. The thread- error log file is output into the current working directory only.
This occurs when GDB attempts a command line call on an already overflowing thread stack. 14.12 Debugging MPI Programs You can attach the debugger to Message Passing Interface (MPI) programs for debugging. You must set the one of the following environment variables before you launch the MPI process: set MPI_FLAGS= egdb for invoking GDB or set MPI_FLAGS= ewdb for invoking WDB For more information, see the mpidebug(1) and mpienv(1) manpages.
Info block version:0x0, flags:0x0, length:4 * 4 == 16 0x40172b20: (0c) R1prologue rlen=12 0x40172b21: (e8) P7preds_when t=11 0x40172b23: (b1) P3preds_gr gr=41 0x40172b25: (ea) P7lc_when t=7 0x40172b27: (b2) P3lc_gr gr=40 0x40172b29: (61) R3body rlen=33 0x40172b2b: (81) B1label_state label=1 0x40172b2c: (c0) B2epilogue t=44 0x40172b2e: (00) R1prologue rlen=0 0x40172b2f: (00) R1prologue rlen=0 14.
Example 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.
"hihi" • Specifies the pattern (expr1). Using the /max-count parameter (gdb) find /1 &int8_search_buf[0], +sizeof(int8_search_buf), 'a', 'a', 'a' where: • /1 Specifies the find command to display only one matching pattern. &int8_search_buf[0] Specifies the starting address. +sizeof(int8_search_buf) Specifies the ending address. 'a', 'a', 'a' Specifies the pattern (expr1, expr2, expr3).
The packcore.tar.Z file can be copied to a different system and the gdb command unpackcore unpacks the packcore.tar.Z file in the current directory, creating a new packcore directory. After unpacking the packcore file, the unpackcore command invokes getcore to load the executable and the core file from the packcore directory, and sets GDB_SHLIB_PATH to the modules directory in the packcore directory. The modules directory holds all of the shared libraries that were used when the core file was generated.
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.
This command displays run time type information for C++ polymorphic object. The input to this command is address of the C++ polymorphic object. GDB displays the demangled type name as output. NOTE: This command is supported only on Integrity systems. Sample Output (gdb) info rtti
RTTI: 14.15.5 Support for Core File Debugging of MITR Applications HP WDB 6.0 and later versions support corefile debugging for MIxed mode TRanslator (MITR) applications.14.15.5.3 Change in the Behavior of Existing Commands Following is the change in behavior of existing commands when a corefile created by a mixed mode application is debugged and if the set debug-aries option is set to off: bt n Includes PA-RISC frames in the backtrace, if applicable. frame n Sets the frame to a PA-RISC frame if n represents a PA-RISC frame according to the backtrace command. Otherwise, the appropriate Itanium frame is displayed.
Following are known issues in mixed mode debugging: • Listing of registers currently in use for PA-RISC 32-bit shared library frames causes the unswizzled 32-bit values to be displayed. • Clicking on the registers tab for a PA-RISC frame in the HP WDB-GUI results in incorrect register information being displayed. Alternatively, execute the info reg command at the gdb prompt in the Commands tab.
assert( r != (void *)-1 ); s = mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0); assert( s != (void *)-1 ); t = mmap(NULL, 4096, PROT_READ, MAP_SHARED, fd, 0); assert( t != (void *)-1 ); fd2 = open("testfile2", O_RDWR); if ( fd2 == -1 ) { perror("open"); return -1; } u = mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_SHARED, fd2, 0); if (u == MAP_FAILED) printf("PROT_READ|PROT_WRITE, MAP_SHARED failed, errno = %d\n", errno); else assert( u != (void *)-1 ); printf("p %p q %p r %p s %p t %p u %p\n", p,
... 0x200000007aada000 - 0x200000007aada0e1 is segment24 (Added with mmapfile) ... Next, add regions pointed to by t and u. (gdb) p t $9 = 0x60000000c1a91000
(gdb) mmapfile testfile 0x60000000c1a91000 0 0xe1 (gdb) p t $10 = 0x60000000c1a91000 "#include \n#include \nint main(){\n foo();\n bar();\n return 0;\n}\nint foo(){\n int * res = malloc(4);\n printf(\"*res %d\\n\", *res);\n return 1;\n}\nint bar(){\n printf(\"Hel"...• For generating a side debug file which is contained in ELF32 image, use the linker option +dbgfile side_file_name, where, the side_file_name is the file name of the side debug file. For generating a side debug file which is in ELF64 binary, use the linker option +dbgfile-large side_file_name. You can use this option even when the actual executable is in ELF32 container. • Invoke gdb on the executable to start debugging the application.
If [start_index] and [end_index] are not specified, the complete table of execution path entries is displayed. • info global-exec-path summary Prints the summary information about all the global execution path entries in the current frame. This command displays the total number of global execution path entries that can be stored, the number of global execution path entries in this frame in the last iteration, and the last executed global execution path number.
(gdb) r Starting program: a.out Breakpoint 1, main () at execpath.c:7 7 int a = 3, b = 0, c = 4; (gdb) n 9 if (a) (gdb) i ep Local execution path table for main(): empty (gdb) i gep Global execution path table: empty (gdb) n 10 printf("Value of a greater than 0\n"); (gdb) n Value of a greater than 0 12 if (b) (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.
where: on Enables HP WDB to unwind beyond 10000 frames. off Disables the limitation on the number of frames. 14.19 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.
14.21 Instruction Level Stepping During instruction level stepping with nexti and stepi, HP WDB prints the assembly instruction along with the next source line. (gdb) stepi 0x101530:0 st4 [r9]=r34 1337 args.argc = argc; It also prints DOC line information, which includes actual line number and the column number, when debugging a binary with -g -O. (gdb) stepi ;;; [8, 1] 0x4000820:1 nop.m 0x0 GDB cannot step into a function with no debug information.
14.22.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. In addition, you can specify a set of commands to be performed when the breakpoint is reached. These breakpoints work like procedural breakpoints in the xdb debugger. The breakpoint commands are rbp and rdp.
14.23.1 Using shared library as main program If the main program is in a shared library and you try to load it as follows: (gdb) symbol-file main.sl Load new symbol table from "main.sl"? (y or n) y Reading symbols from main.sl done. Things don't appear to work. This command is not the correct thing to do. This command assumes that main.sl is loaded at its link time address. This is not true for shared libraries. Do not use symbol-file with shared libraries.
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.
14.23.7 Enhancement to the info shared Command HP WDB 6.0 and later versions provide the enhanced info shared command to display the global pointer (gp) values along with text start, text end, data start, and data end values of the shared library. Following is a sample output of the info shared command with the gp values: tstart tend dstart dend gp /usr/lib/hpux32/dld.so 0x2000000065858000 0x20000000658fb080 0x2000000065853000 0x2000000065857a38 0x2000000065855720 /usr/lib/hpux32/libstd_v2.so.
14.24.3 Evaluating Decimal Floating Point data types HP WDB versions 5.9 and above enable you to evaluate the decimal floating point variable and displays the output. Use the commonly used GDB commands for evaluating and displaying expressions, such as print to evaluate the decimal floating point variable. HP WDB supports: • Evaluation of expressions with decimal floating point constants and variables. • Setting or assignment of decimal floating point constant or variable.
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.2dd / 0 (gdb) inf HP WDB handles finite, infinite and NaN(Not a Number) values of decimal floating point data type.
systems is shown following. The examples are for SDK 1.4; if you are using JDK 1.5, substitute /opt/java1.5 for /opt/java1.4. • For 32 bit IPF applications, export GDB_JAVA_UNWINDLIB = /opt/java1.4/jre/lib/IA64N/server/libjunwind.so • For 64 bit IPF applications, export GDB_JAVA_UNWINDLIB = /opt/java1.4/jre/lib/IA64W/server/libjunwind.so • For 32 bit PA applications, export GDB_JAVA_UNWINDLIB = /opt/java1.4/jre/lib/PA_RISC/server/libjunwind.
14.26.1.2 gdb Subcommands for Java VM Debugging Commands for Examining Java Virtual Machine(JVM) internals To view the gdb commands that support Java VM debugging, type help java at the gdb prompt. (gdb) help java Java and JVM debugging commands.
14.26.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.
NOTE: If the version of gdb on the system is older than version 4.5, it will be necessary to specify the full path of the Java executable in order to use the gdb subcommands. For example: gdb / opt/java1.4/bin/PA_RISC2.0/java p 23989 14.26.2 Enhanced support for C++ templates This version of HP WDB includes these features to support C++ templates: • Setting breakpoints in template class functions and template functions without having to specify details about the instantiation.
where, A and B are ordinary numeric expressions, perhaps in parentheses. This is also the format in which the debugger displays a Complex value. Imaginary values cannot be assigned to variables because there is no imaginary data type. You can take a normal number and multiply it by an imaginary number and get another imaginary number. You can take a normal number and add it to an imaginary number to get a complex number. Complex numbers cannot be used in arithmetic expressions in the debugger.
print /W 14.28 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.
14.28.3 Displaying enumerators You can display the union of several enumeration elements by specifying a value if the elements of the enumeration type are the powers of 2 and the given value is a sum of any given combination of the enumeration elements. For example, assume you have an enumerated type named color in the program, with these elements: RED=0, ORANGE=1, YELLOW=2, GREEN=8, and BLUE=16. If you use the command printf 3, the debugger displays ORANGE|YELLOW, the elements corresponding to 1 and 2.
Debug foo(), use the finish command to exit from the first top-level call, (foo()), execute the steplast command to step into the next top-level call, (bar()). The following example illustrates the use of steplast command: (gdb)10 foo( bar() ) + bar( foo() ) (gdb) sl Use the steplast (sl) command to step 14.29 Getting information from a non-debug executable You can get some information about the arguments passed to the functions displayed in the stack trace in a non-debug, optimized executable.
• frame • info * • next • step • tbreak • rbreak • up The following commands are not affected by the optimization level of the program being debugged: • 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 •
• unset env • until 14.30.1 Debugging Optimized Code at Various Optimization Levels The following sections describe debugging optimized code support at each optimization level. 14.30.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).
to stop at the instructions irrespective of the predicate value of these instructions, can explicitly turn o this feature. To explicitly turn o this feature, enter the following command at the gdb prompt: (gdb) set no-predication-handling The following limitations apply when debugging optimized code: • Support for high-level loop transformations such as modulo-scheduled loops, or LNO-optimized loop nests is limited.
3. The rest of the debugging operations are the same as that on the HP 9000 HP-UX platform. NOTE: Make sure that the user has write permission on /tmp directory and that there is enough space to create a temporary file of one page size as obtained by sysconf(_SC_PAGE_SIZE) system call. 14.31.1.1 Limitations of GDB Support under ARIES • No support for debuggers other than HP 9000 HP-UX GDB for debugging HP 9000 applications under ARIES on HP-UX 11i Integrity servers.
14.32 Visual Interface for HP WDB HP WDB includes an HP-supported Visual Interface for HP WDB with both graphical and terminal modes. The interface is based on Vim 5.7 and HP 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 HP WDB display. Most of Visual Interface for HP WDB functionality is also available for emacs users.
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. • The up and down arrow keys move the cursor in the source window. • Holding the shift key down while using the up and down arrow keys move the cursor in the debugger window.
14.32.4 Using the X-window graphical interface To start Visual Interface for HP WDB in graphical mode with mouse support, run Visual Interface for HP WDB with the command: /opt/langtools/bin/vdb Visual Interface for HP WDB opens an `hpterm' window, ignoring the value of the TERM environment variable, for debugging a program. With a mouse you can do the following: • Left-click the line number to insert or remove breakpoints.
Mouse operations are not supported in the -tui mode. Also the paging and shift keys do not work well with VT100. 14.32.6 Changing the size of the source or debugger pane 1. 2. Escape to vi command mode first. Drag the status bar using the mouse. If you are using -tui mode, use these commands to change the size of the current window: CTRL-W + to increase CTRL-W to decrease In Visual Interface for HP WDB, the current window is usually the debugger window. 14.32.
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.33 Support for ddd GDB works with ddd, the free GDB GUI shell available at http://mumm.ibr.cs.tu-bs.de/.
14.36 Support for command line calls in a stripped executable HP WDB enables you to perform command line calls in a stripped executable. 14.36.1 Support for command line calls in a stripped executable on PA-RISC systems In HP 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.36.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.36.3 Support for debugging stripped binaries HP WDB provides limited support for debugging stripped binaries. 14.36.
14.38 Linux support Linux Runtime Environment (LRE) on HP-UX Itanium enables users to execute Intel Itanium Linux applications on HP-UX. HP WDB provides a prototype for LRE debugging, which allows you to debug applications ported from Linux that run under LRE. This provides a minimal debugging capability for LRE. 14.39 Source level debugging GDB provides support for source level debugging with the help of the following command.
Example 2 Sample Commands to Print CFM and PFS registers Use the following command to print the PFS or ar64 register: (gdb) info reg ar64 pfs: 0xc000000000000c20 (sor:0, sol:24, sof:32) In the above example, 0xc000000000000c20 is the raw value and (sor:0, sol:24, sof:32) is the format for identifying rotating registers, frames and locals.
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 HP WDB Transition Guide” (page 203). 15.1 Starting the TUI Invoke the debugger using a command like the following: gdb -xdb -tui a.
|29 int main(void) | |30 { | |31 /* Try two test cases. */ | *>|32 print_average (my_list, first, last); | |33 print_average (my_list, first, last - 3); | |34 } | |35 | |36 | |37 | |38 | |39 | |----------------------------------------------------------------------| File: average.c Procedure: main Line: 32 pc: 0x3524 .. (gdb) b main Breakpoint 1 at 0x3524: file average.c, line 32. (gdb) run Starting program: /home/work/wdb/a.out Breakpoint 1, main () at average.c:32 (gdb) 15.
15.3.
Breakpoint 1, main () at average.c:32 (gdb) la asm (gdb) la split (gdb) 15.3.4 Disassembly/Register pane The Disassembly/Register pane appears when you issue the command la regs when the current pane is the Source/Disassembly pane. By default, the debugger displays the general registers. The window looks like this: :.........................................................................
|37 | |----------------------------------------------------------------------| File: average.c Procedure: main Line: 32 pc: 0x3524 Breakpoint 1, main () at average.c:32 (gdb) la asm (gdb) la split (gdb) la regs (gdb) la src (gdb) la regs (gdb) 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.
:.........................................................................: :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 : :.........................................................................
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. Use num_lines to specify how many lines to scroll the pane. Use win_name to specify a pane other than the one with logical focus.
|-------------------------------------------------------------------------| |fpsr 0 fpe1 0 | |fpe2 0 fpe3 0 | |fpe4 0 fpe5 0 | |fpe6 0 fpe7 0 | |fr4 0 fr4R 0 | |fr5 1.0000000000000011 fr5R 7.00649232e-45 | |-------------------------------------------------------------------------| *>:32 print_average (my_list, first, last); : :33 print_average (my_list, first, last - 3); : :34 } : :35 : :36 : :37 : :......................................................................: File: average.
If you use stack-navigation commands such as up, down, and frame to change your source location, and you want to return the display to the current point of execution, use the update command (upd): upd 15.
16 XDB to HP WDB Transition Guide This transition aid is designed for XDB users who are learning HP WDB, an HP-supported version of the industry-standard GDB debugger. Select one of these lists for a table that shows HP WDB equivalents for many common XDB commands and other features. Invoke HP 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.
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 5 File viewing commands XDB Command HP WDB Equivalent Meaning {+ | -}[number] {+ | -}[ number] (with -tui; Move view location forward or backward in source file number lines note that a space is required between + or - and the number) /[string] /[string] (with -xdb), search regexp, forw regexp Search source forward for [last] string ?[string] ?[string] (with -xdb), rev regexp Search source backward for [last] string D "dir" D "dir" (with -xdb), dir pathname Add a directory search path for
Table 6 Data viewing and modification commands XDB Command HP WDB Equivalent Meaning Move view location forward or backward in source file number lines l l (with -xdb), info args followed by info locals lc [string] lc [string] (with -xdb), info Search source forward for [last] string common string lg [string] lg [string] (with -xdb), info Search source backward for [last] string variables [string] ll [string] info functions [string], info variables [string], maint print msymbols file Add a direct
Table 6 Data viewing and modification commands (continued) XDB Command HP WDB Equivalent Meaning pq class:: No equivalent Evaluate static members of class pq {+ | -}[\format No equivalent Evaluate next/previous memory location using format 16.1.6 Stack viewing commands The GDB concept of the top and bottom of the stack is the opposite of XDB, so the XDB up is GDB down.
Table 9 Job control commands XDB Command HP WDB Equivalent Meaning c c, continue Continue from breakpoint, ignoring any pending signal c location until location Continue from breakpoint, ignoring any pending signal, set temporary breakpoint at location C c, continue Continue, allowing any pending signal C [location] until location Continue, allowing any pending signal, set temporary breakpoint at location g line g line (with -xdb), go line, Go to line in current procedure tb line followed by
Table 11 Auxillary breakpoint commands XDB Command HP WDB Equivalent Meaning Print any string any_string p "any string" if expr {cmds} [{cmds}] if expr cmds [else cmds] end Conditionally execute cmds Q Q (with -xdb), silent (must be Quiet breakpoints 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 12 Breakpoint creation commands (continued) XDB Command HP WDB Equivalent Meaning bu [depth] bu [depth] (with -xdb). The Set up-level breakpoint. finish command is equivalent to the sequence bu, c, db (to continue out of the current routine). bx [depth] bx [depth] (with -xdb) Set a breakpoint at procedure exit. 16.2.
Table 14 Global breakpoint commands XDB Command HP WDB Equivalent Meaning abc cmds No exact equivalent, but display expr is equivalent to abc print expr Set or delete cmds to execute at every stop dbc undisplay Stop displaying values at each stop 16.2.6 Assertion control commands GDB does not provide the ability to trace by instruction. Watchpoints, however, provide similar functionality to xdb assertions.
Table 15 Macro facility commands XDB Command HP 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 17 Miscellaneous commands (continued) XDB Command HP WDB Equivalent Meaning M[{t | c} [expr[; expr...]]] No equivalent Print object or corefile map q q Quit debugger sm sm (with -xdb), set height 0 Suspend more (turn o pagination) ss file No equivalent Save (breakpoint, macro, assertion) state tc No equivalent Toggle case sensitivity in searches 16.
Table 18 Data format commands (continued) XDB Command HP WDB Equivalent Meaning s No equivalent String S No equivalent Formatted structure display t whatis, ptype Show type of the expression T (1) ptype Show type of expression, including base class information u u Expression in unsigned decimal format U (1) u Expression in long unsigned decimal format w No equivalent Wide character string W (1) No equivalent Address of wide character string x x Print in hexadecimal X (1) x Pr
Table 20 Special language operators XDB Language Operator HP 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.
Table 22 Variable Identifiers (continued) XDB Variable Identifier HP WDB Equivalent Meaning . (dot) Empty string; for example, p is the equivalent of p . Shorthand for last thing you looked at :var or ::var ::var to distinguish a global from a local variable with same name Search for global variable only 16.
Table 24 B (continued) XDB Command Equivalent HP WDB Command bb [depth] No equivalent (use b proc) bc number expr bc number expr (with -xdb), ignore number expr (within a commands list) bi expr.
Table 25 C through D (continued) XDB Command Equivalent HP WDB Command down up down number up number dp No equivalent dpm index No equivalent dpm * No equivalent Dpt No equivalent Dpx No equivalent 16.8.
Table 27 L (continued) XDB Command Equivalent HP WDB Command ll [string] info functions [string], info variables [string], maint print msymbols file lm [string] show user [string] lo [[class]::][string] info func [[class]::][string] lp info functions lp [[class]::]string info func [[class]::]string info addr [[class]::]string lpm No equivalent lr lr (with -xdb), info all-reg lr string lr string (with -xdb), info reg string ls [string] No equivalent lz lz (with -xdb), info signals 16.8.
16.8.
16.8.
Table 32 Symbols (continued) XDB Command Equivalent HP WDB Command [class]::proc [class]::proc [class]::proc[:line] No equivalent [class]::proc[#label] No equivalent proc#line No equivalent name@shared-library No equivalent var var class::var class::var (bug: not yet) [[class]::]proc:[class::]var proc::var (static variables only) [[class]::]proc:depth:[class::]var No equivalent Return Return "any string" p "any string" . (dot) Empty string; for example, p is the equivalent of p .
Table 32 Symbols (continued) XDB Command Equivalent HP 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 68). 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.
.gdb_history (./_gdb_history on MS-DOS) if this variable is not set. set history save, set history save on Record command history in a file, whose name may be specified with the set history filename command. By default, this option is disabled. set history save off Stop recording command history in a file. set history size size Set the number of commands which GDB keeps in its history list. This defaults to the value of the environment variable HISTSIZE, or to 256 if this variable is not set.
set pagination on/off, show pagination Turn the output pagination on or off; the default is on. You can also turn off pagination to set height 0. 17.5 Supported Number Formats You can always enter numbers in octal, decimal, or hexadecimal in GDB by the usual conventions: octal numbers begin with `0', decimal numbers end with `.', and hexadecimal numbers begin with `0x'.
set confirm off Disables confirmation requests. set confirm on Enables confirmation requests (the default). show confirm Displays state of confirmation requests. 17.7 Optional messages about internal happenings set debug arch Turns on or off display of gdbarch debugging info. 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.
18 Canned Sequences of Commands In addition to breakpoint commands (see “Breakpoint command lists” (page 46)), 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.
You may use the document command again to change the documentation of a command. Redefining the command with define does not change the documentation. help user-defined List all user-defined commands, with the first line of the documentation (if any) for each. show user, show user commandname Display the GDB commands used to define commandname (but not its documentation). If no commandname is given, display the definitions for all user- defined commands.
5. Read command files specified by the `-x' option. The init file in your home directory can set options (such as `set complaints') that affect subsequent processing of command line options and operands. Init files are not executed if you use the `-nx' option (see “Choosing modes” (page 22)). It can be useful to create a `.gdbinit' file in the directory where you are debugging an application. This file will set the actions that apply for this application.
output expression Print the value of expression and nothing but that value: no newlines, no `$nn = '. The value is not entered in the value history either. See “Expressions” (page 63). output/fmt expression Print the value of expression in format fmt. You can use the same formats as for print. See “Output formats” (page 65). 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.
M-x gdb-nexti Execute to next instruction, using the GDB nexti command; update display window accordingly. C-c C-f Execute until exit from the selected stack frame, like the GDB finish command. M-c Continue execution of your program, like the GDB continue command. WARNING! M-u Go up the number of frames indicated by the numeric argument (see section "Numeric Arguments" in The gnu Emacs Manual), like the GDB up command. WARNING! M-d In Emacs v19, this command is C-c C-u.
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.
the-value ^Z^Zvalue-history-end where history-number is the number it is getting in the value history, history-string is a string, such as $5 = , which introduces the value to the user, the-value is the output corresponding to the value itself, and value- flags is `*' for a value which can be dereferenced and `-' for a value which cannot.
20.4 Frames Whenever GDB prints a frame, it annotates it. For example, this applies to frames printed when GDB stops, output from commands such as backtrace or up, etc. The frame annotation begins with: ^Z^Zframe-begin level address level-string where level is the number of the frame (0 is the innermost frame, and other frames have positive numbers), address is the address of the code executing in that frame, and level-string is a string designed to convey the level to the user.
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.
query When GDB wants the user to confirm a potentially dangerous operation. prompt-for-continue When GDB is asking the user to press return to continue. Note: Don't expect this to work well; instead use set height 0 to disable prompting. This is because the counting of lines is buggy in the presence of annotations. 20.7 Errors ^Z^Zquit This annotation occurs right before GDB responds to an interrupt. ^Z^Zerror This annotation occurs right before GDB responds to an error.
The output ends with: ^Z^Zbreakpoints-table-end 20.9 Invalidation notices The following annotations say that certain pieces of state may have changed: ^Z^Zframes-invalid The frames (for example, output from the backtrace command) may have changed. ^Z^Zbreakpoints-invalid The breakpoints may have changed. For example, the user just added or deleted a breakpoint. 20.10 Running the program When the program starts executing due to a GDB command such as step or continue, ^Z^Zstarting is output.
source which is being displayed. addr is in the form `0x' followed by one or more lowercase hex digits (note that this does not depend on the language). 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).
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.
Pragmatics: • We want easy access to the existing CLI syntax (for debugging). • We want it to be easy to spot a MI operation. 21.1.2 GDB/MI Output syntax The output from GDB/MI consists of zero or more out-of-band records followed, optionally, by a single result record. This result record is for the most recent command. The sequence of output records is terminated by '(gdb)'.
• status-async-output contains on-going status information about the progress of a slow operation. It can be discarded. All status output is prefixed by '+'. • exec-async-output contains asynchronous state change on the target (stopped, started, disappeared). All async output is prefixed by '*'. • notify-async-output contains supplementary information that the client should handle (for example, a new breakpoint information). All notify output is prefixed by '='.
GDB/MI behaviour, the exact output of such commands is likely to end up being an un-supported hybrid of GDB/MI and CLI output. 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.
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. Result Out-of-band Notes Example 21.5 GDB/MI breakpoint table commands This section documents GDB/MI commands for manipulating breakpoints. The -break-after Command Synopsis -break-after number count The breakpoint number number is not in effect until it has been hit count times.
ignore="3"}]} (gdb) The -break-condition command Synopsis -break-condition number expr Breakpoint number will stop the program only if the condition in expr is true. The condition becomes part of the '-break-list' output (see the description of the '-break-list' command below). GDB command The corresponding GDB command is 'condition'.
body=[]} (gdb) The -break-disable command Synopsis -break-disable ( breakpoint )+ Disable the named breakpoint(s). The field 'enabled' in the break list is now set to 'n' for the named breakpoint(s). GDB command The corresponding GDB command is 'disable'.
The -break-info Command Synopsis -break-info breakpoint Get information about a single breakpoint. GDB command The corresponding GDB command is 'info break breakpoint'. Example N.A.
^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.
Here is an example of the result when there are no breakpoints: (gdb) -break-list ^done,BreakpointTable={nr_rows="0",nr_cols="6", hdr=[{width="3",alignment="-1",col_name="number",colhdr="Num"}, {width="14",alignment="-1",col_name="type",colhdr="Type"}, {width="4",alignment="-1",col_name="disp",colhdr="Disp"}, {width="3",alignment="-1",col_name="enabled",colhdr="Enb"}, {width="10",alignment="-1",col_name="addr",colhdr="Address"}, {width="40",alignment="2",col_name="what",colhdr="What"}], body=[]} (gdb) The
Listing breakpoints and watchpoints, at different points in the program execution. Note that once the watchpoint goes out of scope, it is deleted.
specified as a non-zero value, and lines is lower than the number of disassembly lines between start-addr and end-addr, only lines lines are displayed; if lines is higher than the number of lines between start-addr and end-addr, only the lines up to end-addr are displayed. 'mode' is either 0 (meaning only disassembly) or 1 (meaning mixed source and disassembly).
inst="save %sp, -112, %sp"}, {address="0x000107c0",func-name="main",offset="4", inst="mov 2, %o0"}, {address="0x000107c4",func-name="main",offset="8", inst="sethi %hi(0x11800), %o2"}] (gdb) Disassemble 3 instructions from the start of main in mixed mode: (gdb) -data-disassemble -f basics.c -l 32 -n 3 -- 1 ^done,asm_insns=[ src_and_asm_line={line="31", file="/kwikemart/marge/ezannoni/flathead-dev/devo/gdb/ \ testsuite/gdb.mi/basics.
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.
Display the registers contents. fmt is the format according to which the registers' contents are to be returned, followed by an optional list of numbers specifying the registers to display. A missing list of numbers indicates that the contents of all the registers must be returned. Allowed formats for fmt are: x Hexadecimal o Octal t Binary d Decimal r Raw N Natural GDB command The corresponding GDB commands are 'info reg', 'info all-reg', and (in gdbtk) 'gdb_fetch_registers'.
{number="65",value="0x29002"},{number="66",value="0x202f04b5"}, {number="67",value="0xfe0043b0"},{number="68",value="0xfe00b3e4"}, {number="69",value="0x20002b03"}] (gdb) The -data-read-memory command Synopsis -data-read-memory [ -o byte-offset ] address word-format word-size nr-rows nr-cols [ aschar ] where: 'address' An expression specifying the address of the first memory word to be read. Complex expressions containing embedded white space should be quoted using the C convention.
5^done,addr="0x00001510",nr-bytes="2",total-bytes="2", next-row="0x00001512",prev-row="0x0000150e", next-page="0x00001512",prev-page="0x0000150e",memory=[ {addr="0x00001510",data=["128"]}] (gdb) Read thirty two bytes of memory starting at bytes+16 and format as eight rows of four columns. Include a string encoding with 'x' used as the non-printable character.
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'. Example N.A.
Add directory pathdir to the beginning of search path for source files. GDB command The corresponding GDB command is 'dir'. Example (gdb) -environment-directory /kwikemart/marge/ezannoni/flathead-dev/devo/gdb ^done (gdb) The -environment-path command Synopsis -environment-path ( pathdir )+ Add directories pathdir to beginning of search path for object files. GDB command The corresponding GDB command is 'path'.
(gdb) x = 55 *stopped,reason="exited-normally" (gdb) Program exited exceptionally: (gdb) -exec-run ^running (gdb) x = 55 *stopped,reason="exited",exit-code="01" (gdb) Another way the program can terminate is if it receives a signal such as SIGINT. In this case, GDB/MI displays this: (gdb) *stopped,reason="exited-signalled",signal-name="SIGINT", signal-meaning="Interrupt" The -exec-abort command Synopsis -exec-abort Kill the inferior running program. GDB command The corresponding GDB command is 'kill'.
Example -exec-continue ^running (gdb) @Hello world *stopped,reason="breakpoint-hit",bkptno="2",thread-id="1",frame=addr="0x000029d8", func="foo",args=[],file="hello.c",line="16"file="hello.c",line="13"} (gdb) 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.
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.
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 call1 ^done,bkpt=number="1",type="breakpoint",disp="keep",enabled="y",addr="0x000029ac", func="call1",file="hello.
GDB command The corresponding GDB command is 'show args'. Example N.A. The -exec-step Command Synopsis -exec-step Asynchronous command. Resumes execution of the inferior program, stopping when the beginning of the next source line is reached, if the next source line is not a function call. If it is, stop at the first instruction of the called function. GDB command The corresponding GDB command is 'step'.
~"2" ~"3" *stopped,reason="end-stepping-range",thread-id="1",frame=addr="0x000029dc", func="call",args=[name="a",name="b"],file="hello.c",line="16" (gdb) -exec-step-instruction ^running (gdb) *stopped,reason="end-stepping-range", frame={addr="0x000100f4",func="foo",args=[],file="try.c",line="10"} (gdb) The -exec-until command Synopsis -exec-until [ location ] Asynchronous command. Executes the inferior until the location specified in the argument is reached.
The -file-exec-file command Synopsis -file-exec-file file Specify the executable file to be debugged. Unlike '-file-exec-and-symbols', the symbol table is not read from this file. If used without argument, GDB clears the information about the executable file. No output is produced, except a completion notification. GDB command The corresponding GDB command is 'exec-file'. Example (gdb) -file-exec-file /kwikemart/marge/ezannoni/TRUNK/mbx/hello.
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.
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'. Example (gdb) -gdb-show annotate ^done,value="0" (gdb) The -gdb-version command Synopsis -gdb-version Show version information for GDB. Used mostly in testing.
^done (gdb) 21.9 GDB/MI Stack Manipulation Commands The -stack-info-frame command Synopsis -stack-info-frame Get info on the current frame. GDB command The corresponding GDB command is 'info frame' or 'frame' (without arguments). Example N.A. The -stack-info-depth command Synopsis -stack-info-depth [ max-depth ] Return the depth of the stack. If the integer argument max-depth is specified, do not count beyond max-depth frames. GDB command There is no equivalent GDB command.
The show-values argument must have a value of 0 or 1. A value of 0 means that only the names of the arguments are listed, a value of 1 means that both names and values of the arguments are printed. GDB command GDB does not have an equivalent command. gdbtk has a 'gdb_get_args' command which partially overlaps with the functionality of '-stack-list-arguments'. Example (gdb) -stack-list-frames ^done, stack=[ frame={level="0 ",addr="0x00010734",func="callee4", file="../../../devo/gdb/testsuite/gdb.mi/basics.
List the frames currently on the stack. For each frame it displays the following info: 'level' The frame number, 0 being the topmost frame, that is the innermost function. 'addr' The $pc value for that frame. 'func' Function name. 'file' File name of the source file where the function lives. 'line' Line number corresponding to the $pc. If invoked without arguments, this command prints a backtrace for the whole stack.
(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.
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. GDB command 'gdb_get_function' in gdbtk. Example N.A. The -symbol-info-line command Synopsis -symbol-info-line Show the core addresses of the code for a source line.
Example N.A. The -symbol-list-functions command Synopsis -symbol-list-functions List the functions in the executable. GDB command 'info functions' in GDB, 'gdb_listfunc' and 'gdb_search' in gdbtk. Example N.A. The -symbol-list-types command Synopsis -symbol-list-types List all the type names. GDB command The corresponding commands are 'info types' in GDB, 'gdb_search' in gdbtk. Example N.A.
Example N.A. The -symbol-type command Synopsis -symbol-type variable Show type of variable. GDB command The corresponding GDB command is 'ptype', gdbtk has 'gdb_obj_variable'. Example N.A. 21.11 GDB/MI Target Manipulation Commands The -target-attach command Synopsis -target-attach pid | file Attach to a process pid or a file file outside of GDB. GDB command The corresponding GDB command is 'attach'. Example N.A.
GDB command The corresponding GDB command is 'detach'. 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.
+download,{section=".text",section-sent="4096",section-size="6668", total-sent="4096",total-size="9880"} +download,{section=".text",section-sent="4608",section-size="6668", total-sent="4608",total-size="9880"} +download,{section=".text",section-sent="5120",section-size="6668", total-sent="5120",total-size="9880"} +download,{section=".text",section-sent="5632",section-size="6668", total-sent="5632",total-size="9880"} +download,{section=".
The -target-list-current-targets command Synopsis -target-list-current-targets Describe the current target. GDB command The corresponding information is printed by 'info file' (among other things). Example N.A. The -target-list-parameters command Synopsis -target-list-parameters GDB command No equivalent. Example N.A. The -target-select command Synopsis -target-select type parameters ... Connect GDB to the remote target.
21.12 GDB/MI thread commands The -thread-info command Synopsis -thread-info GDB command No equivalent. Example N.A. The -thread-list-all-threads command Synopsis -thread-list-all-threads GDB command The equivalent GDB command is 'info threads'. Example N.A. The -thread-list-ids command Synopsis -thread-list-ids Produces a list of the currently known GDB thread ids. At the end of the list it also prints the total number of such threads.
The -thread-select command Synopsis -thread-select threadnum Make threadnum the current thread. It prints the number of the new current thread, and the topmost frame for that thread. GDB command The corresponding GDB command is 'thread'. Example (gdb) -exec-next ^running (gdb) ~"0x7f7f0aec" *stopped,reason="end-stepping-range",thread-id="2",frame=addr="0x00002ca4",func ="printme",args=[name="ip"],file="multithread.
Furthermore, complex data types, such as C structures, are represented in a tree format. For instance, the struct type variable is the root and the children will represent the struct members. If a child is itself of a complex type, it will also have children of its own. Appropriate language differences are handled for C, C++ and Java. When returning the actual values of the objects, this facility allows for the individual selection of the display format used in the result creation.
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.
The -var-info-type command Synopsis -var-info-type name Returns the type of the specified variable name. The type is returned as a string in the same format as it is output by the GDB CLI: type=typename The -var-info-expression command Synopsis -var-info-expression name Returns what is represented by the variable object name: lang=lang-spec,exp=expression where lang-spec is {"C" | "C++" | "Java"}.
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.
• The version of GDB. GDB announces it if you start with no arguments; you can also print it at any time using show version. Without this, we will not know whether there is any point in looking for the bug in the current version of GDB. • The type of machine you are using, and the operating system name and version number. • What compiler (and its version) was used to compile the program you are debugging| e.g. \HP92453-01 A.10.32.03 HP C Compiler".
And if we cannot understand what bug you are trying to x, or why your patch should be an improvement, we will not install it. A test case will help us to understand. • A guess about what the bug is or what it depends on. Such guesses are usually wrong. Even we cannot guess right about such things without first using the debugger to find the facts. 22.
A Installing GDB If you obtain GDB (HP 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 (HP 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.
Running configure host and then running make builds the `bfd', `readline', `mmalloc', and `libiberty' libraries, then gdb itself. The configured source files, and the binaries, are left in the corresponding source directories.
When you have multiple hosts or targets configured in separate directories, you can run make on them in parallel (for example, if they are NFS-mounted on each of the hosts); they will not interfere with each other. A.2 Specifying names for hosts and targets The specifications used for hosts and targets in the configure script are based on a three-part naming scheme, but some short predefined aliases are also supported.
--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.