Using GDB Cheat Sheet

The following were done on magi, which is running GCC: (GNU) 3.2.2 20030222 on Red Hat Linux 3.2.2-5

Creating assembler source from C source

gcc t2.c
// produces t2.s -- assembly code generated by the c compiler

To run this code, do the following:

as -o t2.o t2.s
// produces t2.o -- an object module ready for linking
gcc t2.o
// produces a.out -- an executable, which you can run as ./a.out
gdb a.out
// debugs a.out

Running gdb

The following information is from http://www.gnu.org/manual/gdb-5.1.1/html_mono/gdb.html

Showing a listing of your program

disas main
// shows assembly listing for main - don't need to have generated debugging info

Setting breakpoints

b *main
// set breakpoint at the start of main
b *main+55
// set breakpoint at this address in your assembly code (as shown by disas)
b *_start
// set breakpoint at as close as I can find to the real beginning of the program
i b
// show breakpoints currently set
dis 1
// disable breakpoint 1
dis 1-3
// disable breakpoints 1 through 3
ena 1
// (re)enable breakpoint 1

Running and Continuing your program

r
// (Re)start your program from the beginning
si
// step one assembler instruction
c
// continue the program. Goes until the next breakpoint or the end of the program.

Displaying registers and using automatic displays

i reg
// show the values stored in the registers
display/i $pc
// automatically display the program counter after every step instruction
display $esp
// automatically display the stack pointer after every step instruction
display $ebp
// automatically display the frame pointer after every step instruction
i display
// show the automatic displays currently set
dis dis 1
// disable automatic display number 1
ena dis 1
// (re)enable automatic display number 1

Displaying memory

x/48xw $esp (or just x/48 $esp)
// show 48 words of memory starting at the address held in the stack pointer
// x/ means show data
// 48 means display 48 units
// x means display values in hex
// w means units are "words" (4 bytes)
// $esp is the address currently stored in the %esp register

Suppose the value at the address currently held in the stack pointer (call it addr0) is another address (call it addr1), and you would like to see the value stored at addr1 do:

x/48xw *(int*)$esp
// show 48 words of memory at the address held in the stack pointer, i.e., dereference the stack pointer and display memory at the place where it points
// * means dereference a pointer
// (int*) means the next value is a pointer to an int. You must have this cast to keep gdb from giving an "Attempt to dereference a generic pointer." error

Displaying the stack

backtrace