GDB Cheatsheet


[:  :]

Here are some notes and things I’ve referenced for gdb.

I highly recommend using the gef extension for gdb: https://github.com/hugsy/gef

Unsorted

Basics

Here are some of the most basic gdb commands.

Start the program with arguments

gdb --args ./myprogram -f myfile
CommandDescription
startiStart at the first instruction
stepiStep 1 assembly instruction
break *0x400000Set a breakpoint on address 0x400000
continueContinue execution, will stop at breakpoints
vmmap(gef only) Show process memory map
hexdump byte –size 256 0x400000(gef only) See a hex dump of bytes at a address 0x400000
p *objectShow details of object
search-pattern 0x41414141(gef only) Search for bytes \x41\x41\x41\x41 (“AAAA”) in memory

More Info:

Remote GDB

You can connect to programs on different machines using remote GDB. You can also use it to connect to local programs that support remote GDB like QEMU.

Commands

Adapted this guide from a cheatsheet I found but lost the link to Related cheat sheet: gef

More important commands have !

Startup

CommandDescription
gdb -helpprint startup help, show switches
gdb object! normal debug
gdb object core! core debug (must specify core file)
gdb object pidattach to running process
gdbuse file command to load object

Help

CommandDescription
help! list command classes
help runninglist commands in one command class
help runbottom-level help for a command “run”
help infolist info commands (running program state)
help info linehelp for a particular info command
help showlist show commands (gdb state)
help show commandsspecific help for a show command

Breakpoints

CommandDescription
break main! set a breakpoint on a function
break 101! set a breakpoint on a line number
break basic.c:101! set breakpoint at file and line (or function)
break *0xaddress! Break on an address
info breakpoints! show breakpoints
delete 1! delete a breakpoint by number
deletedelete all breakpoints (prompted)
cleardelete breakpoints at current line
clear functiondelete breakpoints at function
clear linedelete breakpoints at line
disable 2turn a breakpoint off, but don’t remove it
enable 2turn disabled breakpoint back on
tbreak functionline
commands break-no … endset gdb commands with breakpoint
ignore break-no countignore bpt N-1 times before activation
condition break-no exprbreak only if condition (expr/expression) is true
condition 2 i == 20example: break on breakpoint 2 if i equals 20
watch expressionset software watchpoint on variable
info watchpointsshow current watchpoints

Running the program

CommandDescription
set step-mode on! This stops at the first instruction of a function
starti! Go to the first instruction to execute
run! run the program with current arguments
run args redirection! run with args and redirection
set args args…set arguments for run
show argsshow current arguments to run
cont! continue the program
step! single step the program; step into functions
stepi! step to next instruction
step countsingle step \fIcount\fR times
next! step but step over functions
next countnext \fIcount\fR times
CTRL-C! actually SIGINT, stop execution of current program
attach process-id! attach to running program
detach! detach from running program
finish! finish current function’s execution
killkill current executing program

Stack backtrace

CommandDescription
x/100x $sp! print 100 bytes from the stack pointer
bt! print stack backtrace
frameshow current execution position
upmove up stack trace (towards main)
downmove down stack trace (away from main)
info locals! print automatic variables in frame
info argsprint function parameters

Browsing source

CommandDescription
list 101! list 10 lines around line 101
list 1,10! list lines 1 to 10
list main! list lines around function
list basic.c:main! list from another file basic.c
list -! list previous 10 lines
list *0x22e4list source at address
cd dirchange current directory to \fIdir\fR
pwdprint working directory
search regexprforward current for regular expression
reverse-search regexprbackward search for regular expression
dir dirnameadd directory to source path
dirreset source path to nothing
show directoriesshow source path

Browsing Data

CommandDescription
print expression! print expression, added to value history
print/x expressionR! print in hex
print array[i]@countartificial array - print array range
print $print last value
print *$->nextprint thru list
print $1print value 1 from value history
print ::gxforce scope to be global
print ‘basic.c’::gxglobal scope in named file (>=4.6)
print/x &mainprint address of function
x/countFormatSize addresslow-level examine command
x/x &gxprint gx in hex
x/4wx &mainprint 4 longs at start of \fImain\fR in hex
x/gf &gd1print double
help xshow formats for x
info locals! print local automatics only
info functions regexpprint function names
info variables regexpprint global variable names
ptype name! print type definition
whatis expressionprint type of expression
set variable = expression! assign value
display expressiondisplay expression result at stop
undisplaydelete displays
info displayshow displays
show valuesprint value history (>= gdb 4.0)
info historyprint value history (gdb 3.5)

