Below is a list of useful snippets I took from the GDB manual to reference later.


Print exceptions: p $_exception


Define a function to rebuild a program from within gdb

define reload
  set confirm off
  shell make
  file ./your_app
  run
end

Run with catch throw and without initial breakpoint: gdb -ex "catch throw" -ex "run" --args


To look at some context, we can display ten lines of source surrounding the current line with the l (list) command.

(gdb) l
533             xfree(rquote);
534
535         lquote = (lq == nil || *lq == '\0') ? def_lquote\
 : xstrdup (lq);
536         rquote = (rq == nil || *rq == '\0') ? def_rquote\
 : xstrdup (rq);
537
538         len_lquote = strlen(rquote);
539         len_rquote = strlen(lquote);
540     }
541
542     void

Run using a TUI: gdb -tui

See https://ftp.gnu.org/old-gnu/Manuals/gdb/html_node/gdb_192.html#SEC197


If you need to execute occasional shell commands during your debugging session, there is no need to leave or suspend GDB; you can just use the shell command.

shell command string

The utility make is often needed in development environments. You do not have to use the shell command for this purpose in GDB:

make make-args


Sometimes the string you need, while logically a “word”, may contain parentheses or other characters that GDB normally excludes from its notion of a word. To permit word completion to work in this situation, you may enclose words in ' (single quote marks) in GDB commands:

(gdb) b 'bubble( M-?
bubble(double,double)    bubble(int,int)
(gdb) b 'bubble(

set args

Specify the arguments to be used the next time your program is run. If set args has no arguments, run executes your program with no arguments. Once you have run your program with arguments, using set args before the next run is the only way to run it again without arguments.

show args

Show the arguments to give your program when it is started.


Debugging threads: https://ftp.gnu.org/old-gnu/Manuals/gdb/html_node/gdb_24.html


You have several ways to say where the breakpoint should go.

You can use a watchpoint to stop execution whenever the value of an expression changes, without having to predict a particular place where this may happen.

You can use catchpoints to cause the debugger to stop for certain kinds of program events (for example catch throw to break whenever an exception is thrown)

command description
break function set a breakpoint at entry to function function.
break ... if cond set a breakpoint with condition cond, a condition is just a Boolean expression in your programming language
tbreak args set a breakpoint enabled only for one stop
rbreak regex set breakpoints on all functions matching the regular expression regex
info break print a table of all breakpoints, watchpoints, and catchpoints
watch expr set a watchpoint for an expression. GDB will break when expr is written into by the program and its value changes.
rwatch expr set a watchpoint that will break when watch expr is read by the program.
awatch expr set a watchpoint that will break when expr is either read or written into by the program.
catch throw stop when an exception is thrown
catch catch stop when an exception was caught
clear delete any breakpoints at the next instruction to be executed in the selected stack frame (see section Selecting a frame). When the innermost frame is selected, this is a good way to delete a breakpoint where your program just stopped.
clear function delete any breakpoints set at entry to the function function.
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 or del.
disable [breakpoints] [range...] disable the specified breakpoints–or all breakpoints, if none are listed
enable [breakpoints] [range...] enable the specified breakpoints (or all defined breakpoints).

You can give any breakpoint (or watchpoint or catchpoint) a series of commands to execute when your program stops due to that breakpoint. For example, you might want to print the values of certain expressions, or enable other breakpoints.

commands [bnum]

... command-list ...

end

Specify a list of commands for breakpoint number bnum. The commands themselves appear on the following lines. Type a line containing just end to terminate the commands. To remove all commands from a breakpoint, type commands and follow it immediately with end; that is, give no commands. With no bnum argument, commands refers to the last breakpoint, watchpoint, or catchpoint set (not to the breakpoint most recently encountered).

For example, here is how you could use breakpoint commands to print the value of x at entry to foo whenever x is positive (and the cont causes the program to not wait at the breakpoint).

break foo if x>0
commands
silent
printf "x is %d\n",x
cont
end

One application for breakpoint commands is to compensate for one bug so you can test for another. Put a breakpoint just after the erroneous line of code, give it a condition to detect the case in which something erroneous has been done, and give it commands to assign correct values to any variables that need them. End with the continue command so that your program does not stop, and start with the silent command so that no output is produced. Here is an example:

