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 beforerun),tbreak(one-shot). A software breakpoint replaces the first byte of an instruction withint3(0xCC). - Watchpoint:
watch *(int *)&counterstops 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 arg1runs 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.
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|^