浏览 2.2k
在MacOSX上使用VSCode 查阅、调试NGINX代码
NGINX是一款十分流行的开源软件,代码量有17万行。如何从代码学习、研读它成为一个很挑战的问题。如果能够凭借VSCode等调试工具的能力边调试跟踪边学习,效率和效果要好很多。
网上关于用GCC、GDB去编译调试NGINX代码的文章有很多。但是实际配置起来会出现各种各样的问题。
这里经过实际验证把验证的过程总结下来,希望对大家有帮助。
我们先了解下 gcc 与 clang llvm 的关系
gcc和clang 都是编译器。
gcc诞生于GNU,clang和苹果关系更密切一些。
clang 是 llvm的前端,他们共同组成了macOSX上编译套件。
我们不建议使用GCC、GDB在macosx上调试NGINX,而建议使用在macOSX上兼容性更好的的编译套件,
MacOSX上使用GDB还会出现以下问题:
Unable to find Mach task port for process-id 57304: (os/kern) failure (0x5).
(please check gdb is codesigned - see taskgated(8))
如果想彻底解决这个问题,尝试以下方法:
https://sourceware.org/gdb/wiki/PermissionsDarwin
自行下载 https://nginx.org/en/download.html
lldb 和 clang 已经包含在llvm的安装中。
本文章描述的搭建过程使用的版本为:
[zong@BEI-ML-00005205 nginx-codes-learning]$ clang -v
Apple LLVM version 10.0.1 (clang-1001.0.46.4)
Target: x86_64-apple-darwin18.7.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
[zong@BEI-ML-00005205 nginx-codes-learning]$ lldb -v
lldb-1001.0.13.3
Swift-5.0
使用brew search 可以查找是否存在相关的依赖包。
使用brew install 安装相应的依赖包。
编译NGINX的过程封装:https://github.com/zongzw-nginx/vscode-nginx
build-cc.sh中使用intercept-build 作为编译工具,而不是用make 或者 bear make,是因为在OSX上对特定目录下的可以执行文件做了限制,具体可以参考:
https://github.com/rizsotto/Bear#empty-compilation-database-on-os-x--macos-or-fedora
Security extension/modes on different operating systems might disable library preloads. In this case Bear behaves normally, but the result compilation database will be empty. (Please make sure it's not the case when reporting bugs.) Notable examples for enabled security modes are: OS X 10.11 (check with csrutil status | grep 'System Integrity Protection'), and Fedora, CentOS, RHEL (check with sestatus | grep 'SELinux status').
因此,我们使用scan-build 这个编译器的wrapper: https://github.com/rizsotto/scan-build
使用scan-build的model 1即可:
Use compiler wrappers to make actions. The compiler wrappers does run the real compiler and the analyzer. This is the default behaviour, can be enforced with --override-compiler flag.
intercept-build --override-compiler make CC=intercept-cc CXX=intercept-c++ all
顺便可以生成compile_commands.json
C/C++
CodeLLDB
打开VSCode,却换到插件管理 标签页:
点击其中一个插件,在右侧点击install即可安装,点击reload 会自动重启vscode以生效插件。
参考 https://github.com/zongzw-nginx/vscode-nginx 链接中的vscode目录文件
Sourcetrail 是个比较炫的代码查看工具,可以从代码生成针对数据结构、函数、文件等等的视图。
Sourcetrail依赖于compile_commands.json,具体操作步骤为:
填写project名称和保存路径,这里的路径不是源码路径,是Sourcetrail项目文件保存的位置,可以是任何文件目录。
这里我们选择C,使用生成的compile_commands.json 配置此项目。
使用compile_commands.json的方式可以大大节省我们的配置过程,而使用“Empty C Source Group”的方式配置过程很复杂,几乎是不可能的,那需要将nginx的编译过程<nginx source home>/auto/* 重新在Sourcetrail中重新实现一遍。
Select from Compilation Database -> check all
点击Next直到Create,这里的其他选项都采用默认。
点击Create 后Sourcetrail从compile_commands.json中发现144 个源文件。这里源文件的数量取决于配置 NGINX编译过程中选中的模块的数量:
./configure … --with-xxxx_module
详细细节可以参考: https://github.com/zongzw-nginx/woboq-nginx, 这里将woboq集成在docker中一键拉起,文档在链接中比较详细可供参考。