TExcelTAD
Home › Reverse Engineering & Binary Analysis › gdb in Batch Mode: Breakpoints, Registers, Memory, Stepping

gdb in Batch Mode: Breakpoints, Registers, Memory, Stepping

Static analysis tells you what code could do; a debugger shows what it does with a particular input: the argument that really arrives in rdi, the value a loop computes, the moment a global changes. For reverse engineering the debugger is a measuring instrument. You stop the program at a chosen place, read registers and memory, step a few instructions, and compare with your hypothesis. gdb is the standard debugger on Linux, and its batch mode (gdb -batch -ex ... or a command file) makes measurements repeatable and scriptable, which is how every gdb session in this course runs. The assembly course's Debugging with gdb covers interactive use; this lesson is about using it on a binary without source or debug information, in a lab.

Definitions

  • Breakpoint: break score (by symbol), break *0x1149 (by address; in a PIE, gdb relocates addresses given before run), tbreak (one-shot). A software breakpoint replaces the first byte of an instruction with int3 (0xCC).
  • Watchpoint: watch *(int *)&counter stops when the value at that address changes, using the CPU's debug registers (hardware watchpoint): ideal for "who writes this variable?". Without debug info, gdb needs the cast to know the size.
  • Inspecting: p/x $rdi (a register in hex), info registers, x/s addr (a string), x/8xb addr (8 bytes in hex), x/4gx addr (four 8-byte words), x/5i $pc (the next 5 instructions).
  • Stepping: stepi (si, one instruction, entering calls), nexti (ni, one instruction, stepping over calls), finish (run until the current function returns), continue.
  • Batch mode: gdb -q -batch -x script.gdb --args ./prog arg1 runs the commands and exits; output can be saved and diffed.

A measurement session

The session builds a small scoring function (3 points per a, 1 for any other letter, counting characters in a global), compiles it without debug information, and uses a gdb command file to check the analyst's reading of it: the argument string, the first instructions, the global changing, and the return value.

bash · try it yourself
cat > score.c <<'SRC'
#include <stdio.h>
int counter = 0;
int score(const char *w) {
    int s = 0;
    for (; *w; w++) { s += (*w == 'a') ? 3 : 1; counter++; }
    return s;
}
int main(int argc, char **argv) {
    const char *w = argc > 1 ? argv[1] : "banana";
    printf("%s -> %d\n", w, score(w));
    return 0;
}
SRC
gcc -O1 score.c -o score
cat > measure.gdb <<'GDB'
set disassembly-flavor intel
break score
run
echo == argument in rdi\n
p/x $rdi
x/s $rdi
x/8xb $rdi
echo == the first instructions\n
x/5i $pc
echo == who writes counter?\n
watch *(int *)&counter
continue
continue
delete 2
echo == return value\n
finish
p $rax
continue
GDB
gdb -q -batch -x measure.gdb --args ./score cabbage 2>&1 | grep -vE '^\[|libthread|^
  

Breakpoint 1 at 0x1149
Breakpoint 1, 0x000055ea1db58149 in score ()
== argument in rdi
$1 = 0x7fffdd21fe59
0x7fffdd21fe59:	"cabbage"
0x7fffdd21fe59:	0x63	0x61	0x62	0x62	0x61	0x67	0x65	0x00
== the first instructions
=> 0x55ea1db58149 <score>:	endbr64
   0x55ea1db5814d <score+4>:	movzx  eax,BYTE PTR [rdi]
   0x55ea1db58150 <score+7>:	test   al,al
   0x55ea1db58152 <score+9>:	je     0x55ea1db5817a <score+49>
   0x55ea1db58154 <score+11>:	mov    edx,0x0
== who writes counter?
Hardware watchpoint 2: *(int *)&counter
Hardware watchpoint 2: *(int *)&counter
Old value = 0
New value = 1
0x000055ea1db5816c in score ()
Hardware watchpoint 2: *(int *)&counter
Old value = 1
New value = 2
0x000055ea1db5816c in score ()
== return value
0x000055ea1db5819e in main ()
$2 = 11
cabbage -> 11

Each command answers one question:

  • p/x $rdi, x/s, x/8xb: the first argument is a pointer to the string cabbage, with its bytes and the terminating 00. The calling convention (System V) said it would be in rdi; the debugger confirms.
  • x/5i $pc: the function starts by loading the first byte and testing it for zero: the for (; *w; ...) condition.
  • The watchpoint stops twice, at the same instruction, as counter goes 0 → 1 → 2: one increment per character. The stop address minus the function's start (0x...816c - 0x...8149 = 0x23) says the write happens 35 bytes into score, at score+35, which you can then find in a static listing.
  • finish and p $rax: the function returns 11 for cabbage (c, b, b, g, e = 5 × 1, a, a = 2 × 3). Measured, not guessed: the hypothesis "3 per a, 1 otherwise" holds.