Object File Manipulation

CommandDescription
file objectload new file for debug (sym+exec)
filediscard sym+exec file info
symbol-file objectload only symbol table
exec-file objectspecify object to run (not sym-file)
core-file corepost-mortem debugging

Signal Control

CommandDescription
info signalsprint signal setup
handle signo actionsset debugger actions for signal
handle INT printprint message when signal occurs
handle INT noprintdon’t print message
handle INT stopstop program when signal occurs
handle INT nostopdon’t stop program
handle INT passallow program to receive signal
handle INT nopassdebugger catches signal; program doesn’t
signal signocontinue and send signal to program
signal 0continue and send no signal to program

Machine-level Debug

CommandDescription
info registersprint registers sans floats
info all-registersprint all registers
print/x $pcprint one register
stepisingle step at machine level
sisingle step at machine level
nextisingle step (over functions) at machine level
nisingle step (over functions) at machine level
display/i $pcprint current instruction in display
x/x &gxprint variable gx in hex
info line 22print addresses for object code for line 22
info line *0x2c4eprint line number of object code at address
x/10i maindisassemble first 10 instructions in \fImain\fR
disassemble addrdissassemble code for function around addr

History Display

CommandDescription
show commandsprint command history (>= gdb 4.0)
info editingprint command history (gdb 3.5)
ESC-CTRL-Jswitch to vi edit mode from emacs edit mode
set history expansion onturn on c-shell like history
break class::memberset breakpoint on class member. may get menu
list class::memberlist member in class
ptype classprint class members
print *thisprint contents of this pointer
rbreak regexpruseful for breakpoint on overloaded member name

Miscellaneous

CommandDescription
define command … enddefine user command
*(gdb) RETURNrepeat last command
*(gdb) shell command argsexecute shell command
*(gdb) source fileload gdb commands from file
*(gdb) quitquit gdb

GDB Scripting

The following example is from https://stackoverflow.com/questions/4060565/how-to-script-gdb-with-python-example-add-breakpoints-run-what-breakpoint-d

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class DebugPrintingBreakpoint(gdb.Breakpoint):
    debugging_IDs = frozenset({37, 153, 420})
    def stop(self):
        top = gdb.newest_frame()
        someVector = top.read_var('aVectorVar')
        # Access the begin() & end() pointer of std::vector in GNU Standard C++ lib
        first = someVector['_M_impl']['_M_start']
        last = someVector['_M_impl']['_M_finish']
        values = []
        while first != last:
            values.append(int(first.dereference()['intID']))
            first = first + 1
        if not set(values) & debugging_IDs:
            return False # skip: none of the items we're looking for can be found by ID in the vector on the stack
        print("Found other accompanying IDs: {}".format(values))
        return True # drop to gdb's prompt
# Ensure shared libraries are loaded already
gdb.execute("start")
# Set our breakpoint, which happens to reside in some shared lib, hence the "start" previously
DebugPrintingBreakpoint("source.cpp:42")
gdb.execute("continue")

You can execute this script from gdb’s prompt like this:

(gdb) source script.py

Or from the command-line:

$ gdb --command script.py ./executable.elf

Events

According to the Events doc, this is an event handler:

1
2
3
4
5
6
7
8
def exit_handler (event):
    print ("event type: exit")
    if hasattr (event, 'exit_code'):
        print ("exit code: %d" % (event.exit_code))
    else:
        print ("exit code not available")

gdb.events.exited.connect (exit_handler)

The types of events are

The stop_signal and exit_code Event attributes may have changed. They don’t seem to work anymore.

I got the stop hook writing to a file, as well as other hooks that update “gdb_status.txt”. The gdb.SignalEvent thing doesn’t seem to fire though…

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
def signal_stop_handler (event):
    if (isinstance (event, gdb.StopEvent)):
        print ("event type: stop")
        with open("gdb_status.txt", "w") as f:
            f.write("Stopped\n")
        f.close()
    if (isinstance (event, gdb.SignalEvent)):
        print ("stop reason: signal")
        print ("stop signal: %s" % (event.stop_signal))
        if ( event.inferior_thread is not None) :
            print ("thread num: %s" % (event.inferior_thread.num))

gdb.events.stop.connect(signal_stop_handler)

TODO: Update this with real info hahah