Debugging with GDB Manual The GNU Source-Level Debugger HP Part Number: 769148-001 Published: March 2014 Edition: 24
© Copyright 2014 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 HP secure development lifecycle....................................................................11 Summary of GDB........................................................................................12 Free Software.........................................................................................................................12 Contributors to GDB................................................................................................................12 1 A Sample GDB Session..
Signals..................................................................................................................................47 Stopping and starting multi-thread programs..............................................................................48 6 Examining the Stack.................................................................................50 Stack frames..........................................................................................................................
10 Examining the Symbol Table....................................................................81 11 Altering Execution...................................................................................84 Assignment to variables...........................................................................................................84 Continuing at a different address..............................................................................................85 Giving your program a signal..............
Support for Memory debugging from Core File....................................................................126 Memory debugging without prior preparation.....................................................................126 Open-files reporting.........................................................................................................126 Configuring memory debugging settings.............................................................................127 Specifying the stack depth.........
Command and Features Applicable to PA-RISC Libraries...................................................150 Known Issues and Unsupported Features in Mixed Mode Debugging.................................150 Support for mmapfile command.........................................................................................151 Debugging with debug information available in the side debug file............................................153 Printing the Execution Path Entries for the Current Frame or Thread......
Debugging optimized code....................................................................................................172 Debugging Optimized Code at Various Optimization Levels..................................................173 +O0 and +O1...........................................................................................................174 +O2/+O3/+O4/-ipo.................................................................................................174 Debugging with ARIES................
Changing the register display................................................................................................192 Changing the pane size........................................................................................................193 Refreshing and updating the window......................................................................................193 16 XDB to HP WDB Transition Guide...........................................................
Commands for controlled output.............................................................................................222 19 Using GDB under gnu Emacs.................................................................224 20 GDB Annotations.................................................................................226 What is an annotation?.........................................................................................................226 The server prefix....................................
HP secure development lifecycle Starting with HP-UX 11i v3 March 2013 update release, HP secure development lifecycle provides the ability to authenticate HP-UX software. Software delivered through this release has been digitally signed using HP's private key. You can now verify the authenticity of the software before installing the products, delivered through this release. To verify the software signatures in signed depot, the following products must be installed on your system: • B.11.31.
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.
David Johnson wrote the original COFF support; Pace Willison did the original support for encapsulated COFF. Brent Benson of Harris Computer Systems contributed DWARF 2 support. Adam de Boor and Bradley Davis contributed the ISI Optimum V support. Per Bothner, Noboyuki Hikichi, and Alessandro Forin contributed MIPS support. Jean-Daniel Fekete contributed Sun 386i support. Chris Hanson improved the HP 9000 support. Noboyuki Hikichi and Tomoyuki Hasei contributed Sony/News OS 3 support.
Dawn Perchik, Rich Pixley, Zdenek Radouch, Keith Seitz, Stan Shebs, David Taylor, and Elena Zannoni.
1 A Sample GDB Session This chapter describes the most common GDB commands with the help of an example.
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. Setting Breakpoints Here we describe how to set a breakpoint. ((gdb)) break m4 changequote Breakpoint 1 at 0x62f4: file builtin.c, line 879.
#1 0x6344 in m4_changequote (argc=3, argv=0x33c70) at builtin.c:882 #2 0x8174 in expand_macro (sym=0x33320) at macro.c:242 #3 0x7a88 in expand_token (obs=0x0, t=209696, td=0xf7fffa30) at macro.c:71 #4 0x79dc in expand_input () at macro.c:40 #5 0x2930 in main (argc=0, argv=0xf7fffb20) at m4.c:195 We step through a few more lines to see what happens. The first two times, we can use 's'; the next two times we use n to avoid falling into the xstrdup subroutine.
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. 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 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). Command syntax • A GDB command is a single line of input. There is no limit on how long it can be.
((gdb)) b make_TAB GDB sounds bell; press TAB again, to see: make_a_section_from_file make_environ make_abs_section make_function_type make_blockvector make_pointer_type make_cleanup make_reference_type make_command make_symbol_completion_list ((gdb)) b make_ After displaying the available possibilities, GDB copies your partial input ('b make_' in the example) so you can finish the command.
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.
info This command (abbreviated i) is for describing the state of your program. For example, you can list the arguments given to your program with info args, list the registers currently in use with info registers, or list the breakpoints you have set with info breakpoints. You can get a complete list of the info sub-commands with help info. set You can assign the result of an expression to an environment variable with set. For example, you can set the GDB prompt to a $-sign with set prompt $.
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.
the tty command to set a different device for your program. See “Program Input and Output” (page 30). WARNING! You can redirect input and output, but you cannot use pipes to pass the output of the program you are debugging to another program; if you attempt this, GDB is likely to wind up debugging the wrong program. NOTE: • When you issue the run command, your program begins to execute immediately. See Chapter 5 (page 36), for discussion of how to arrange for your program to stop.
variables are just strings, and any interpretation is supplied by your program itself. The value parameter is optional; if it is eliminated, the variable is set to a null value. For example, this command: set env USER = foo tells the debugged program, when subsequently run, that its user is named 'foo'. (The spaces around '=' are used for clarity here; they are not actually required.) unset environment varname Remove variable varname from the environment to be passed to your program.
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. NOTE: • You can redirect your program input and output using shell redirection with the run command. For example, run > outfile starts your program, diverting its output to the file 'outfile'. • An explicit redirection in run overrides the tty command's effect on the input/output device, but not its effect on the controlling terminal.
NOTE: When GDB attaches to a running program you may get a message saying "Attaching to process #nnnnn failed." The most likely cause for this message is that you have attached to a process that was started across an NFS mount. Versions of the HP-UX kernel before 11.x have a restriction that prevents a debugger from attaching to a process started from an NFS mount, unless the mount was made non-interruptible with the -nointr flag, see mount(1).
Whenever GDB detects a new thread in your program, it displays the target system's identification for the thread with a message in the form '[New systag]'. systag is a thread identifier whose form varies depending on the particular system. For example, on LynxOS, you might see [New process 35 thread 27] when GDB notices a new thread. In contrast, on an SGI system, the systag is simply something like 'process 368', with no further qualifier.
number, as shown in the first field of the 'info threads' display. GDB responds by displaying the system identifier of the thread you selected, and its current stack frame summary: ((gdb)) thread 2 [Switching to thread 2 (system thread 26594)] 0x34e5 in sigpause () As with the '[New ...]' message, the form of the text after 'Switching to' depends on your system's conventions for identifying threads.
set follow-fork-mode mode Set the debugger response to a program call of fork or vfork. A call to fork or vfork creates a new process. The mode can be: parent The original process is debugged after a fork. The child process runs unimpeded. This is the default. child show follow-fork-mode The new process is debugged after a fork. The parent process runs unimpeded. Display the current debugger response to a fork or vfork call.
5 Stopping and Continuing The principal purpose of a debugger is to let you stop your program before it terminates abnormally or runs into trouble, so that you can investigate and determine the reason. Inside GDB, your program can stop for several reasons, such as a signal, a breakpoint, or reaching a new line after a GDB command such as step. You can then examine and change variables, set new breakpoints or remove old ones, and then continue execution.
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.
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 41)). See “Break conditions” (page 41). thbreak args Set a hardware-assisted breakpoint enabled only for one stop. args are the same as for the hbreak command and the breakpoint is set in the same way.
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 61)). info break displays a count of the number of times the breakpoint has been hit.
tcatch event 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. unload, unload libname The unloading of any dynamically loaded shared library, or the unloading of the library libname. This is currently only available for HP-UX.
clear linenum, clear filename:linenum Delete any breakpoints set at or within the code of the specified line. delete [breakpoints] [range...] Delete the breakpoints, watchpoints, or catchpoints of the breakpoint ranges specified as arguments. If no argument is specified, delete all breakpoints (GDB asks confirmation, unless you have set confirm off). You can abbreviate this command as d. Disabling breakpoints Rather than deleting a breakpoint, watchpoint, or catchpoint, you might prefer to disable it.
This is the converse of using assertions for program validation; in that situation, you want to stop when the assertion is violated―that is, when the condition is false. In C, if you want to test an assertion expressed by the condition assert, you should set the condition '! assert' on the appropriate breakpoint.
to continue, rather than using ignore. See “Continuing and stepping” (page 45). If a breakpoint has a positive ignore count and a condition, the condition is not checked. Once the ignore count reaches zero, GDB resumes checking the condition. You could achieve the effect of the ignore count with a condition such as '$foo-- <= 0' using a debugger convenience variable that is decremented each time. See “Convenience variables” (page 68). Ignore counts apply to breakpoints, watchpoints, and catchpoints.
break 403 commands silent set x = y + 4 cont end Breakpoint menus Some programming languages (notably C++) permit a single function name to be defined several times, for application in different contexts. This is called overloading. When a function name is overloaded, 'break function' is not enough to tell GDB where you want a breakpoint. If you realize this is a problem, you can use something like 'break function(types)' to specify which particular version of the function you want.
When this message is printed, you need to disable or remove some of the hardware-assisted breakpoints and watchpoints, and then continue. Continuing and stepping Continuing means resuming program execution until your program completes normally. In contrast, stepping means executing just one more “step” of your program, where “step” may mean either one line of source code, or one machine instruction (depending on what particular command you use).
step count Continue running as in step, but do so count times. If a breakpoint is reached, or a signal not related to stepping occurs before count steps, stepping stops right away. next [count] Continue to the next source line in the current (innermost) stack frame. This is similar to step, but function calls that appear within the line of code are executed without stopping.
the command uses breakpoints, and hence is quicker than until without an argument. stepi, stepi arg, Execute one machine instruction, then stop and return to the debugger. si It is often useful to do 'display/i $pc' when stepping by machine instructions. This makes GDB automatically display the next instruction to be executed, each time your program stops. See “Automatic display” (page 62). An argument is a repeat count, as in step.
info handle is an alias for info signals. set The debugger does not deliver the silent signals to the ignore-uninteresting-signals program when ignore-uninteresting-signals is switched on. The default option is on. [on|off] show Display the current status of set ignore-uninteresting-signals ignore-uninteresting-signals command. handle signal keywords... Change the way GDB handles signal signal. signal can be the number of a signal or its name (with or without the 'SIG' at the beginning).
You can use the thread qualifier on conditional breakpoints as well; in this case, place 'thread threadno' before the breakpoint condition, like this: ((gdb)) break frik.c:13 thread 28 if bartab > lim Whenever your program stops under GDB for any reason, all threads of execution stop, not just the current thread. This allows you to examine the overall state of the program, including switching between threads, without worrying that things may change underfoot.
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. 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. 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 51).
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 51)), 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.
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. If your source path is cluttered with directories that are no longer of interest, GDB can end up detecting the wrong version of the source.
Some architectures have more than one commonly-used set of instruction mnemonics or other syntax. set disassembly-flavor Select the instruction set to use when disassembling the program via the disassemble or x/i commands. instruction-set 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 71)). The following forms of print command are supported: print expr, expr is an expression (in the source language).
Variables in expressions are understood in the selected stack frame (see “Selecting a frame” (page 51); 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
Artificial arrays It is often useful to print out several successive objects of the same type in memory; a section of an array, or an array of dynamically determined size for which only a pointer exists in the program. You can do this by referring to a contiguous span of memory as an artificial array, using the binary operator '@'. The left operand of '@' should be the first element of the desired array and be an individual object. The right operand should be the desired length of the array.
t a 2 Print as integer in binary. The letter 't' stands for “two”2. Print as an address, both absolute in hexadecimal and as an offset from the nearest preceding symbol. You can use this format used to discover where (in what function) an unknown address is located: ((gdb)) p/a 0x54320 $3 = 0x54320 <_initialize_vx+396> c Regard as an integer and print it as a character constant. f Regard the bits of the value as a floating point number and print using typical floating point syntax.
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). For example, 'x/3uh 0x54320' is a request to display three halfwords (h) of memory, formatted as unsigned decimal integers ('u'), starting at address 0x54320. 'x/4xw $sp' prints the four words ('w') of memory above the stack pointer (here, '$sp'; see “Registers” (page 69)) in hexadecimal ('x').
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 61). For example, `display/i $pc' can be helpful, to view the machine instruction about to be executed each time execution stops (`$pc' is a common name for the program counter; see “Registers” (page 69)). undisplay dnums...
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 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. If GDB is printing a large array, it stops printing after it has printed the number of elements set by the set print elements command. This limit also applies to the display of strings. When GDB starts, this limit is set to 200.
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 = {...
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. show print object Show whether actual or declared object types are displayed.
show values Print the last ten values in the value history, with their item numbers. This is like 'p $$9' repeated ten times, except that show values does not change the history. show values n Print ten history values centered on history item number n. show values + Print ten history values following the values last printed. If no more values are available, show values + produces no display. Pressing RET to repeat show values n has exactly the same effect as 'show values +'.
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 ...
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.
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 74), for the default settings of supported languages.
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.
C and C++ operators Operators must be defined on values of specific types. For instance, + is defined on numbers, but not on structures. Operators are often defined on groups of types. 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 *).
- Negative. Defined on integral and floating-point types. Same precedence as ++. ! Logical negation. Defined on integral types. Same precedence as ++. ~ 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.
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.
printing the variable or class returns: (gdb) p d3 $3 = {} (gdb) ptype RWCollectableDate type = class RWCollectableDate { C and C++ defaults If you allow GDB to set type and range checking automatically, they both default to off whenever the working language changes to C or C++. This happens regardless of whether you or GDB selects the working language. If you allow GDB to set the language automatically, it recognizes source files whose names end with '.c', '.C', or '.
set print object, show print Choose whether to print derived (actual) or declared types of objects. See “Print settings” (page 63). object set print vtbl, show print vtbl Control the format for printing virtual function tables. See “Print settings” (page 63). (The vtbl commands do not work on programs compiled with the HP aC++ compiler (aCC).) set overload-resolution on Enable overload resolution for C++ expression evaluation. The default is on.
character*len, character*(*) [len is a user supplied length] arrays • automatic • explicit-shape Array elements are displayed in column-major order. Use () for array member access (for example, arr(i) instead of arr[i]). Use set print elements to control the number of elements printed out when specifying a whole array. The default is 200 elements or the number of elements of the array, whichever is smaller.
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 19)), or by one of the file-management commands (see “Commands to specify files” (page 88)).
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.
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. An opaque type is a type declared as a pointer to a struct, class, or union―for example, struct MyType *―that is used in one source file although the full declaration of struct MyType is in another source file. The default is on.
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.
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 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. 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 19)). Occasionally it is necessary to change to a different file during a GDB session.
environment, you may use a compiler that adheres 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.
GDB circumvents the error by ignoring this symbol information. This usually allows you to debug your program, though certain symbols are not accessible. If you encounter such a problem and feel like debugging it, you can debug (gdb) with itself, breakpoint on complain, then go up to the function read_dbx_ symtab and examine *bufp to see the symbol. stub type has NULL name GDB could not find the full definition for a struct or class. const/volatile indicator missing (ok if using g++ v1.x), got...
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 88). 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.
• “Support for Fortran array slices” (page 170) • “Displaying enumerators” (page 170) • “Support for debugging typedefs” (page 171) • “Support for steplast command for C and C++” (page 171) • “Getting information from a non-debug executable” (page 171) • “Debugging optimized code” (page 172) • “Debugging with ARIES” (page 175) • “Visual Interface for HP WDB” (page 176) • “Support for ddd” (page 181) • “Support for XDB commands” (page 181) • “GDB Logging Commands” (page 181) • “Sup
• 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.
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() 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_init_context() pt
• 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.
librtc.sl location $WDB_ROOT/bin None $WDB_ROOT/bin /opt/langtools/bin$WDB_ROOT/lib /opt/langtools/binn/a GDB_SERVER n/a 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. Specifying object file directories GDB enables automatic loading of debug information from object modules when an application is compiled with the +objdebug option.
2. 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. On HP-UX, the debug information does not contain the full path name to the source file, only the relative path name that was recorded at compile time. Consequently, you may need several dir commands for a complex application with multiple source directories. One way to do this is to place them in a .
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 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.
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. NOTE: You must rebuild the program after you use the fix command because the changes you make are temporarily patched into the executable image.
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. (gdb) edit The edit command opens a new terminal session using your environment variable settings for terminal and editor.
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. For example: /opt/aCC/bin/aCC -g +inline_debug test.c 2. Inline debugging is enabled by default. To explicitly enable or disable inline de- bugging, complete either of the following steps before loading the application to the debugger: $ gdb --inline= a.out or (gdb) set inline-debug 3.
The set inline-debug inline_bp_all command enables you to set and modify breakpoints on all instances of a particular inline function. It also enables the inline debugging feature. A single instance of the specified inline function is displayed as a representative in- stance for all the instances of the specified inline function. This creates a single-breakpoint illusion for multiple instances of the inline function.
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 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. This feature is available only for compiler versions A.06.15 and later.
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.
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.
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.
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. The report does not show allocations that have already been freed.
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. min-heap-size This option reports the heap allocations that exceed the specified number of bytes based on the cumulative number of bytes that are allocated at each call-site, which is inclusive of multiple calls to malloc at a particular call site.
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.
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.
nudge_reporting = (or) nudge= Enables nudge triggered reporting feature. Default is off. nudge_signal= Sets the signal number to be used as nudge/trigger for the generation of rtc reports. The default value is 16. 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: Starting from HP WDB 6.4 , with the “nudge triggered rtc reporting” feature, you can now obtain the batch mode reports on Itanium at any point in time during execution of process. The requirement that the process running in batch mode should exit smoothly to produce memory reports, is no longer applicable. You can obtain the batch mode reports by sending a pre-specified signal to the process running under batch mode .
stderr: error message goes to stderr [+]filename: error message goes to filename, + means output is appended to the file. 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.
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.
or gdb prompt, the gdb settings override the process rtc settings. The latest settings in gdb get synced up in the process rtc as well. Use '-leaks' command line option when invoking gdb or set heap-check commands at gdb prompt (before attaching to gdb) for PA-RISC and older versions of HP WDB on Itanium and PA-RISC to enable heap checking on attach. 4. Use info heap and info leaks commands to obtain a memory analysis report of the application. NOTE: • From HP WDB 5.
For detailed information about debugging using RTC APIs, refer Debugging Dynamic Memory Usage Errors Using HP WDB whitepaper at the HP WDB Documentation webpage at: http:// www.hp.com/go/wdb Support for Memory debugging from Core File HP WDB 6.4 and later versions support info heap/leak/danglingcommands for corefile debugging if corefile is generated when application is running under BATCH mode with required rtcconfig setting.
Table 1 Command Description check_openfd=[on | off] Enable/Disable the detection of open file descriptors. NOTE: This feature is currently supported only for batch-mode of memory debugging on HP Integrity systems. Configuring memory debugging settings The following configuration settings are supported to control the level of details of information required to be displayed when debugging memory leaks.
Scenarios in memory debugging Stop when freeing unallocated or deallocated blocks HP WDB enables you to locate improper calls to free() and realloc(), with the command: – In interactive debugging mode: set heap-check free [on | off]. – In batch mode debugging: check_free [on | off]. With this setting on, whenever the program calls free() or realloc() HP WDB inspects the parameters to verify that they are pointing to valid currently allocated heap blocks.
This change to the memory contents increases the chance that erroneous behaviors will cause the program to fail. Examples of such behavior include attempting to access space that is freed or depending on initial values of malloc() blocks. You can now look at the stack trace to understand where and how the problem occurred. NOTE: Turning on scrambling slows down the program slightly, because at every malloc() and free() call, the space involved must be overwritten.
Table 2 Memory Debugging Commands in Interactive and Batch Mode Command Description Interactive mode Batch mode Toggles heap profiling and detection of leaks, bounds, and double free set heap-check [on | off] check_heap= [on | off] (or) set heap-check [on | off] Toggle the leak detection capability set heap-check leaks [on |off] check_leaks =[on | off] (or) set heap-check leaks [on |off] Toggle validation of calls to strcpy, set heap-check string strncpy, memcpy, memccpy, memset, [on | off] memmove
Table 2 Memory Debugging Commands in Interactive and Batch Mode (continued) Command Description Interactive mode Batch mode NULL pointer return by memory allocators; catch nomem used with set heap-check on, with/without null-check enabled. Not supported in batch mode Print hexadecimal addresses against the function names shown in heap or leak report stack trace.
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. If the dynamic linker version is B.11.19 or later, skip this step because HP WDB automatically loads the librtc.sl library. 2. Turn on profiling with the set heap-check on command: (gdb) set heap-check on 3. Set a breakpoint: (gdb) b myfunction 4.
set heap-check high-mem-count X_number Stops when brk() value has moved X_number of times. Limitations: • This feature assumes that an application has a deterministic memory allocation pattern from one run to another. • The high_mem feature is not supported in batch mode debugging.
To enable a thread, execute the following command: (gdb) thread enable 1 Enabling thread 1 You can set and view the kernel threads with the help of the following commands: set show-all-kthreads Sets non-zero integer value so that the gdb reports all the kernel threads. By default this is set to 0, that means gdb reports only those kernel threads that are associated with user threads. show show-all-kthreads Displays the status of current set show-all-kthreads command.
• The thread uses more than the specified percentage of the stack allocated to the thread. • The number of threads waiting on any pthread object exceeds the specified thresh- old number. Pre-requisites for Advanced Thread Debugging The following pre-requisites apply for advanced thread debugging: • The advanced thread debugging features are supported only on HP-UX 11i v2 and later on both PA-RISC and Integrity systems. • The tracing pthread library is required for advanced thread-debugging.
When a thread attempts to acquire a lock on a non-recursive mutex, the debugger checks if the thread currently holds the lock object for the mutex. The debugger transfers the execution control to the user and prints a warning message when this condition is detected. unlock-not-own [on|off] The set thread-check unlock-not-own [on|off] command checks if a thread has attempted to unlock a mutex or a read-write lock that it has not acquired.
thread-exit-own-mutex [on|off] The set thread-check thread-exit-own-mutex [on|off] command checks if any thread has terminated execution without unlocking the mutexes or read-write locks that are associated with the thread. The debugger transfers the execution control to the user and prints a warning message when this condition is detected. This situation can result in deadlocks if other threads are waiting to acquire the locked mutexes or read-write locks.
info mutex [mutex-id] The info mutex [mutex-id] command displays a list of known mutexes. If a mutex-id is provided, the command displays extended information on the specified mutex. info condvar [condvar-id] The info condvar [condvar-id] command displays a list of known condition variables. If condvar-id is provided, the command displays extended information on the specified condition variable. info rwlock [rwlock-id] The info rwlock [rwlock-id] command displays a list of known read-write locks.
To preload the librtc runtime library from a path that is different from the default paths, you must use the LD_PRELOAD environment variable. OR • 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 .
Pre-requisites for Batch mode of Thread Debugging The various prerequisites for Batch mode of Thread Debugging are as follows: • The thread-debugging feature in HP WDB is dependent on the availability of the dynamic linker version B.11.19. • Advanced thread-debugging feature requires the pthread tracer library which is available by default on systems running HP-UX 11i v2 or later. Steps to debug threads in batch mode 1. Compile the source files.
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.
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.
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.
0x40172b25: 0x40172b27: 0x40172b29: 0x40172b2b: 0x40172b2c: 0x40172b2e: 0x40172b2f: (ea) (b2) (61) (81) (c0) (00) (00) P7lc_when t=7 P3lc_gr gr=40 R3body rlen=33 B1label_state label=1 B2epilogue t=44 R1prologue rlen=0 R1prologue rlen=0 Command to Search for a Pattern in the Memory Address Space The HP WDB find command searches for a pattern in the given memory address range for both live and corefile debugging.
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. Support for the dumpcore command HP WDB provides the command, dumpcore to generate a core image file for a process running under the debugger during execution.
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: Support for Core File Debugging of MITR Applications HP WDB 6.0 and later versions support corefile debugging for MIxed mode TRanslator (MITR) applications.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"...To use the side debug file feature on HP-UX/Integrity, follow these steps: • 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.
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. Invoking GDB Before a Program Aborts This -crashdebug option enables GDB to monitor the execution of a process or a program. It invokes GDB when the program execution is about to abort. Once the debugger is invoked, you can debug the application using the normal debugger commands. This option enables you to debug a live process instead of getting a core dump if the program is about to abort.
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.
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.
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.
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.
HP WDB supports: • Evaluation of expressions with decimal floating point constants and variables. • Setting or assignment of decimal floating point constant or variable. • Arithmetic operations such as addition, subtraction, multiplication, division, and negation with decimal floating point constants or variables. • Comparison operations such as ==,!=, >, >=, <, <= with decimal floating point constants or variables.
NOTE: HP WDB will not support: • Command line calls of intrinsic functions (Mathematical functions like cos, sin, log etc) • Decimal Floating Point data type support for Fortran and C++ • HP-UX 11iv2 Integrity and HP 9000 systems Additional Support for binary floating point data type Support for Binary Floating Point constants f, l If the binary floating point constant contains the letter f or l then HP WDB recognizes it as float or long double binary floating point constant.
export GDB_JAVA_UNWINDLIB = /opt/java1.4/jre/lib/PA_RISC/server/libjunwind.sl • For 64-bit PA applications, export GDB_JAVA_UNWINDLIB = /opt/java1.4/jre/lib/PA_RISC2.0/server/libjunwind.sl export GDB_JAVA_UNWINDLIB = /opt/java1.4/jre/lib/PA_RISC2.0W/server/libjunwind.sl If the SDK is installed in a location other than the default, substitute the non-default location for /opt/java1.4 in the previous commands.
java java java java java java java java jvm-state -- Show Java virtual machine's current internal states locals -- Show the current or specified Java frame locals info mutex-info -- Print out details of the static mutexes object -- Print out the given Java object's fields info oop -- Find the Java object oop of the given Java heap address references -- Find all the references to the given Java object in the Java heap unwind-info -- Show the unwind info of the code where the given pc is located unwind-table
2. Invoke gdb on a core file generated when running a 64-bit Java application on an Integrity system with /opt/java1.4/bin/java -d64: $ gdb /opt/java1.4/bin/IA64W/java core.java 3. Invoke gdb on a core file generated when running a 32-bit Java application on PA-RISC using /opt/java1.4/bin/java: $ gdb /opt/java1.4/bin/PA_RISC2.0/java core.java 4. Invoke gdb on a core file generated when running a 64-bit Java application on PA-RISC using /opt/java1.4/bin/java: $ gdb /opt/java1.4/bin/PA_RISC2.
A option -v in ptype command will now display the field offset and size information of a struct/ union/class in addition to the default type information.
Support for debugging namespaces This release of HP WDB provides full support for debugging namespaces. You do not need to use fully qualified names to access symbols within a namespace. The debugger can compile a list of namespaces active in the scope that you are in and, when possible, choose an appropriate symbol. The debugger recognizes using declarations, using directives, namespace aliases, nested namespaces, and unqualified lookup within a namespace.
To run the Visual Interface for HP WDB, use the following command: $vdb -tui To redirect HP WDB output to a log file named mylogfile, use the log command in the following manner: (gdb) log mylogfile The Visual Interface for HP WDB stores the log file, mylogfile, in the current directory.
Values that do not form the sum of any combination of the elements will be displayed as integers while the values that form the sum of any combination of the elements will be printed as unions.
When GDB has no debug information; it does not know where the arguments are located or even the type of the arguments. GDB cannot infer this in an optimized, non-debug executable. However, for integer arguments you can and the first few parameters for the top-of- stack frame by looking at the registers. On PA-RISC systems, the first parameter will be in $r26, the second in $r25, and so on. On IPF systems, the first few parameters will be in $gr32 and $gr33.
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 • tty • undisplay • unset env • until Debugging Optimized Cod
+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). New values may be assigned to a global and a local variable (set = ) when stepping by line (step/next/break ).
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. (This limited support includes all loop optimizations that are enabled at +O3 and above, and some loop optimizations at +O2 or -O.) • Debug support for local aggregates and arrays is limited. • Complete debug support for inlined subroutines is not available.
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. • No support for old GDB versions (of HP-UX 10.20 and earlier). However, debugging of HP-UX 10.20 applications using a HP-UX 11.0 (and newer) HP 9000 GDB is supported. • HP 9000 GDB behaves differently for child processes created using fork() and vfork() system calls. ARIES emulates fork() and vfork() system calls identically.
Most of Visual Interface for HP WDB functionality is also available for emacs users. Visual Interface for HP WDB does not require knowledge of vi commands. Visual Interface for HP WDB identifies you as an emacs user by looking at the environment variable `$EDITOR'. If this variable has a value that matches emacs, or gmacs, or xemacs, then Visual Interface for HP WDB starts in emacs mode automatically.
• The left and right arrow keys move the cursor in the debugger window. • Two rows of labeled softkeys at the bottom of the display give you quick access to common commands. Visual Interface for HP WDB GUI display 33 #include 34 #include "Deck.h" 35 #include "Player.h" 36 #include "House.h" 37 38 int main () 39 { *> 40 srand ((int) time(0)); 41 42 Deck theDeck; 43 Player thePlayer (100); 44 House theHouse (16); 45 46 theHouse.Instructions(); 47 } File: BlackJack.
With a mouse you can do the following: • Left-click the line number to insert or remove breakpoints. • Left-click an identifier to select the identifier as an operand for the Print, Print*, Type, and List softkeys. • Where necessary, manually select an expression by dragging the cursor over it. • Right-click the line number to activate a pop-up menu with several useful commands.
CTRL-W + to increase CTRL-W to decrease In Visual Interface for HP WDB, the current window is usually the debugger window. Using commands to browse through source files browse. For example, CTRL-B, CTRL-F, CTRL-D, CTRL-U are useful for browsing the debugger window. These commands work whether or not you escape to `vi' mode. These `vim' commands require you to escape to `vi' mode.
Support for ddd GDB works with ddd, the free GDB GUI shell available at http://mumm.ibr.cs.tu-bs.de/. While this is not formally supported by Hewlett-Packard, these two do work together. Note however if you have ddd issues, you'll need to report them to the ddd support channel. Support for XDB commands HP WDB provides support for a subset of XDB commands, enabled with the -xdb option.
To perform command line calls after attaching a running process to GDB, you must execute one of the following commands: • /opt/langtools/bin/pxdb -s on • chatr +dbg enable Additional support for command line calls in a stripped executable HP WDB enables you to perform command line calls in a stripped executable.
GDB will be able to access the globals or locals defined in other unstripped shared libraries loaded into the stripped executable when you are in the right scope. Backtrace on stripped frames GDB should be able to backtrace properly stripped frames. Arguments will not be displayed (as in the case of non -g binary). If it is a fully archived stripped binary, function names will not be displayed (but PCs will be).
compiling with the -g option for all source files except for the files in system libraries. The valid options are: Options Description none Source level debugging is not available when the program is compiled without -g. no_sys_libs Source level debugging is available for all the source files except the source files in the system libraries. This option is the default setting, when no options are specified. all show src-no-g Source level debugging is available for all the source files.
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 195). 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.
Disassembly pane The Disassembly pane appears when you issue the command la asm The pane looks like this: |----------------------------------------------------------------------| |;;; print_average (my_list, first, last); | *>|0x3524 addil L'-0x800,%dp,%r1 | |0x3528 ldo 0x730(%r1),%r26 | |0x352c ldi 9,%r24 | |0x3530 ldi 0,%r25 | |0x3534 ldil L'0x3000,%r31 | |0x3538 be,l 0x498(%sr4,%r31) | |0x353c copy %r31,%rp | |;;; print_average (my_li
Breakpoint 1, main () at average.c:32 (gdb) la asm (gdb) la split (gdb) 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) 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 : :.........................................................................
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] Vertically scroll the pane forward (+) or backward (-). + or - with no arguments scrolls the pane forward or backward [win_name] 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 194 The HP-UX Terminal User Interface
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.
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 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) 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.
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 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 Signal control commands The following table lists the XDB and equivalent HP WDB commands for signal control: Table 16 Signal control com
Table 17 Miscellaneous commands (continued) XDB Command HP WDB Equivalent Meaning M[{t | c} [expr[; expr...
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 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 .
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 F through K Table 26 F through K XDB Command Equivalent HP WDB Command f ["printf-style-fmt"] No equivalent fr fr (with -xdb -tui), display $fregs (with -tui) g line g line (with -xdb), go line, tb line followed by jump line g #label No equivalent g {+ | -}lines g {+ | -}lines (with -xd
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 M thr
Q through S Table 29 Q through S XDB Command Equivalent HP WDB Command q q Q Q (with -xdb), silent (must be first command in a commands list) r [arguments] r [arguments] R R (with -xdb), r s s, si s number s number, si number S S (with -xdb), n, ni S number S number (with -xdb), n number, ninumber sa number No equivalent sa * No equivalent sb number disable number sb * disable sb @shared-library No equivalent sm sm (with -xdb), set height 0 sr sr (with -xdb -tui), display $sre
U through Z Table 31 U through Z XDB Command Equivalent HP WDB Command u u (with -xdb -tui), update (with -tui) U U (with -xdb -tui), refresh (with -tui) undef name def name [follow with empty command list] undef * No equivalent up down up number down number v v (with -xdb), list v location v location (with -xdb), list location V [depth] V [depth] (with -xdb), frame [depth] va address va address (with -xdb), disas address va label va label (with -xdb), disas label va label + offset
Table 32 Symbols (continued) XDB Command 214 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" .
Table 32 Symbols (continued) XDB Command Equivalent HP WDB Command Control-C Control-C # [text] # [text] #label No equivalent Alphabetical lists of XDB commands and HP WDB equivalents 215
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 63). Other settings are described here. Setting the GDB Prompt GDB indicates its readiness to read a command by printing a string called the prompt. This string is normally `((gdb))'. You can change the prompt string with the set prompt command.
set 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. History expansion assigns special meaning to the character !.
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'. Numbers that begin with none of these are, by default, entered in base 10; likewise, the default display for numbers|when no particular format is specified| is base 10. You can change the default base for both input and output with the set radix command.
show confirm Displays state of confirmation requests. Optional messages about internal happenings set debug arch Turns on or off display of gdbarch debugging info. The default is off show debug arch Displays the current state of displaying gdbarch debugging information. set debug event Turns on or o display of GDB event debugging information. The default is o. show debug event Displays the current state of displaying GDB event debugging info.
18 Canned Sequences of Commands In addition to breakpoint commands (see “Breakpoint command lists” (page 43)), GDB provides the following two ways to store sequence of commands for execution as a unit: • user-defined commands • command files 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.
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 20)). 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 58). output/fmt expression Print the value of expression in format fmt. You can use the same formats as for print. See “Output formats” (page 60). 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. 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.
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.
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. 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.
^Z^Zbreakpoints-table-end 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. Running the program When the program starts executing due to a GDB command such as step or continue, ^Z^Zstarting is output.
Annotations We Might Want in the Future • target-invalid the target might have changed (registers, heap contents, or execution status). For performance, we might eventually want to hit registers-invalid and all-registers-invalid with greater precision • systematic annotation for set/show parameters (including invalidation notices). • similarly, `info' returns a list of candidates for invalidation notices.
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. 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)'. If an input command was prefixed with a token then the corresponding output for that command will also be prefixed by that same token.
• 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. GDB/MI output records 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 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'.
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.
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.
(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 -break-watch command Synopsis -break-watch [ -a | -r ] Create a
-break-watch j ^done,wpt=number="2",exp="j" (gdb) -break-list ^done,BreakpointTable=nr_rows="2",nr_cols="6",hdr=[width="3", alignment="-1",col_name="number",colhdr="Num",width="14",alignment="-1", col_name="type",colhdr"Type",width="4",alignment="-1",col_name="disp", colhdr="Disp",width="3",alinment="-1",col_name="enabled",colhdr="Enb", width="10",alignment="-1",col_name"addr",colhdr="Address", width="40",alignment="2",col_name="what",colhdr="What],body=[bkpt=number="1", type="breakpoint",disp="keep",enable
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). Result The output for each instruction is composed of four fields: • Address • Func-name • Offset • Instruction Note that whatever included in the instruction field, is not manipulated directly by GDB/MI, that is it is not possible to adjust its format.
{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="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. 'word-format' The format to be used to print the memory words.
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.
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. The -environment-cd command Synopsis -environment-cd pathdir Set the GDB working directory.
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'. Example (gdb) -environment-path /kwikemart/marge/ezannoni/flathead-dev/ppc-eabi/gdb ^done (gdb) The -environment-pwd command Synopsis -environment-pwd Show the current working directory.
^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 N.A.
The -exec-finish command Synopsis -exec-finish Asynchronous command. Resumes the execution of the inferior program until the current function is exited. Displays the results returned by the function. GDB command The corresponding GDB command is 'finish'. Example Function returning void. -exec-finish ^running (gdb) @hello from foo *stopped,reason="function-finished",thread-id="1",frame=addr="0x000029ec", func="main",args=[],file="hello.c",line="7file="hello.
-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. GDB command The corresponding GDB command is 'next'. Example -exec-next ^running (gdb) *stopped,reason="end-stepping-range",thread-id="1",frame=addr="0x00002a10", func="main",args=[],file="hello.
Example (gdb) -break-insert call1 ^done,bkpt=number="1",type="breakpoint",disp="keep",enabled="y",addr="0x000029ac", func="call1",file="hello.c",line="9",times="0" (gdb) -exec-run ^running (gdb) ~"3" *stopped,reason="breakpoint-hit",bkptno="1",thread-id="1",frame=addr="0x000029ac", func="call1",args=[name="a"],file="hello.c",line="9" (gdb) -exec-return ~"2" ~"3" ^done,frame=level="0 ",addr="0x000029e8",func="call",args=[name="a",name="b"], file="hello.
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'.
(gdb) *stopped,reason="end-stepping-range", frame={addr="0x000100f4",func="foo",args=[],file="try.c",line="10"} (gdb) The -exec-until command Synopsis -exec-until [ location ] Asynchronous command. Executes the inferior until the location specified in the argument is reached. If there is no argument, the inferior executes until a source line greater than the current one is reached. The reason for stopping in this case will be 'location-reached'. GDB command The corresponding GDB command is 'until'.
Example (gdb) -file-exec-file /kwikemart/marge/ezannoni/TRUNK/mbx/hello.mbx ^done (gdb) The -file-list-exec-sections command Synopsis -file-list-exec-sections List the sections of the current executable file. GDB command The GDB command 'info file' shows, among the rest, the same information as this command. gdbtk has a corresponding command 'gdb_load_info'. Example N.A. The -file-list-exec-source-files command Synopsis -file-list-exec-source-files List the source files for the current executable.
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. GDB command The corresponding GDB command is 'symbol-file'. Example (gdb) -file-symbol-file /kwikemart/marge/ezannoni/TRUNK/mbx/hello.
The -gdb-show command Synopsis -gdb-show Show the current value of a GDB variable. GDB command The corresponding GDB command is 'show'. Example (gdb) -gdb-show annotate ^done,value="0" (gdb) The -gdb-version command Synopsis -gdb-version Show version information for GDB. Used mostly in testing. GDB command The corresponding GDB command is 'show version'. Example (gdb) -gdb-version ~GNU gdb 5.2.1 ~Copyright 2000 Free Software Foundation, Inc.
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.
frame={level="3 ",addr="0x000107b4",func="callee1", file="../../../devo/gdb/testsuite/gdb.mi/basics.c",line="27"}, frame={level="4 ",addr="0x000107e0",func="main", file="../../../devo/gdb/testsuite/gdb.mi/basics.
(gdb) -stack-list-frames ^done,stack= [frame={level="0 ",addr="0x0001076c",func="foo", file="recursive2.c",line="11"}, frame={level="1 ",addr="0x000107a4",func="foo", file="recursive2.c",line="14"}, frame={level="2 ",addr="0x000107a4",func="foo", file="recursive2.c",line="14"}, frame={level="3 ",addr="0x000107a4",func="foo", file="recursive2.c",line="14"}, frame={level="4 ",addr="0x000107a4",func="foo", file="recursive2.c",line="14"}, frame={level="5 ",addr="0x000107a4",func="foo", file="recursive2.
Example (gdb) -stack-list-locals 0 ^done,locals=[name="A",name="B",name="C"] (gdb) -stack-list-locals 1 ^done,locals=[{name="A",value="1"},{name="B",value="2"}, {name="C",value="3"}] (gdb) The -stack-select-frame command Synopsis -stack-select-frame framenum Change the current frame. Select a different frame framenum on the stack. GDB command The corresponding GDB commands are 'frame', 'up', 'down', 'select-frame', 'up-silent', and 'down-silent'.
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. GDB command The corresponding GDB command is 'info line'. gdbtk has the 'gdb_get_line' and 'gdb_get_file' commands. Example N.A.
The -symbol-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. The -symbol-list-variables command Synopsis -symbol-list-variables List all the global and static variable names. GDB command 'info variables' in GDB, 'gdb_search' in gdbtk. Example N.A. The -symbol-locate command Synopsis -symbol-locate GDB command 'gdb_loc' in gdbtk. Example N.A.
GDB/MI Target Manipulation Commands The -target-attach command Synopsis -target-attach pid | file Attach to a process pid or a file file outside of GDB. GDB command The corresponding GDB command is 'attach'. Example N.A. The -target-compare-sections command Synopsis -target-compare-sections [ section ] Compare data of section section on target to the exec file. Without the argument, all sections are compared. GDB command The GDB equivalent is 'compare-sections'. Example N.A.
'section-size' The size of the section. 'total-sent' The total size of what was sent so far (the current and the previous sections). 'total-size' The size of the overall executable to download. Each message is sent as status record (see “GDB/MI Output syntax” (page 234). In addition, it prints the name and size of the sections, as they are downloaded. These messages include the following fields: 'section' The name of the section. 'section-size' The size of the section.
total-sent="8772",total-size="9880"} +download,{section=".data",section-sent="2560",section-size="3156", total-sent="9284",total-size="9880"} +download,{section=".data",section-sent="3072",section-size="3156", total-sent="9796",total-size="9880"} ^done,address="0x10004",load-size="9880",transfer-rate="6586", write-rate="429" (gdb) The -target-exec-status command Synopsis -target-exec-status Provide information on the state of the target (whether it is running or not, for instance).
GDB command No equivalent. Example N.A. The -target-select command Synopsis -target-select type parameters ... Connect GDB to the remote target. This command takes two args: 'type' The type of target, for instance 'async', 'remote', and so on. 'parameters' Device names, host names and the like. See “Commands for managing targets” (page 94), for more details.
Example N.A. The -thread-list-ids command Synopsis -thread-list-ids Produces a list of the currently known GDB thread ids. At the end of the list it also prints the total number of such threads. GDB command Part of 'info threads' supplies the same information.
GDB/MI variable objects Motivation for variable objects in GDB/MI For the implementation of a variable debugger window (locals, watched expressions, and so on.), we are proposing the adaptation of the existing code used by Insight. The two main reasons for that are: 1. It has been proven in practice (it is already on its second generation). 2. It will shorten development time (needless to say how important it is now).
Table 33 GDB/MI Operations (continued) -var-assign set the value of this variable -var-update update the variable and its children In the next subsection we describe each operation in detail and suggest how it can be used.
The -var-show-format command Synopsis -var-show-format name Returns the format used to display the value of the object name.
The -var-evaluate-expression command Synopsis -var-evaluate-expression name Evaluates the expression that is represented by the specified variable object and returns its value as a string in the current format specified for the object: value=value The -var-assign command Synopsis -var-assign name expression Assigns the value of expression to the variable object specified by name. The object must be 'editable'.
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.
To enable us to x the bug, you should include all these things: • The version of GDB. GDB announces it if you start with no arguments; you can also print it at any time using show version. 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.
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.
23 Documentation feedback HP is committed to providing documentation that meets your needs. To help us improve the documentation, send any errors, suggestions, or comments to Documentation Feedback (docsfeedback@hp.com). Include the document title and part number, version number, or the URL when submitting your feedback.
A Installing GDB If you obtain GDB (HP WDB) as part of the HP ANSI C, HP aC++ 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. 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.