English | 简体中文
Applicable scenarios:
- The program crashed during runtime, and the cause of the crash needs to be located.
- The program is behaving abnormally, and its execution flow needs to be traced.
- I want to observe the memory state and variable changes during program execution.
What problems can this article help you solve?
- How do I get a coredump and analyze it when the program crashes?
- How to deduce the root cause from the scene of the collapse?
- How to actively debug a program that is running or about to run?
The difference between dynamic debugging and static analysis:
- Dynamic debugging: Observe the execution process while the program is actually running.
- Static analysis: Analyzing binary files directly without running the program.
- The two complement each other: dynamic debugging solves "where the crash occurred," while static analysis solves "what is the program's logic?"
A coredump file is a memory dump file generated by the operating system when a program crashes. It contains the memory state, register values, stack information, etc. at the time of the crash and is an important tool for debugging the cause of program crashes.
Necessary conditions:
- A serious error has occurred in the program (such as segmentation fault, bus fault, etc.).
- The system coredump function is enabled.
- There is enough disk space
- Target directory with write permissions
Common triggering situations:
- Accessing a null pointer or wild pointer
- Memory out-of-bounds access
- Stack overflow
- Division by zero error
- Actively calling the abort() function
ulimit -c
If it displays 0, it means it is disabled and needs to be set to unlimited.
View all restrictions:
ulimit -a
Temporary settings (valid for the current session):
ulimit -c unlimited
Check target directory permissions:
ls -ld /tmp
Ensure the program has write permissions.
View process limitations:
cat /proc/<pid>/limits
Some programs may capture crash signals and handle them automatically:
// 示例:程序捕获了SIGSEGV信号
signal(SIGSEGV, custom_handler);
strace -f -o strace.log ./your_program
Ubuntu/Debian:
sudo service apport status
CentOS/RHEL:
sudo service abrt status
In a traditional Linux environment, when an application crashes, the system might generate a core file containing a memory image of the application at the time of the crash. The kernel parameter kernel.core_pattern determines how these core files are generated. WSL's design has its own unique features:
| Design Features | illustrate |
|---|---|
| core_pattern points to the pipe | WSL by default sets kernel.core_pattern to a pipe command, meaning core data is not written directly to disk files but is instead handled by a specific program (such as /wsl-capture-crash ). |
| Core file generation is disabled by default. | By setting ulimit -c 0 , WSL disables the generation of traditional core files within containers by default. |
The advantages of this design:
- Enhance system security: Prevent core files from unintentionally recording sensitive information (such as passwords, keys, etc.) and storing it on the disk.
- Optimize the development experience: Pipe crash information to specific handlers for formatting, analysis, or integration with Windows-side debugging tools.
Security Warning: /proc/sys/kernel/core_pattern is a sensitive file that requires close monitoring. If it can be written to arbitrarily, especially in a container environment, it could be exploited to achieve container escape or privilege escalation.
WSL's core dump mechanism:
内核检测到段错误 → 准备生成核心转储
↓
检查 core_pattern → 发现要发送给 /wsl-capture-crash
↓
显示消息 → 内核固定显示 "Segmentation fault (core dumped)"
↓
实际处理 → WSL 的 CaptureCrash 服务接收并处理崩溃信息
↓
文件系统层面 → 没有生成传统的 core 文件
Why does it display "core dumped"?
- The kernel's message text is hard-coded; it neither knows nor cares about the actual dump target.
- From the kernel's perspective, it did indeed "dump" the kernel information—only through a pipe rather than a file.
- WSL has chosen to retain this traditional message, even though the actual mechanism is different.
Traditional Linux vs WSL behavior comparison:
| Behavior | Traditional Linux | WSL |
|---|---|---|
| Core dump target | document | Pipeline → Specialized Services |
| Limited by ulimit -c | yes | Unaffected by traditional document limitations |
| Generate core file? | generate | No generation |
Therefore, in WSL, Segmentation fault (core dumped) should be understood as "a segmentation fault has occurred and the crash information has been captured", rather than "a core dump file has been generated".
In this WSL configuration, generating a traditional core dump file requires modifying the core dump configuration.
echo "core-%e-%t-%p" | sudo tee /proc/sys/kernel/core_pattern
The changes have been successfully confirmed.
cat /proc/sys/kernel/core_pattern
Method 2: Permanent modification (This method is ineffective for WSL reboots and is applicable to traditional Linux distributions).
Edit the sysctl configuration:
sudo vim /etc/sysctl.conf
Add the following line:
kernel.core_pattern=core-%e-%t-%p
kernel.core_uses_pid=1
Apply configuration immediately:
sudo sysctl -p
echo "|/wsl-capture-crash %t %E %p %s" | sudo tee /proc/sys/kernel/core_pattern
Format instructions:
| placeholder | meaning |
|---|---|
| %p | Process ID (PID) |
| %t | Dump time (UNIX timestamp) |
| %e | Executable filename |
Complete operation process example:
# 1. 检查当前限制
ulimit -c
# 输出: 0
# 2. 检查core_pattern
cat /proc/sys/kernel/core_pattern
# 输出: |/wsl-capture-crash %t %E %p %s
# 3. 启用coredump
echo "core-p%p-t%t-%e" | sudo tee /proc/sys/kernel/core_pattern
ulimit -c unlimited
# 4. 确认设置
ulimit -c
# 输出: unlimited
# 5. 编译并运行程序
gcc -g -o bubble bubble.c
./bubble
# 6. 查看生成的core文件
ls -la core-*
# 输出: core-p12345-t1623456789-bubble
# 7. 用GDB分析
gdb ./bubble core-<pid>
(gdb) bt
# 添加调试信息
gcc -g -o program program.c
# 添加堆栈保护
gcc -fstack-protector-all -o program program.c
# 启用所有警告
gcc -Wall -Wextra -o program program.c
Use valgrind to check for memory problems:
valgrind --tool=memcheck ./program
Using AddressSanitizer:
gcc -fsanitize=address -g -o program program.c
gdb <程序路径> <coredump文件路径>
Example:
gdb /usr/bin/myapp /tmp/core-myapp-12345-1623456789
(gdb) bt # 显示调用栈(backtrace简写)
(gdb) where # 同bt
(gdb) bt full # 显示调用栈和局部变量
(gdb) info registers # 显示所有寄存器
(gdb) info registers # 简写: i r
Pay special attention to rip (the instruction pointer register in x86-64), which points to the execution address at the time of the crash.
(gdb) info proc mappings
Output example:
0x555555554000 0x555555555000 0x1000 0x0 /home/musk/work/deliberate/algorithm/insertion
0x555555555000 0x555555556000 0x1000 0x1000 /home/musk/work/deliberate/algorithm/insertion
0x555555556000 0x555555557000 0x1000 0x2000 /home/musk/work/deliberate/algorithm/insertion
...
0x7ffff7dc9000 0x7ffff7deb000 0x22000 0x0 /usr/lib/x86_64-linux-gnu/libc-2.31.so
0x7ffff7fcf000 0x7ffff7fd0000 0x1000 0x0 /usr/lib/x86_64-linux-gnu/ld-2.31.so
Normal address mode:
- Program code segment:
0x55555555xxxx - Library code segment:
0x7ffff7xxxxxxor0x7ffffxxxxxxx - Stack:
0x7ffffffxxxxx
(gdb) print variable_name # 打印变量值
(gdb) p variable_name # print的简写
(gdb) print *pointer # 打印指针指向的值
(gdb) print array[5] # 打印数组元素
(gdb) print $rax # 打印寄存器值
View all local variables in the current stack frame:
(gdb) info locals
To view the parameters of the current function:
(gdb) info args
x`命令格式:`x/<重复次数><格式><大小> <地址>
Format instructions:
| Format | meaning |
|---|---|
| x | hexadecimal |
| d | Decimal |
| t | binary |
| c | character |
| s | String |
| i | Assembly instructions |
Size description:
| size | meaning |
|---|---|
| b | byte (1 byte) |
| h | Half a character (2 bytes) |
| w | 4 bytes |
| g | Large characters (8 bytes) |
Common examples:
(gdb) x/10wx &variable # 以十六进制查看10个字
(gdb) x/20cb buffer # 查看20个字节(字符形式)
(gdb) x/s str # 查看字符串
(gdb) x/g $rsp # 查看栈指针指向的内容
(gdb) x/10i $pc # 查看当前指令附近10条指令
(gdb) x/20xg $rsp # 查看栈内容(20个巨字)
(gdb) x/10wx 0x7fffffffe110 # 查看指定地址的10个字
(gdb) backtrace # 显示调用栈,简写: bt
(gdb) backtrace full # 显示调用栈和局部变量
(gdb) frame <编号> # 切换到指定栈帧,简写: f
(gdb) up # 向上移动栈帧(调用者方向)
(gdb) down # 向下移动栈帧(被调用者方向)
(gdb) info frame # 显示当前帧信息,简写: i f
(gdb) info locals # 查看当前栈帧的局部变量,简写: i lo
(gdb) info args # 查看当前函数的参数,简写: i ar
(gdb) info threads # 显示所有线程,简写: i th
(gdb) thread <线程ID> # 切换到指定线程
(gdb) thread apply all bt # 查看所有线程堆栈
(gdb) disassemble # 反汇编当前函数
(gdb) disas main # 反汇编指定函数
(gdb) info signals # 显示信号信息,简写: i sig
Create the debug script debug_core.sh :
#!/bin/
# debug_core.sh
if [ $# -ne 2 ]; then
echo "用法: $0 <程序路径> <coredump路径>"
exit 1
fi
PROGRAM=$1
COREFILE=$2
gdb -q $PROGRAM $COREFILE << EOF
set pagination off
bt
info registers
thread apply all bt
quit
EOF
How to use:
chmod +x debug_core.sh
./debug_core.sh ./bubble core-12345
The core idea is to locate the problem from macroscopic symptoms to microscopic code errors, and to narrow down the scope of the problem by observing memory status and program behavior.
Using the insertion.c program as an example, this demonstrates every step from crash to root cause location.
Compilation preparation (with AddressSanitizer):
gcc -g -fsanitize=address -fno-omit-frame-pointer -o insertion insertion.c
(gdb) r
Program received signal SIGSEGV, Segmentation fault
Observation: Program crashes, segmentation fault inference: memory access violation (accessing memory it shouldn't have accessed).
Checklist:
- Mapping check: Is the address within the segment listed in
info proc mappings? - Pattern check: Does the address conform to the system memory layout pattern?
- Symbol check: Can GDB resolve the function name?
- Numerical check: Does the address contain suspicious data patterns?
- Consistency check: Whether it is consistent with other register/stack values.
(gdb) bt
#0 0x00000003555550db in ?? ()
(gdb) info registers
rip 0x3555550db 0x3555550db
Observation: Call stack exception, RIP points to strange address 0x3555550db Inference: The return address is corrupted, indicating that the stack memory was modified unexpectedly.
(gdb) info proc mappings
0x555555554000 0x555555555000 0x1000 0x0 /home/musk/work/deliberate/algorithm/insertion
Observation: The normal code segment is in the range of 0x55555555xxxx , but RIP points to 0x3555550db
正常程序地址: 0x55555555558a (在映射范围内)
异常的 rip: 0x00000003555550db (不在任何映射范围内)
^^^^^^^^^^
异常的高位部分
Inference: The control flow is disrupted, most likely due to a stack overflow or buffer overflow.
(gdb) info locals
arr = {10277, -402295808, -1772, -2125934455, 41156}
n = 32767
Key finding: Local variable values were corrupted.
arris not the original{98, 11, 45, 3, 65}nis not the expected5, but32767
Inference: The stack memory was accidentally written to, corrupting local variables.
(gdb) info frame
rip = 0x55555555558a in main (insertion.c:30)
(gdb) list
30 {
Observation: The crash occurs at the beginning of the main function (line 30). Inference: The problem occurs during the function call, not in the current line.
gcc -g -fsanitize=address -o insertion insertion.c
(gdb) r
Strategy: Use AddressSanitizer to automatically detect memory errors . Result: Accurately located the stack buffer underflow in insertion.c:19 (accessing arr[-1] ).
| parameter | effect |
|---|---|
-g |
Includes debugging information, making bug reports clearer. |
-fsanitize=address |
Enable AddressSanitizer instrumentation to automatically detect memory errors. |
-fno-omit-frame-pointer |
Preserving frame pointers facilitates debugging and stack backtracking. |
段错误
↓
内存访问违规
↓
异常rip地址 → 控制流/返回地址被破坏
↓
局部变量值异常 → 栈内存被意外修改
↓
崩溃在main开始 → 问题发生在之前的函数调用
↓
AddressSanitizer报告 → 精确定位到数组越界访问
| Phenomenon | infer |
|---|---|
| Local variables are corrupted | Stack corruption |
| Return address error | Control flow hijacked |
| These two phenomena occur simultaneously | Buffer overflow |
- GDB basic commands:
bt,info,xare used for initial location. - Memory detection tools: AddressSanitizer, Valgrind for precise location
- Observation point:
watchfor changes in key variables.
- Knowing it's an "insertion" procedure → I speculate it's insertion sort.
- Common insertion sort errors → Cycle boundary issues, index out of bounds
- Stack buffer underflow → accessed
arr[-1]
- Deducing the cause from the phenomenon : There is a definite memory access error behind the anomaly.
- Delving deeper : From crash symptoms → memory state → code location → specific error
- Combination of tools : GDB for initial positioning + professional tools for precise positioning
- Integrating domain knowledge : Algorithm characteristics help predict error types
This systematic troubleshooting method can be applied to debugging various memory-related problems. The key is to establish a reasoning chain from the phenomenon to the cause and to make good use of tools to verify each inference.
# 内存检查(追踪未初始化值的来源)
valgrind --tool=memcheck --track-origins=yes ./insertion
# 内存泄漏检查(完整报告)
valgrind --leak-check=full ./insertion
Note : This chapter explains how to actively debug a program. It covers setting breakpoints, single-stepping, observing variable changes, and tracing the execution flow.
Chapter 2 has fully explained the usage of commands such as
bt,info locals,x,info registers, andinfo proc mappings. This chapter will fully explain breakpoint-related commands (break, watch, etc.) and other active debugging commands. It will also list all viewing commands for quick reference. For specific usage details, please refer to the corresponding sections in Chapter 2.
The -g option must be added during compilation to preserve debugging information:
gcc -g -o program program.c
Alternatively, ensure that -g is included in the Makefile: makefile
CFLAGS = -g -Wall
file program
# 输出应该包含: "with debug_info"
Or use readelf:
readelf -S program | grep debug
# 调试可执行文件
gdb ./program
# 调试运行中的进程
gdb -p <进程ID>
# 调试 core dump 文件(详见第二章)
gdb ./program core
(gdb) run [参数] # 运行程序,简写: r
(gdb) start # 开始执行并停在main函数
(gdb) continue # 继续运行,简写: c
(gdb) next # 执行下一行(不进入函数),简写: n
(gdb) step # 执行下一行(进入函数),简写: s
(gdb) finish # 运行到当前函数返回,简写: fin
(gdb) until <行号> # 运行到指定行
(gdb) quit # 退出GDB,简写: q
(gdb) break main # 在main函数设置断点,简写: b
(gdb) break 15 # 在第15行设置断点
(gdb) break file.c:20 # 在指定文件的第20行设置断点
(gdb) break function # 在指定函数设置断点
(gdb) break *0x400512 # 在内存地址设置断点
(gdb) tbreak main # 设置临时断点(触发后自动删除),简写: tb
(gdb) break func if i>5 # i>5时断点触发
(gdb) break file.c:20 if i == 5
(gdb) condition 2 i > 10 # 为断点2设置条件
(gdb) ignore 2 5 # 忽略断点2的前5次触发
(gdb) info breakpoints # 查看所有断点,简写: i b
(gdb) delete <断点编号> # 删除断点,简写: d
(gdb) disable <断点编号> # 禁用断点,简写: dis
(gdb) enable <断点编号> # 启用断点,简写: en
(gdb) clear # 清除当前行断点
(gdb) clear function # 清除指定函数的断点
(gdb) commands 2 # 为断点2设置命令列表
> p i
> p arr[i]
> c
> end
(gdb) save breakpoints breakpoints.txt
(gdb) source breakpoints.txt
(gdb) watch variable # 变量改变时暂停
(gdb) watch *(int*)0x1234 # 监视内存地址
(gdb) rwatch variable # 变量被读取时暂停
(gdb) awatch variable # 变量被读或写时暂停
(gdb) list # 显示当前行附近的代码,简写: l
(gdb) list function # 显示指定函数的代码
(gdb) list file.c:15 # 显示指定文件的指定行
(gdb) list 10,20 # 显示10-20行的代码
| Order | use | For detailed usage, see |
|---|---|---|
print variable |
Print variable values | Chapter 2, Section 2.5 |
print *pointer |
Print the value pointed to by the pointer | Chapter 2, Section 2.5 |
print array[5] |
Print array elements | Chapter 2, Section 2.5 |
print $rax |
Print register values | Chapter 2, Section 2.5 |
display variable |
Automatically display each time it stops | Chapter 2, Section 2.5 |
info display |
View the automatically displayed list | Chapter 2, Section 2.5 |
undisplay <编号> |
Cancel automatic display | Chapter 2, Section 2.5 |
whatis variable |
View variable types | Chapter 2, Section 2.5 |
ptype variable |
View detailed type information | Chapter 2, Section 2.5 |
(gdb) p/x variable # 十六进制显示
(gdb) p/d variable # 十进制显示
(gdb) p/t variable # 二进制显示
(gdb) p/c variable # 字符显示
(gdb) p/a variable # 地址显示
| Order | use | For detailed usage, see |
|---|---|---|
x/10wx &variable |
View 10 characters in hexadecimal | Chapter 2, Section 2.6 |
x/20cb buffer |
View 20 bytes (in character format) | Chapter 2, Section 2.6 |
x/s ptr |
View string | Chapter 2, Section 2.6 |
x/i $pc |
View current commands | Chapter 2, Section 2.6 |
| Order | use | For detailed usage, see |
|---|---|---|
backtrace / bt |
Show the call stack | Chapter 2, Sections 2.2 and 2.7 |
frame <编号> / f |
Select stack frame | Chapter 2, Section 2.7 |
up |
Move stack frame up | Chapter 2, Section 2.7 |
down |
Move stack frame down | Chapter 2, Section 2.7 |
info frame / if |
Display current frame information | Chapter 2, Section 2.7 |
info locals / i lo |
Display local variables | Chapter 2, Section 2.5 |
info args / i ar |
Display function parameters | Chapter 2, Section 2.5 |
(gdb) info threads # 查看所有线程,简写: i th
(gdb) thread <线程ID> # 切换到指定线程,简写: t
(gdb) thread apply all bt # 对所有线程执行bt命令
(gdb) thread apply all command # 对所有线程执行指定命令
(gdb) handle SIGSEGV stop # 当收到SIGSEGV时停止
(gdb) info signals # 查看信号处理设置,简写: i sig
Target machine:
gdbserver :1234 ./program
Development machine:
(gdb) target remote 目标IP:1234
(gdb) continue
gdb -tui ./program # 启动文本用户界面
Switching TUI in GDB:
(gdb) tui enable # 启用TUI
(gdb) layout src # 显示源代码布局
(gdb) layout asm # 显示汇编布局
(gdb) layout regs # 显示寄存器布局
(gdb) shell # 执行shell命令,简写: sh
(gdb) set logging on # 开启日志
(gdb) set logging off # 关闭日志
(gdb) set logging file gdb.log # 设置日志文件
(gdb) define mycmd # 定义用户命令
> print variable1
> print variable2
> backtrace
> end
(gdb) mycmd # 执行自定义命令
(gdb) source file # 执行命令文件,简写: so
(gdb) show commands # 显示历史命令
(gdb) record # 开始执行记录
(gdb) reverse-step # 反向单步执行
(gdb) skip -gfi /usr/include/*.h # 跳过标准库头文件
(gdb) skip -gfi /usr/lib/*.so # 跳过标准库
#include <stdio.h>
#define ARRAY_COUNT(arr) (sizeof(arr) / sizeof(arr[0]))
int arr[] = {9, 23, 86, 12, 34};
int main(int argc, char const *argv[])
{
int temp = 0;
for (int i = 0; i < ARRAY_COUNT(arr)-1; i++)
{
for (int j = 0; i < ARRAY_COUNT(arr)-i-1; j++)
{
if (arr[j] > arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
for (int i = 0; i < ARRAY_COUNT(arr); i++)
{
printf("arr[%d] = %d\n", i, arr[i]);
}
return 0;
}
Compiled by:
gcc -g -o bubble bubble.c
Start GDB:
gdb ./bubble
Debugging operations:
# 设置断点在可能出问题的地方
(gdb) break bubble.c:15
# 运行程序
(gdb) run
# 监视变量变化
(gdb) display j
(gdb) display i
(gdb) display n
# 单步调试
(gdb) next
(gdb) step
# 检查 arr[j] 和 arr[j+1] 是否在有效范围内
(gdb) print j
(gdb) print j+1
(gdb) print n # 数组长度
# 查看这些位置的值
(gdb) print arr[j]
(gdb) print arr[j+1]
# 继续执行
(gdb) continue
# 退出
(gdb) quit
| category | Full command | abbreviation | Function Description |
|---|---|---|---|
| Basic debugging | run | r | Run the program |
| quit | q | Exit GDB | |
| help | h | View help | |
| list | l | Show source code | |
| p | Print expression value | ||
| next | n | Single-step execution (without entering functions) | |
| step | s | Single-step execution (entering the function) | |
| continue | c | Continue execution | |
| finish | fin | Execution continues until the current function returns. | |
| Breakpoint Management | break | b | Set breakpoints |
| delete | d | Delete breakpoint | |
| disable | dis | Disable breakpoints | |
| enable | en | Enable breakpoints | |
| info breakpoints | ib | Show all breakpoints | |
| clear | cl | Clear breakpoints | |
| tbreak | tb | Set a temporary breakpoint | |
| condition | cond | Set breakpoint conditions | |
| commands | com | Set breakpoint trigger command | |
| Stack and Frame | backtrace | bt | Show the call stack |
| frame | f | Select stack frame | |
| up | Move stack frame up | ||
| down | Move stack frame down | ||
| info frame | if | Display current frame information | |
| info locals | i lo | Display local variables | |
| info args | i ar | Display function parameters | |
| Variables and memory | display | disp | Display the expression each time it stops |
| undisplay | undisp | Cancel display | |
| watch | wa | Set up monitoring points | |
| rwatch | rwa | Set up monitoring points | |
| awatch | awa | Set up read/write monitoring points | |
| x | Check memory | ||
| set variable | set var | Set variable value | |
| whatis | wh | Display variable type | |
| ptype | pt | Display detailed type information | |
| Advanced debugging | thread | t | Thread operations |
| info threads | i th | Show all threads | |
| catch | cat | Set capture point | |
| signal | sig | Send signal | |
| return | ret | Forced function return | |
| jump | j | Jump to the specified location | |
| attach | att | Attach to running process | |
| detach | det | Separation process | |
| handle | han | Set signal processing | |
| Information Inquiry | info registers | ir | Display registers |
| info program | i prog | Display program status | |
| info signals | i sig | Display signal information | |
| info functions | i fun | Display function information | |
| info variables | i var | Display variable information | |
| Other practical applications | shell | sh | Execute shell command |
| define | def | Define user commands | |
| source | so | Execute command file | |
| show commands | sh com | Show command history | |
| record | rec | Start Execution Record | |
| reverse-step | rs | Reverse single-step execution |
gdb ./insertion
(gdb) run
(gdb) bt # 当出现segmentation fault时
(gdb) b main # 在main函数设断点
(gdb) r # 运行程序
(gdb) n # 单步执行
(gdb) p variable # 查看变量
(gdb) bt # 查看调用栈
(gdb) c # 继续执行
# 1. 启动调试
gdb ./program
# 2. 设置断点
(gdb) b main
(gdb) b suspicious_function
# 3. 运行程序
(gdb) r
# 4. 单步调试
(gdb) n
(gdb) s
# 5. 检查变量
(gdb) p variable
(gdb) i locals
# 6. 检查调用栈
(gdb) bt
# 7. 检查内存
(gdb) x/10wx address
# 8. 继续执行或重新运行
(gdb) c
(gdb) run
(gdb) x/10wx addr # 查看10个字(16进制)
(gdb) x/20cb buf # 查看20个字节(字符)
(gdb) x/s str # 查看字符串
(gdb) x/10wx 0x7fffffffe110 # 查看10个word(16进制)
(gdb) x/20cb buffer # 查看20个字节(字符形式)
(gdb) x/s ptr # 查看字符串
(gdb) x/i $pc # 查看当前指令
(gdb) b func if i>5 # i>5时断点触发
(gdb) commands 2 # 为断点2设置命令
> p i
> c
> end
(gdb) b main # 在main函数设置断点
(gdb) b 15 # 在第15行设置断点
(gdb) b file.c:20 # 在指定文件的第20行设置断点
(gdb) b *0x400512 # 在内存地址设置断点
(gdb) b func if i == 5 # 条件断点
# 条件调试
(gdb) commands 2 # 为断点2设置命令列表
> p i
> p arr[i]
> c
> end
(gdb) condition 2 i > 10 # 为断点2设置条件
(gdb) ignore 2 5 # 忽略断点2的前5次触发
# 监视点使用
(gdb) watch variable # 变量改变时暂停
(gdb) watch *(int*)0x1234 # 监视内存地址
(gdb) rwatch variable # 变量被读时暂停
(gdb) awatch variable # 变量被读或写时暂停
# 保存断点配置
(gdb) save breakpoints breakpoints.txt
(gdb) source breakpoints.txt
# 自定义命令
(gdb) define mycmd
> p $arg0
> p $arg1
> end
(gdb) mycmd var1 var2
# 开启日志
(gdb) set logging on
(gdb) set logging file gdb.log
(gdb) set logging off
# 远程调试
(gdb) target remote :1234 # 连接到远程gdbserver
# 跳过库函数
(gdb) n # 执行下一行,但不进入函数
(gdb) s # 进入函数内部(会进入printf)
(gdb) finish # 执行完当前函数,返回到调用处
(gdb) skip -gfi /usr/include/*.h
(gdb) skip -gfi /usr/lib/*.so