TExcelTAD
Home › x86-64 Assembly › Debugging with gdb

Debugging with gdb

Assembly bugs rarely produce helpful messages: the program prints the wrong number, loops forever, or dies with SIGSEGV. A debugger lets you stop the program at any instruction and inspect registers, flags and memory. On Linux that is gdb. It cannot run inside these playgrounds, so this lesson shows typical sessions as text and uses runnable examples for the kinds of failures you will be hunting.

Preparing the program

Assemble with debug information and link as usual:

bash
nasm -f elf64 -g -F dwarf prog.asm -o prog.o
ld prog.o -o prog
gdb ./prog

A few settings make gdb much nicer for assembly (put them in ~/.gdbinit):

text
set disassembly-flavor intel
layout asm          # a window with the instructions around rip
layout regs         # plus the registers

The essential commands

Command Meaning
break _start / b print_uint stop when execution reaches a label
break *0x401010 stop at an address
run / r start the program
stepi / si execute one instruction (enters calls)
nexti / ni execute one instruction (steps over calls)
continue / c run until the next breakpoint
info registers / i r rax rbx show registers
p/x $rax, p/d $rcx print a register in hex / decimal
x/8xg $rsp examine 8 quadwords (g) in hex (x) at rsp
x/s &message examine memory as a string
x/5i $rip disassemble the next 5 instructions
p $eflags the flags, decoded: [ ZF PF ]
display/i $pc show the current instruction after every step
bt backtrace (works best with frame pointers)

A sample session

Imagine the bubble sort from the Sorting lesson prints garbage. You stop at the comparison and step through one iteration:

text
(gdb) break _start.compare
Breakpoint 1 at 0x401019
(gdb) run
Breakpoint 1, 0x0000000000401019 in _start.compare ()
(gdb) x/7dg &scores
0x402000:  29  10  14  37
0x402020:  13   5  22
(gdb) p $rcx
$1 = 0
(gdb) si
(gdb) si
(gdb) p $rax
$2 = 29
(gdb) p $rdx
$3 = 10
(gdb) si
(gdb) p $eflags
$4 = [ PF AF IF ]        # no CF, no ZF: 29 > 10, the jbe will not jump

The workflow is always the same: form a hypothesis ("the swap writes to the wrong address"), stop just before the suspicious instruction, and check registers and memory against what you expect.

Reading a crash

When a program receives SIGSEGV, gdb stops at the faulting instruction. The address in the register you dereferenced usually tells the story — 0 is a null pointer, a small number is an integer used as a pointer, and a huge number is often uninitialized data:

nasm · try it yourself
section .data
values: dq 10, 20, 30

section .text
global _start
_start:
    mov rbx, [values]           ; BUG: loads the VALUE 10, not the address
    mov rdi, [rbx + 8]          ; reads address 18 -> crash
    call print_uint

    mov eax, 60
    xor edi, edi
    syscall

; ---- print_uint: print rdi as an unsigned decimal number and a newline ----
print_uint:
    mov rax, rdi            ; rax = the number to convert
    sub rsp, 32             ; room for up to 20 digits and a newline
    lea rsi, [rsp + 31]     ; fill the buffer from its end
    mov byte [rsi], 10      ; the newline is the last character
    mov ecx, 10
.next_digit:
    xor edx, edx            ; the dividend is rdx:rax, so clear rdx
    div rcx                 ; rax = quotient, rdx = remainder (0..9)
    add dl, '0'             ; remainder -> ASCII digit
    dec rsi
    mov [rsi], dl           ; store it in front of the previous one
    test rax, rax
    jnz .next_digit         ; repeat until the quotient is 0
    lea rdx, [rsp + 32]
    sub rdx, rsi            ; rdx = number of bytes to print
    mov eax, 1              ; write(1, rsi, rdx)
    mov edi, 1
    syscall
    add rsp, 32
    ret
Program terminated with signal SIGSEGV (11)
text
(gdb) run
Program received signal SIGSEGV, Segmentation fault.
0x0000000000401008 in _start ()
(gdb) x/i $pc
=> 0x401008 <_start+8>:	mov    rdi,QWORD PTR [rbx+0x8]
(gdb) p $rbx
$1 = 10                  # a "pointer" with the value 10: that's data, not an address

The fix is mov rbx, values (or lea rbx, [values]): load the address, not the contents.

Breakpoints in the code: int3

The int3 instruction is what gdb inserts to implement breakpoints. You can also write it into your code yourself: under gdb execution stops there, and without a debugger the program ends with SIGTRAP. That makes it a handy "this should never be reached" marker:

nasm · try it yourself
section .text
global _start
_start:
    mov edi, 5
    call print_uint
    int3                        ; a hard-coded breakpoint
    mov edi, 6                  ; not reached without a debugger
    call print_uint
    mov eax, 60
    xor edi, edi
    syscall

; ---- print_uint: print rdi as an unsigned decimal number and a newline ----
print_uint:
    mov rax, rdi            ; rax = the number to convert
    sub rsp, 32             ; room for up to 20 digits and a newline
    lea rsi, [rsp + 31]     ; fill the buffer from its end
    mov byte [rsi], 10      ; the newline is the last character
    mov ecx, 10
.next_digit:
    xor edx, edx            ; the dividend is rdx:rax, so clear rdx
    div rcx                 ; rax = quotient, rdx = remainder (0..9)
    add dl, '0'             ; remainder -> ASCII digit
    dec rsi
    mov [rsi], dl           ; store it in front of the previous one
    test rax, rax
    jnz .next_digit         ; repeat until the quotient is 0
    lea rdx, [rsp + 32]
    sub rdx, rsi            ; rdx = number of bytes to print
    mov eax, 1              ; write(1, rsi, rdx)
    mov edi, 1
    syscall
    add rsp, 32
    ret
5
Program terminated with signal SIGTRAP (5)

Print debugging

When no debugger is at hand (as in these playgrounds), printing registers is the low-tech alternative. The print_hex helper from the Registers lesson preserves no registers, so wrap it: save everything you care about, print, restore. Here a macro dumps a register with a label, without disturbing the program's state:

nasm · try it yourself
%macro dump 1                   ; print "<name> = 0x..." for a register
    push rax
    push rcx
    push rdx
    push rsi
    push rdi
    push r11
    mov rdi, %1                 ; read the register before anything changes
    push rdi
    section .rodata
    %%name: db %str(%1), " = "
    %%len   equ $ - %%name
    section .text
    mov eax, 1
    mov edi, 1
    mov rsi, %%name
    mov edx, %%len
    syscall
    pop rdi
    call print_hex
    pop r11
    pop rdi
    pop rsi
    pop rdx
    pop rcx
    pop rax
%endmacro

section .text
global _start
_start:
    mov rax, 0xDEAD
    mov rcx, 3
    shl rax, cl
    dump rax                    ; inspect the intermediate values
    dump rcx
    add rax, rcx
    dump rax

    mov eax, 60
    xor edi, edi
    syscall

; print_hex: print rdi as 16 hex digits with a 0x prefix and a newline
print_hex:
    sub rsp, 32
    mov word [rsp], '0x'        ; the prefix (NASM stores '0' first, then 'x')
    mov ecx, 16                 ; 16 hex digits
.digit:
    rol rdi, 4                  ; bring the top 4 bits to the bottom
    mov eax, edi
    and eax, 0xF                ; isolate one hex digit (0-15)
    cmp eax, 10
    jb .decimal
    add eax, 'A' - '0' - 10     ; 10-15 -> 'A'-'F'
.decimal:
    add eax, '0'
    mov rdx, 18
    sub rdx, rcx                ; position 2..17 in the buffer
    mov [rsp + rdx], al
    dec ecx
    jnz .digit
    mov byte [rsp + 18], 10     ; newline
    mov eax, 1                  ; write(1, rsp, 19)
    mov edi, 1
    mov rsi, rsp
    mov edx, 19
    syscall
    add rsp, 32
    ret
rax = 0x000000000006F568
rcx = 0x0000000000000003
rax = 0x000000000006F56B

%str(%1) turns the macro argument into a string, so the output names the register.

Other useful tools

  • strace ./prog — every system call with its arguments and result (great for "why does my write print nothing?").
  • objdump -d -M intel ./prog — check what NASM actually generated.
  • valgrind — reports reads of uninitialized memory and invalid addresses.
  • gdb's record and reverse-stepi — step backwards to see how a register got its wrong value.

Test yourself

Which gdb command executes exactly one instruction but steps over calls?

  1. stepi
  2. nexti
  3. continue
  4. finish

What does x/4xg $rsp show?

  1. 4 bytes at rsp
  2. 4 quadwords at rsp in hexadecimal
  3. The value of rsp
  4. 4 instructions

A crash happens at mov rdi, [rbx + 8] and rbx = 10. What is the most likely bug?

  1. rbx contains a value where an address was expected
  2. The stack is misaligned
  3. rdi is callee-saved
  4. The instruction is invalid