Gdb

mohitmishra786/low-level-dev-skills/skills/debuggers/gdb

作者 mohitmishra786bdc58472fa9f无许可证253 个星标收录于 2026年10月9日更新于 2026年10月9日仓库3个月前更新

GDB debugger skill for C/C++ programs. Use when starting a GDB session, setting breakpoints, stepping through code, inspecting variables, debugging crashes, using reverse debugging (record/replay), remote debugging with gdbserver, or loading core dumps. Activates on queries about GDB commands, segfaults, hangs, watchpoints, conditional breakpoints, pretty-printers, Python GDB scripting, or multi-threaded debugging.

AI 生成的概览

指导代理使用 GDB 调试 C/C++ 程序,涵盖断点、崩溃诊断、反向调试与远程调试。

功能
该技能提供针对 C/C++ 程序的 GDB 会话结构化指引。内容包括带调试信息编译、启动 GDB、常用单步与状态查看命令、断点与观察点、多线程调试、基于 record/replay 的反向调试、通过 gdbserver 的远程调试,以及常见故障现象与修复方法。它还指向命令速查表以及 pretty-printer 与 Python 脚本编写的参考文档。
适用场景
当 C/C++ 程序崩溃、段错误、挂起或缺少符号,需要用 GDB 排查时使用。也适用于设置断点或观察点、查看变量、内存、寄存器或线程、确定性地重放缺陷、调试远程或嵌入式目标,以及加载核心转储。
运行要求
不附带脚本,只有说明文档和两份参考文档。使用所述流程需要安装 GDB、C/C++ 工具链(如 GCC 或 Clang);远程调试还需要目标端的 gdbserver 以及主机与目标之间的网络访问。

GDB

Purpose

Walk agents through GDB sessions from first launch to advanced workflows: crash diagnosis, reverse debugging, remote debugging, and multi-thread inspection.

Triggers

  • "My program segfaults / crashes — how do I debug it?"
  • "How do I set a breakpoint on condition X?"
  • "How do I inspect memory / variables in GDB?"
  • "How do I debug a remote embedded target?"
  • "GDB shows ?? frames / no source"
  • "How do I replay a bug deterministically?" (record/replay)

Workflow

1. Prerequisite: compile with debug info

Always compile with -g (GCC/Clang). Use -Og or -O0 for most debuggable code.

bash
gcc -g -Og -o prog main.c

For release builds: use -g -O2 and keep the binary with symbols (strip separately with objcopy).

2. Start GDB

bash
gdb ./prog                          # load binarygdb ./prog core                     # load with core dumpgdb -p 12345                        # attach to running processgdb --args ./prog arg1 arg2         # pass argumentsgdb -batch -ex 'run' -ex 'bt' ./prog  # non-interactive (CI)

3. Essential commands

CommandShortcutEffect
run [args]rStart the program
continuecResume after break
nextnStep over (source line)
stepsStep into
nextiniStep over (instruction)
stepisiStep into (instruction)
finishRun to end of current function
until NRun to line N
return [val]Force return from function
quitqExit GDB

4. Breakpoints and watchpoints

gdb
break main                          # break at functionbreak file.c:42                     # break at linebreak *0x400abc                     # break at addressbreak foo if x > 10                 # conditional breaktbreak foo                          # temporary breakpoint (fires once)rbreak ^mylib_.*                    # regex breakpoint on all matching functions
watch x                             # watchpoint: break when x changeswatch *(int*)0x601060               # watch memory addressrwatch x                            # break when x is readawatch x                            # break on read or write
info breakpoints                    # list all breakpointsdelete 3                            # delete breakpoint 3disable 3                           # disable without deletingenable 3

5. Inspect state

gdb
print x                             # print variableprint/x x                           # print in hexprint *ptr                          # dereference pointerprint arr[0]@10                     # print 10 elements of arraydisplay x                           # auto-print x on every stopundisplay 1
info locals                         # all local variablesinfo args                           # function argumentsinfo registers                      # all CPU registersinfo registers rip rsp rbp          # specific registersx/10wx 0x7fff0000                   # examine 10 words at addressx/s 0x400abc                        # examine as stringx/i $rip                            # examine current instruction
backtrace                           # call stack (bt)bt full                             # bt + local varsframe 2                             # switch to frame 2up / down                           # move up/down the stack

6. Multi-thread debugging

gdb
info threads                        # list threadsthread 3                            # switch to thread 3thread apply all bt                 # backtrace all threadsthread apply all bt full            # full bt all threadsset scheduler-locking on            # pause other threads while stepping

7. Reverse debugging (record/replay)

Record requires target record-full or target record-btrace (Intel PT):

gdb
# Software record (slow but universal)record                              # start recordingrun# ... trigger the bug ...reverse-continue                    # go back to last breakreverse-next                        # step backwardsreverse-stepreverse-finish
# Intel Processor Trace (fast, hardware)target record-btrace ptrun# view instruction historyrecord instruction-history

8. Remote debugging with gdbserver

On target:

bash
gdbserver :1234 ./prog# Or attach:gdbserver :1234 --attach 5678

On host:

bash
gdb ./prog(gdb) target remote 192.168.1.10:1234(gdb) break main(gdb) continue

For cross-compilation: use aarch64-linux-gnu-gdb on the host.

9. Common problems

SymptomCauseFix
No symbol tableBinary not compiled with -gRecompile with -g
?? frames in backtraceMissing debug info or stack corruptionInstall debuginfo package; check for stack smash
Cannot access memory at addressNull dereference / freed memoryCheck pointer before deref; use ASan
SIGABRT in backtraceabort() or assertion failureGo up frames to find the assertion
GDB hangs on runBinary waiting for inputRedirect stdin: run < /dev/null
Breakpoint in wrong placeOptimiser moved codeCompile with -Og; or use nexti

10. GDB init file (~/.gdbinit)

gdb
set history save onset history size 1000set print pretty onset print array onset print array-indexes onset pagination offset confirm off

For a command cheatsheet, see references/cheatsheet.md [blocked]. For pretty-printers and Python scripting, see references/scripting.md [blocked].

Related skills

  • Use skills/debuggers/core-dumps for loading core files
  • Use skills/debuggers/lldb for LLDB-based workflows
  • Use skills/runtimes/sanitizers to catch bugs before needing the debugger
  • Use skills/compilers/gcc for -g flag details

来源与署名

来源:mohitmishra786/low-level-dev-skills位于skills/debuggers/gdb提交bdc5847

许可证: 无许可证

内容归原作者所有。SourceWeft 从公开仓库中收录这些内容。

举报或申请下架