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 從公開儲存庫中收錄這些內容。

檢舉或申請下架