break 403
commands
silent
set x = y + 4
cont
end

When a function name is overloaded, break function is not enough to tell GDB where you want a breakpoint. For example, the following session excerpt shows an attempt to set a breakpoint at the overloaded symbol String::after. We choose three particular definitions of that function name:

(gdb) b String::after
[0] cancel
[1] all
[2] file:String.cc; line number:867
[3] file:String.cc; line number:860
[4] file:String.cc; line number:875
[5] file:String.cc; line number:853
[6] file:String.cc; line number:846
[7] file:String.cc; line number:735
> 2 4 6
Breakpoint 1 at 0xb26c: file String.cc, line 867.
Breakpoint 2 at 0xb344: file String.cc, line 875.
Breakpoint 3 at 0xafcc: file String.cc, line 846.
Multiple breakpoints were set.
Use the "delete" command to delete unwanted
 breakpoints.
(gdb)

Stepping through code

command description
c [ignore-count] Resume program execution, the optional argument ignore-count allows you to specify a further number of times to ignore a breakpoint at this location.
step Continue running your program until control reaches a different source line, then stop it and return control to GDB. This command is abbreviated s.
step count Continue running as in step, but do so count times.
next [count] Continue to the next source line in the current (innermost) stack frame, but do so count times
finish Continue running until just after function in the selected stack frame returns. Print the returned value (if any). Contrast this with the return command (see section Returning from a function).
untilu Continue running until a source line past the current line, in the current stack frame, is reached. This command is used to avoid single stepping through a loop more than once. It is like the next command, except that when until encounters a jump, it automatically continues execution until the program counter is greater than the address of the jump. This means that when you reach the end of a loop after single stepping though it, until makes your program continue execution until it exits the loop. In contrast, a next command at the end of a loop simply steps back to the beginning of the loop, which forces you to step through the next iteration.
until [location]u [location] Continue running your program until either the specified location is reached, or the current stack frame returns. location is any of the forms of argument acceptable to break

