0%

nginx源码编译并调试,nginx源码使用GDB或者vscode+GDB远程debug源码调试-图文详细

nginx源码编译并调试,nginx源码使用GDB或者vscode+GDB远程debug源码调试-图文详细

克隆项目

1
git clone https://github.com/nginx/nginx.git

进入目录下

1
cd /home/hou/nginx

生成配置

1
auto/configure --prefix=./bin --with-debug --with-cc-opt='-O0 -g'

--with-debug

  • 作用:启用 Nginx 的调试日志功能。

  • 解释

    • 启用后,Nginx 会输出更详细的调试信息到错误日志中(error_log)。

    • 这些信息对于排查问题非常有用,例如请求处理流程、模块加载情况等。

    • 需要在 Nginx 配置文件中设置日志级别为 debug

      1
      error_log /path/to/error.log debug;

  1. --with-cc-opt='-O0 -g'
  • 作用:向 C 编译器(如 GCC)传递额外的编译选项。
  • 解释
    • -O0:禁用编译器优化。
      • -O0 表示不进行任何优化,保留所有调试信息,方便调试。
      • 如果使用 -O2-O3,编译器会优化代码,可能会影响调试(例如变量被优化掉,无法查看)。
    • -g:生成调试信息。
      • 在编译时生成调试符号,这些符号会被 GDB 等调试工具使用。
      • 如果没有 -g,GDB 将无法显示源代码和变量信息。

image-20250123230649305

生成成功

image-20250123230710507

编译

1
make

image-20250123230747317

生成成功

image-20250123230808814

安装

1
make install

image-20250123230834519

image-20250123230843875

可以看到已经生成成功

image-20250123231019988

测试

查看版本

image-20250123231031562

GDB调试

1
gdb ./nginx

image-20250123231104217

设置断点

1
b main

执行打印版本号

1
run -v

单步调试

1
b

image-20250123231244450

退出

image-20250123231848631

vscode+GDB调试

借助开源免费工具调试,一个字爽,不在受license的干扰。

安装code

https://code.visualstudio.com/updates/v1_85

安装好后启动

输入code就可以启动

1
code

打开源码目录

image-20250123232104928

安装插件

image-20250122232620837

添加配置

image-20250123232155655

添加配置文件选择连接远程gdbserver

image-20250123232232408

修改执行路径

image-20250123232310441

image-20250123232352427

配置launch.json如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "by-gdb",
"request": "launch",
"name": "Launch(remote)",
"program": "/home/hou/nginx/bin/sbin/nginx",
"cwd": "${workspaceRoot}",
"remote": {
"enabled": true,
"address": ":2345",
"mode": "remote",
"execfile": "/home/hou/nginx/bin/sbin/nginx"
}
},
{
"type": "by-gdb",
"request": "launch",
"name": "Launch(gdb)",
"program": "${fileBasenameNoExtension}",
"cwd": "${workspaceRoot}"
}
]
}

安装gdbserver

1
sudo yum install gdb-gdbserver

进入nginx执行目录

1
cd /home/hou/nginx/bin/sbin

image-20250123232559818

执行远程调试服务命令

1
gdbserver :2345 nginx -v

看到服务器已经在监听了

image-20250123232619330

设置断点

image-20250123232748628

调试

执行调试

image-20250123232828726

可以看到已经执行到断点处

image-20250123232850931

点击单步调试

image-20250123232912540

可以看到执行到下一步了

image-20250123232927390