gdb

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

GDB

GDB

Purpose

用途

Walk agents through GDB sessions from first launch to advanced workflows: crash diagnosis, reverse debugging, remote debugging, and multi-thread inspection.
引导Agent完成从首次启动到高级工作流的GDB会话:崩溃诊断、反向调试、远程调试以及多线程检查。

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)
  • "我的程序出现段错误/崩溃——该如何调试?"
  • "如何设置满足条件X的断点?"
  • "如何在GDB中检查内存/变量?"
  • "如何调试远程嵌入式目标?"
  • "GDB显示
    ??
    帧/无源代码"
  • "如何确定性地重放一个bug?"(记录/重放)

Workflow

工作流程

1. Prerequisite: compile with debug info

1. 前提:编译时包含调试信息

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
).
始终使用
-g
(GCC/Clang)进行编译。大多数情况下使用
-Og
-O0
以获得最佳可调试性。
bash
gcc -g -Og -o prog main.c
对于发布版本:使用
-g -O2
编译,并保留带有符号的二进制文件(可通过
objcopy
单独剥离符号)。

2. Start GDB

2. 启动GDB

bash
gdb ./prog                          # load binary
gdb ./prog core                     # load with core dump
gdb -p 12345                        # attach to running process
gdb --args ./prog arg1 arg2         # pass arguments
gdb -batch -ex 'run' -ex 'bt' ./prog  # non-interactive (CI)
bash
gdb ./prog                          # 加载二进制文件
gdb ./prog core                     # 加载二进制文件及核心转储
gdb -p 12345                        # 附加到运行中的进程
gdb --args ./prog arg1 arg2         # 传递参数
gdb -batch -ex 'run' -ex 'bt' ./prog  # 非交互式模式(CI环境)

3. Essential commands

3. 核心命令

CommandShortcutEffect
run [args]
r
Start the program
continue
c
Resume after break
next
n
Step over (source line)
step
s
Step into
nexti
ni
Step over (instruction)
stepi
si
Step into (instruction)
finish
Run to end of current function
until N
Run to line N
return [val]
Force return from function
quit
q
Exit GDB
命令快捷键作用
run [args]
r
启动程序
continue
c
断点后恢复执行
next
n
单步跳过(源代码行)
step
s
单步进入
nexti
ni
单步跳过(指令级)
stepi
si
单步进入(指令级)
finish
运行到当前函数结束
until N
运行到第N行
return [val]
强制从函数返回
quit
q
退出GDB

4. Breakpoints and watchpoints

4. 断点与观察点

gdb
break main                          # break at function
break file.c:42                     # break at line
break *0x400abc                     # break at address
break foo if x > 10                 # conditional break
tbreak foo                          # temporary breakpoint (fires once)
rbreak ^mylib_.*                    # regex breakpoint on all matching functions

watch x                             # watchpoint: break when x changes
watch *(int*)0x601060               # watch memory address
rwatch x                            # break when x is read
awatch x                            # break on read or write

info breakpoints                    # list all breakpoints
delete 3                            # delete breakpoint 3
disable 3                           # disable without deleting
enable 3
gdb
break main                          # 在函数处设置断点
break file.c:42                     # 在指定文件的第42行设置断点
break *0x400abc                     # 在指定地址设置断点
break foo if x > 10                 # 设置条件断点
tbreak foo                          # 设置临时断点(仅触发一次)
rbreak ^mylib_.*                    # 对所有匹配正则的函数设置断点

watch x                             # 设置观察点:当x改变时触发断点
watch *(int*)0x601060               # 监控指定内存地址
rwatch x                            # 当x被读取时触发断点
awatch x                            # 当x被读取或写入时触发断点

info breakpoints                    # 列出所有断点
delete 3                            # 删除编号为3的断点
disable 3                           # 禁用编号为3的断点(不删除)
enable 3

5. Inspect state

5. 检查程序状态

gdb
print x                             # print variable
print/x x                           # print in hex
print *ptr                          # dereference pointer
print arr[0]@10                     # print 10 elements of array
display x                           # auto-print x on every stop
undisplay 1

info locals                         # all local variables
info args                           # function arguments
info registers                      # all CPU registers
info registers rip rsp rbp          # specific registers
x/10wx 0x7fff0000                   # examine 10 words at address
x/s 0x400abc                        # examine as string
x/i $rip                            # examine current instruction

backtrace                           # call stack (bt)
bt full                             # bt + local vars
frame 2                             # switch to frame 2
up / down                           # move up/down the stack
gdb
print x                             # 打印变量值
print/x x                           # 以十六进制打印变量值
print *ptr                          # 解引用指针
print arr[0]@10                     # 打印数组的前10个元素
display x                           # 每次暂停时自动打印x的值
undisplay 1

