3. GDB Cheat Sheet¶
gdb [options] [PROGRAM [COREFILE or PID]]
gdb [options] --args PROGRAM [INFARGS...] to pass any arguments
after the executable file to the inferior
3.1. Options¶
--silent[or-q/--quiet] to start without printing the front material--core COREFILE[or-c] to analyze a core dump--pid PID[or-p] to debug a running process (as with theattachcommand)--command EXECFILE[or-x] to execute commands from file (as with thesourcecommand)--symbols SYMFILE[or-s] to read symbol table from file
3.2. Examples¶
gdb -q --args gcc -O2 -c foo.c
3.3. Examples of command-lists from a command file¶
b main
commands 1
print argc
continue
end
b *0xdeadbeef if x > 0
commands 2
p i
p b
continue
end
run
Table of Contents
3.4. Getting In and Out of gdb¶
3.4.1. Quitting gdb¶
quit[orq] to exit gdb. An interrupt (oftenCtrl-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. It is safe to type the interrupt character at any time because gdb does not allow it to take effect until a time when it is safe
3.4.2. Shell Commands¶
shell COMMAND[or!COMMAND] to invoke a standard shell to execute COMMAND
3.4.3. Logging Output¶
set logging on|offto enable/disable loggingset logging file FILEto change the name of the current logfile. The default logfile isgdb.txt
3.5. gdb Commands¶
3.5.1. Getting Help¶
help[orh] to display a short list of named classes of commandshelp COMMANDto display a short paragraph on how to use that commandapropos ARGSto searche through all of the gdb commands and their documentation for the regular expression specified in ARGScomplete ARGSto list all the possible completions for the beginning of a command specified by ARGSinfo[ori] to describe the state of your program. You can get a complete list of the info sub-commands withhelp infoinfo files[orinfo target] to display info on the debugged program (useful to find the entry point)info functions [REGEXP]to list all defined functions or whose matching REGEXPinfo address SYMBOLto find address of SYMBOLinfo proc mappingsto display the list of mapped memory regionsinfo registers [REGISTER]to display the contents of all the general-purpose processor registers or the content of register REGISTERinfo sharedlibraryto display information about loaded librariesinfo symbol ADDRto display the name of the symbol residing at a given address ADDRinfo types [REGEXP]to display the list of types defined in the currently loaded modules or the list of types matching REGEXPinfo variables [REGEXP]to display the list of global/static variables or whose matching REGEXP
3.5.1.1. Examples¶
help statusapropos aliascomplete iinfo addr system
3.6. Running Programs Under gdb¶
3.6.1. Compiling for Debugging¶
To request debugging information, specify the -g option when you run
the compiler.
3.6.2. Starting your Program¶
run[orr] to start your program under gdbstartto set a temporary breakpoint at the beginning of the main procedure and then invoke theruncommandset exec-wrapper WRAPPERto set the wrapper used to launch programs for debugging, with a shell command of the formexec WRAPPER program. You can use any program that eventually callsexecvewith its arguments as a wrappershow exec-wrapperset disable-randomization on|offto enable/disable address randomization
3.6.2.1. Examples¶
set exec-wrapper env 'LD_PRELOAD=custom_libc.so'(to pass an environment variable to the debugged program without setting the variable in your shell’s environment)
3.6.3. Your Program’s Arguments¶
set argsto specify the arguments to be used the next time your program is run. Ifset argshas no arguments, run executes your program with no arguments. Once you have run your program with arguments, usingset argsbefore the next run is the only way to run it again without argumentsshow args
3.6.4. Your Program’s Environment¶
set environment VARNAME [VALUE]to set environment variable VARNAME to VALUEshow environment [VARNAME]to print the value of environment variable VARNAME. If VARNAME is not specified, print the names and values of all environment variablesunset environment [VARNAME]to remove variable VARNAME from the environment. If VARNAME is not specified, remove all environment variables
3.6.4.1. Examples¶
set environment LD_PRELOAD=./yourso.so
3.6.5. Debugging an Already-running Process¶
attachto attach to a running process started outside gdb
3.6.6. Debugging Multiple Inferiors and Programs¶
info inferiorsto print a list of all inferiors currently being managed by gdbinferior INFNOto make inferior number INFNO the current inferiorkill inferiors INFNO...to kill the inferior or inferiors identified by gdb inferior number(s)
3.6.7. Debugging Programs with Multiple Threads¶
thread THREADIDto switch among threadsinfo threadsto inquire about existing threads
3.6.8. Debugging Forks¶
set follow-fork-mode MODEto set the debugger response to a program call offorkorvfork. The MODE argument can beparent(the original process is debugged after a fork) orchild(the new process is debugged after a fork)show follow-fork-modeset detach-on-fork MODEto detach one of the processes after a fork or retain debugger control over them both. The MODE argument can beon(the child process (or parent process, depending on the value offollow-fork-mode) will be detached and allowed to run independently) oroff(both processes will be held under the control of gdb, one debugged and the other held suspended)show detach-on-forkset follow-exec-mode MODEto set debugger response to a program call ofexec. The MODE argument can benew(gdb creates a new inferior and rebinds the process to this new inferior. The program the process was running before theexeccall can be restarted afterwards by restarting the original inferior) orsame(gdb keeps the process bound to the same inferior. The new executable image replaces the previous executable loaded in the inferior. Restarting the inferior after theexeccall, with e.g., theruncommand, restarts the executable the process was running after theexeccall)show follow-exec-mode
3.6.9. Setting a Bookmark to Return to Later¶
checkpointsave a snapshot of the debugged program’s current execution stateinfo checkpointsto list the checkpoints that have been saved in the current debugging sessionrestart CHKIDto restore the program state that was saved as checkpoint number CHKIDdelete checkpoint CHKIDto delete the previously-saved checkpoint identified by CHKID
3.7. Stopping and Continuing¶
3.7.1. Breakpoints, Watchpoints, and Catchpoints¶
break [LOCATION]to a breakpoint at the given LOCATION. If LOCATION is not specified, set a breakpoint at the next instruction to be executed in the selected stack framebreak ... if CONDto set a breakpoint with condition CONDtbreak ARGSto set a breakpoint enabled only for one stop (ARGS are the same as for thebreakcommand)hbreak ARGSto set a hardware-assisted breakpoint (ARGS are the same as for thebreakcommand)thbreak ARGSto set a hardware-assisted breakpoint enabled only for one stop (ARGS are the same as for thehbreakcommand)rbreak REGEXto set breakpoints on all functions matching the regular expression REGEXbreak ARGS thread THREADNOto set breakpoints on a particular threadinfo breakpointsto print a table of all breakpoints, watchpoints, and catchpoints set and not deleted
Use a watchpoint to stop execution whenever the value of an expression changes.
watch EXPRto set a watchpoint that will break when the expression EXPR is written into by the program and its value changesrwatch EXPRto set a watchpoint that will break when the value of EXPR is read by the programawatch EXPRto set a watchpoint that will break when EXPR is either read from or written into by the programinfo watchpointsto print a list of watchpoints
gdb sets a hardware watchpoint if possible. Hardware watchpoints execute
very quickly, and the debugger reports a change in value at the exact
instruction where the change occurs. If gdb cannot set a hardware
watchpoint, it sets a software watchpoint, which executes more slowly
and reports the change in value at the next statement, not the
instruction, after the change occurs. -
set can-use-hw-watchpoints 0|1 to set whether or not to use hardware
watchpoints - show can-use-hw-watchpoints to show the current mode
of using hardware watchpoints
In multi-threaded programs, watchpoints will detect changes to the watched expression from every thread.
delete [RANGE...]to delete the breakpoints, watchpoints, or catchpoints of the breakpoint ranges. If RANGE… is not specified, delete all breakpoints, watchpoints or catchpointsdisable [RANGE...]to disable the specified breakpoints. If RANGE… is not specified, disable all breakpointsenable [RANGE...]to enable the specified breakpoints. If RANGE… is not specified, enable all breakpointsenable once RANGE...to enable the specified breakpoints temporarily and then disable them after stopping your programenable delete RANGE...to enable the specified breakpoints temporarily and then delete them after stopping your programsave breakpoints [FILE]to save breakpoint definitions to a file
3.7.1.1. Examples¶
watch xwatch *0x600850watch *(int *)0x12345678(to watch a 4-byte region at the specified address)watch a*b + c/ddelete 1 2 3delete 1-3 5-6disable 1 2 3enable delete 1 2
3.7.2. Continuing and Stepping¶
continue[orc] to resume program execution after a stopfinishto continue running until just after function in the selected stack frame returnsuntil[oru] to continue execution until the program counter is greater than the address of the jump (very useful to continue execution until loop exit)advance LOCATIONto continue running the program up to the given locationstepi[orsi] to execute one machine instructionnexti[orni] to execute one machine instruction stepping over function calls
3.7.3. Signals¶
info signals[orinfo handle] to print a table of all the kinds of signals and how gdb has been told to handle each onehandle SIGNAL [KEYWORDS...]to change the way gdb handles signal SIGNAL. The keywords can be:nostopto not stop your program when this signal happensstopto stop your program when this signal happens. This implies theprintkeyword as wellprintto print a message when this signal happensnoprintto not mention the occurrence of the signal at all. This implies thenostopkeyword as wellpass[ornoignore] to allow your program to see this signalnopass[orignore] to not allow your program to see this signal
3.7.3.1. Examples¶
handle SIGUSR1
3.8. Running Programs Backward¶
reverse-continue[orrc] to start executing in reverse beginning at the point where your program last stoppedreverse-stepito reverse-execute one machine instructionreverse-nextito reverse-execute a single instruction in reverse (called functions are “un-executed” atomically)reverse-finishto take you to the point where the current function was called
3.9. Examining the Stack¶
3.9.1. Backtraces¶
backtrace [N][orbt] to print a backtrace of the entire stackbacktrace full [N]to print the values of the local variables also
3.9.2. Selecting a Frame¶
frame N[orf] to select frame number N (frame zero is the innermost (currently executing) frame)frame STACKADDRto select the frame at address STACKADDRup [N]to move N frames up the stack. N defaults to1down [N]to move N frames down the stack. N defaults to1select-frame [N]to silently select a stack frame
3.9.3. Information About a Frame¶
frame[orf] to print a brief description of the currently selected stack frameinfo frameto print a verbose description of the selected stack frameinfo argsto print the arguments of the selected frameinfo localsto print the local variables of the selected frame
3.10. Examining Data¶
print [/F] [EXPR][orinspect] to evaluate and print the value of an expression of the language your program is written in. You can choose a different format by specifying/F, where F is a letter specifying the format. If you omit EXPR, gdb displays the last value again (useful to inspect the same value in an alternative format)explore ARGto explore either an expression (in the source language), or a type visible in the current context of the program being debugged
3.10.1. Examples¶
p filename[0] = 'a'p strlen(filename)explore arrexplore struct ComplexStruct
3.10.2. Program Variables¶
3.10.2.1. Examples¶
p 'f2.c'::x(to refer to static variables)p i@entry(to get value of variableiat the time the function got called)
3.10.3. Artificial Arrays¶
3.10.3.1. Examples¶
p *array@lenp/x (short[])0x12345678(to create artificial arrays)
3.10.4. Examining Memory¶
x[/NFU] ADDRto examine memory. N, F, and U are all optional parameters that specify how much memory to display and how to format it
3.10.4.1. Examples¶
x/3uh 0x54320(to display three halfwords (h) of memory, formatted as unsigned decimal integers (u), starting at address0x54320)x/4xw $sp(to print the four words (w) of memory above the stack pointer ($sp) in hexadecimal (x))x/5i $pc-6x/s *environ(to get the address of the first environment variable (or, alternatively, EBP of main + 16/32 bytes))
3.10.5. Automatic Display¶
display[/FMT] EXPRto add the expression EXPR to the list of expressions to display each time your program stops. FMT is used to specify a display format
3.10.5.1. Examples¶
display/i $pc
3.10.6. Value History¶
To refer to any previous value, use $ followed by the value’s
history number.
show valuesto print the last ten values in the value history
3.10.6.1. Examples¶
p *$
3.10.7. Convenience Variables¶
gdb provides convenience variables that you can use within gdb to hold
on to a value and refer to it later. Convenience variables are prefixed
with $.
3.10.7.1. Examples¶
set $foo = *object_ptr
3.10.8. Convenience Functions¶
3.10.8.1. Examples¶
print $_isvoid ($v)p $_strlen($s)
3.10.9. Registers¶
info registersto print the names and values of all registers except floating-point and vector registersinfo all-registers
gdb has four “standard” register names that are available (in
expressions) on most machines—whenever they do not conflict with an
architecture’s canonical mnemonics for registers. The register names
$pc and $sp are used for the program counter register and the
stack pointer. $fp is used for a register that contains a pointer to
the current stack frame, and $ps is used for a register that
contains the processor status.
3.10.9.1. Examples¶
set $sp += 4
3.10.10. Copy Between Memory and a File¶
dump [FORMAT] memory FILE START_ADDR END_ADDRto dump the contents of memory from START_ADDR to END_ADDR, or the value of expr, to FILE in the given formatrestore FILE [binary] BIAS START ENDto restore the contents of file FILE into memory
3.10.11. How to Produce a Core File from Your Program¶
generate-core-file [FILE][orgcore] to produce a core dump of the inferior process
3.10.12. Character Sets¶
set charset CHARSETto set the current host and target character sets to CHARSET. If you typeset charset <TAB><TAB>, gdb will list the names of the character sets that can be used for both host and target
3.10.13. Search Memory¶
find [/SN] START_ADDR, +LEN|END_ADDR, VAL1 [, VAL2, ...]to search memory for the sequence of bytes specified by VAL1, VAL2, etc. The search begins at address START_ADDR and continues for either LEN bytes or through to END_ADDR inclusive
3.11. Altering Execution¶
3.11.1. Assignment to Variables¶
set is really the same as print except that the expression’s
value is not printed and is not put in the value history.
3.11.1.1. Examples¶
print x=4whatis widthset var width=47set {int}0x83040 = 4
3.11.2. Continuing at a Different Address¶
jump LOCATION[orj] to resume execution at location. Thejumpcommand does not change the current stack frame, or the stack pointer, or the contents of any memory location or any register other than the program counter
3.11.2.1. Examples¶
jump *0x4028ba
3.11.3. Giving your Program a Signal¶
signal SIGNALto resume execution where your program is stopped, but immediately give it the signal SIGNAL. The signal can be the name or the number of a signal
3.11.3.1. Examples¶
signal SIGINTsignal 2
3.11.4. Returning from a Function¶
return [EXPR]to discard the selected stack frame (and all frames within it). If you wish to specify a value to be returned, give that value as EXPR
3.11.4.1. Examples¶
return -1