Run-time addresses (0x55ea1db5... here) change every run because of ASLR; the offsets inside functions (<score+35>) don't, so write offsets in your notes.

Stepping through a decision

Stepping is how you follow a branch you can't decide statically. The second session stops at score, runs into the loop's entry test (test al, al, the *w condition) one instruction at a time, printing the flags after each, so you see which way the jump will go before it happens.

bash · try it yourself
cat > score.c <<'SRC'
#include <stdio.h>
int counter = 0;
int score(const char *w) {
    int s = 0;
    for (; *w; w++) { s += (*w == 'a') ? 3 : 1; counter++; }
    return s;
}
int main(int argc, char **argv) {
    const char *w = argc > 1 ? argv[1] : "banana";
    printf("%s -> %d\n", w, score(w));
    return 0;
}
SRC
gcc -O1 score.c -o score
gdb -q -batch -ex 'set disassembly-flavor intel' -ex 'break score' -ex 'run ""' \
  -ex 'stepi' -ex 'x/i $pc' -ex 'stepi' -ex 'x/i $pc' -ex 'stepi' -ex 'p $eflags' -ex 'x/i $pc' \
  -ex 'stepi' -ex 'x/i $pc' -ex 'kill' ./score 2>&1 | grep -E '=>|^\
  

 | sed -E 's/0x[0-9a-f]{9,} //'
=> <score+4>:	movzx  eax,BYTE PTR [rdi]
=> <score+7>:	test   al,al
$1 = [ PF ZF IF ]
=> <score+9>:	je     0x55c407a0417a <score+49>
=> <score+49>:	mov    edx,0x0

With an empty string, movzx eax, BYTE PTR [rdi] loads the terminator 0, test al, al sets ZF (eflags shows ZF), and the next stepi lands on the instruction after the loop: the je was taken and the loop body never ran. kill ends the program in the middle; in batch mode gdb would otherwise kill it on exit anyway.

How debugging is detected, and why it matters

Programs can tell when they are being debugged: a breakpoint is a 0xCC byte in their code, a debugger is the process's tracer (visible as TracerPid in /proc/self/status), single-stepping is slow, and ptrace can be attached only once. Malware and copy-protection use these facts to change behaviour under analysis, and analysts must notice. The Anti-Debugging lesson shows the checks and how to see them. On the defender side, an unexpected ptrace attach to a production process is itself a security event: EDRs and auditd rules (-a always,exit -S ptrace) record it.

Doing it safely and reproducibly

  • Only debug in the lab what you are allowed to run: a debugger executes the program for real.
  • Keep the command file with your notes; batch sessions are evidence anyone can re-run.
  • Hardening against debugging of your own production services: kernel.yama.ptrace_scope = 1 or higher (only parents may attach; Ubuntu's default is 1), no debuggers on production hosts, and PR_SET_DUMPABLE 0 for processes holding secrets.

Pitfalls

  • AT&T syntax by default: add set disassembly-flavor intel (the course's sessions do).
  • No debug info means no types: print counter fails or guesses; cast explicitly (*(int *)&counter) and use $rax, $rdi.
  • finish in a function without a frame pointer still works (gdb uses .eh_frame), but in a function that was reached by a tail call (jmp), it returns to the caller of the function that made the jump, which has no frame of its own any more.
  • Breakpoints change the code bytes: a program that checksums its own code sees them (use hardware breakpoints, hbreak, in that case).
  • ASLR: never compare absolute run-time addresses between runs; compare offsets.

Practice

1. Which gdb command shows the next four instructions at the current position?

x/4i $pc.

2. You want to know which function writes a global flag at offset 0x4014 of a PIE. Without symbols, how do you set the watchpoint?

Start the program (starti), compute the address from the load base shown by info proc mappings (base + 0x4014), then watch *(int *)ADDRESS and continue; the stop shows the writing instruction.

3. Predict score("aaa") and check it with the first session by changing the argument.

9 (three a at 3 points each); the watchpoint fires three times if you keep continuing.

Test yourself

How does a software breakpoint work on x86?

  1. It pauses the CPU clock
  2. The debugger replaces the first byte of the instruction with int3 (0xCC)
  3. It changes the page permissions
  4. It uses a system call

Which command stops when a variable changes value?

  1. break
  2. watch
  3. finish
  4. x/s

What is the difference between stepi and nexti?

  1. None
  2. stepi enters called functions, nexti steps over calls
  3. nexti runs to the end of the function
  4. stepi works only with debug info

Why should notes record <score+35> rather than the run-time address?

  1. Offsets are shorter
  2. ASLR moves the program each run, while offsets inside functions stay the same
  3. gdb requires it
  4. Run-time addresses are secret