info locals                         # 查看所有局部变量
info args                           # 查看函数参数
info registers                      # 查看所有CPU寄存器
info registers rip rsp rbp          # 查看指定寄存器
x/10wx 0x7fff0000                   # 查看指定地址处的10个字
x/s 0x400abc                        # 以字符串形式查看指定地址内容
x/i $rip                            # 查看当前指令

backtrace                           # 查看调用栈(缩写bt)
bt full                             # 查看调用栈及局部变量
frame 2                             # 切换到编号为2的栈帧
up / down                           # 在栈帧间上下移动

6. Multi-thread debugging

6. 多线程调试

gdb
info threads                        # list threads
thread 3                            # switch to thread 3
thread apply all bt                 # backtrace all threads
thread apply all bt full            # full bt all threads
set scheduler-locking on            # pause other threads while stepping
gdb
info threads                        # 列出所有线程
thread 3                            # 切换到编号为3的线程
thread apply all bt                 # 查看所有线程的调用栈
thread apply all bt full            # 查看所有线程的完整调用栈
set scheduler-locking on            # 单步执行时暂停其他线程

7. Reverse debugging (record/replay)

7. 反向调试(记录/重放)

Record requires
target record-full
or
target record-btrace
(Intel PT):
gdb
undefined
记录功能需要使用
target record-full
target record-btrace
(Intel PT):
gdb
undefined

Software record (slow but universal)

Software record (slow but universal)

record # start recording run
record # start recording run

... trigger the bug ...

... trigger the bug ...

reverse-continue # go back to last break reverse-next # step backwards reverse-step reverse-finish
reverse-continue # go back to last break reverse-next # step backwards reverse-step reverse-finish

Intel Processor Trace (fast, hardware)

Intel Processor Trace (fast, hardware)

target record-btrace pt run
target record-btrace pt run

view instruction history

view instruction history

record instruction-history
undefined
record instruction-history
undefined

8. Remote debugging with gdbserver

8. 使用gdbserver进行远程调试

On target:
bash
gdbserver :1234 ./prog
在目标设备上:
bash
gdbserver :1234 ./prog

Or attach:

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.
gdbserver :1234 --attach 5678

在主机上:

```bash
gdb ./prog
(gdb) target remote 192.168.1.10:1234
(gdb) break main
(gdb) continue
对于交叉编译:在主机上使用
aarch64-linux-gnu-gdb

9. Common problems

9. 常见问题

SymptomCauseFix
No symbol table
Binary not compiled with
-g
Recompile with
-g
??
frames in backtrace
Missing debug info or stack corruptionInstall debuginfo package; check for stack smash
Cannot access memory at address
Null dereference / freed memoryCheck pointer before deref; use ASan
SIGABRT
in backtrace
abort()
or assertion failure
Go up frames to find the assertion
GDB hangs on
run
Binary waiting for inputRedirect stdin:
run < /dev/null
Breakpoint in wrong placeOptimiser moved codeCompile with
-Og
; or use
nexti
症状原因解决方法
No symbol table
二进制文件未使用
-g
编译
使用
-g
重新编译
调用栈中出现
??
缺少调试信息或栈损坏安装调试信息包;检查栈溢出
Cannot access memory at address
空指针解引用/内存已释放解引用前检查指针;使用ASan
调用栈中出现
SIGABRT
调用了
abort()
或断言失败
向上查看栈帧找到断言位置
GDB在
run
时挂起
程序等待输入重定向标准输入:
run < /dev/null
断点位置错误优化器移动了代码使用
-Og
编译;或使用
nexti

10. GDB init file (~/.gdbinit)

10. GDB初始化文件(~/.gdbinit)

gdb
set history save on
set history size 1000
set print pretty on
set print array on
set print array-indexes on
set pagination off
set confirm off
For a command cheatsheet, see references/cheatsheet.md. For pretty-printers and Python scripting, see references/scripting.md.
gdb
set history save on
set history size 1000
set print pretty on
set print array on
set print array-indexes on
set pagination off
set confirm off
如需命令速查表,请查看references/cheatsheet.md。 如需美化打印机和Python脚本相关内容,请查看references/scripting.md

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
  • 加载核心文件请使用
    skills/debuggers/core-dumps
  • LLDB相关工作流请使用
    skills/debuggers/lldb
  • 在需要调试前捕捉bug请使用
    skills/runtimes/sanitizers
  • 了解
    -g
    参数详情请使用
    skills/compilers/gcc