To resume execution at a different place, you can use return (see section Returning from a function) to go back to the calling function; or jump (see section Continuing at a different address) to go to an arbitrary location in your program.


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); a list of signal numbers of the form low-high’; or the word `all’, meaning all the known signals. The keywords say what change to make.

The keywords allowed by the handle command can be abbreviated. Their full names are:

nostop GDB should not stop your program when this signal happens. It may still print a message telling you that the signal has come in.

stop GDB should stop your program when this signal happens. This implies the print keyword as well.

print GDB should print a message when this signal happens.

noprint GDB should not mention the occurrence of the signal at all. This implies the nostop keyword as well.

pass / noignore GDB should allow your program to see this signal; your program can handle the signal, or else it may terminate if the signal is fatal and not handled. pass and noignore are synonyms.

nopass / ignore GDB should not allow your program to see this signal. nopass and ignore are synonyms.


Interacting with frames:

frame args The frame command allows you to move from one stack frame to another, and to print the stack frame you select. args may be either the address of the frame or the stack frame number. Without an argument, frame prints the current stack frame.

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.

up n Move n frames up the stack. For positive numbers n, this advances toward the outermost frame, to higher frame numbers, to frames that have existed longer. n defaults to one.

down n Move n frames down the stack. For positive numbers n, this advances toward the innermost frame, to lower frame numbers, to frames that were created more recently. n defaults to one. You may abbreviate down as do.

info args Print the arguments of the selected frame, each on a separate line.

info locals Print the local variables of the selected frame, each on a separate line. These are all variables (declared either static or automatic) accessible at the point of execution of the selected frame.

info catch Print a list of all the exception handlers that are active in the current stack frame at the current point of execution.

backtrace n backtrace, but print only the innermost n frames. bt n


Print source lines: list linenum Print lines centered around line number linenum in the current source file.

list function Print lines centered around the beginning of function function.

list Print more lines. If the last lines printed were printed with a list command, this prints lines following the last lines printed; however, if the last line printed was a solitary line printed as part of displaying a stack frame (see section Examining the Stack), this prints lines centered around that line.

list - Print lines just before the lines last printed. list + Print lines just after the lines last printed.

By default, GDB prints ten source lines with any of these forms of the list command. You can change this using set listsize:

set listsize count Make the list command display count source lines (unless the list argument explicitly specifies some other number).

show listsize Display the number of lines that list prints.


Printing arrays:

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. The result is an array value whose elements are all of the type of the left argument. The first element is actually the left argument; the second element comes from bytes of memory immediately following those that hold the first element, and so on. Here is an example. If a program says

int *array = (int *) malloc (len * sizeof (int));

you can print the contents of array with

p *array@len

The left operand of @' must reside in memory. Array values made with @’ in this way behave just like other arrays in terms of subscripting, and are coerced to pointers when used in expressions. Artificial arrays most often appear in expressions via the value history (see section Value history), after printing one out.

Another way to create an artificial array is to use a cast. This re-interprets a value as if it were an array. The value need not be in memory:

(gdb) p/x (short[2])0x12345678
$1 = {0x1234, 0x5678}

As a convenience, if you leave the array length out (as in (type[])value') GDB calculates the size to fill the value (as sizeof(value)/sizeof(type)':

(gdb) p/x (short[])0x12345678
$2 = {0x1234, 0x5678}

Sometimes the artificial array mechanism is not quite enough; in moderately complex data structures, the elements of interest may not actually be adjacent–for example, if you are interested in the values of pointers in an array. One useful work-around in this situation is to use a convenience variable (see section Convenience variables) as a counter in an expression that prints the first interesting value, and then repeat that expression via RET. For instance, suppose you have an array dtab of pointers to structures, and you are interested in the values of a field fv in each structure. Here is an example of what you might type:

set $i = 0
p dtab[$i++]->fv
RET
RET
...

 Format Letter   Description 
 x             Regard the bits of the value as an integer, and print the integer in hexadecimal. 
 d             Print as integer in signed decimal. 
 u             Print as integer in unsigned decimal. 
 o             Print as integer in octal. 
 t             Print as integer in binary. The letter t stands for “two” (2). 
 a             Print as an address, both absolute in hexadecimal and as an offset from the nearest preceding symbol.  Example: (gdb) p/a 0x54320 → $3 = 0x54320 <_initialize_vx+396>.  Also see info symbol
 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. 

For example, to print the program counter in hex, type: p/x $pc


You can use the command x (for “examine”) to examine memory in any of several formats, independently of your program’s data types. x/nfu addr x addr x

Use the x command to examine memory.

n, f, and u are all optional parameters that specify how much memory to display and how to format it; addr is an expression giving the address where you want to start displaying memory. If you use defaults for nfu, you need not type the slash /. Several commands set convenient defaults for addr.

n, the repeat count: The repeat count is a decimal integer; the default is 1. It specifies how much memory (counting by units u) to display.

f, the display format: The display format is one of the formats used by prints' (null-terminated string), or i’ (machine instruction). The default is x' (hexadecimal) initially. The default changes each time you use either x or print`.

u, the unit size: The unit size is any of b Bytes. h Halfwords (two bytes). w Words (four bytes). This is the initial default. g Giant words (eight bytes).


If you find that you want to print the value of an expression frequently (to see how it changes), you might want to add it to the automatic display list so that GDB prints its value each time your program stops. Each expression added to the list is given a number to identify it; to remove an expression from the list, you specify that number. The automatic display looks like this:

2: foo = 38
3: bar[5] = (struct hack *) 0x3804

This display shows item numbers, expressions and their current values. As with displays you request manually using x or print, you can specify the output format you prefer; in fact, display decides whether to use print or x depending on how elaborate your format specification is–it uses x if you specify a unit size, or one of the two formats (i' and s’) that are only supported by x; otherwise it uses print.

display expr Add the expression expr to the list of expressions to display each time your program stops. See section Expressionsdisplay does not repeat if you press RET again after using it.

display/fmt expr For fmt specifying only a display format and not a size or count, add the expression expr to the auto-display list but arrange to display it each time in the specified format fmt. See section Output formats.

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 section Examining memory.