Clang 静态分析工具的使用

来源:互联网 发布:网络论坛系统cms 编辑:程序博客网 时间:2024/05/20 23:03
woogle原创,转载注明出处。
Clang作为LLVM(LowLevel VirtualMachine)编译器框架的前端,可以将C/C++、O-C/O-C++语言编译成为LLVM的中间表达式IR(IntermediateReresentation), 其结构图如下所示:Clang <wbr>静态分析(Static <wbr>Analyzer)工具使用的总结

上面的不是重点,本篇文章的重点是讲Clang静态分析工具的使用,Clang作为前端,最主要的任务是词法分析、语法分析,中间代码生成,到此其基本任务就完成了。源代码通过Clang语法分析后,生成了语法分析树(AST),接下来任务不同就有不同的效果:1、作为编译器前端将AST翻译成为IR;2、作为静态分析工具对AST进行分析。

Clang自己定义了很多Checker,可以通过下面的命令行查出所有的checker:
>clang -cc1 -analyzer-checker-help
当需要对单个源文件进行检测时,使用下面的命令进行检测:
>clang --analyze -Xanalyzer -analyzer-checker= 
package就是上面的所有cheker中的一个,file就是在源文件,例如:a.cpp
这就是最基本的用法,针对一般的单个文件的小程序实用,当需要对大型文件进行分析的时候,就需要用到scan-buid这个自动化脚本,它是由perl语言编写而成的,使用如下:
> scan-build [options] [build options]
下面是一个具体的实例:
>scan-build --use-c++ /usr/bin/clang++--use-analyzer=/usr/bin/clang  -enable-checkeryourself.checker -k make
上面这条指令,--use-c++指定了使用的C++编译器,--use-analyzer指定使用的分析器,-enable-checker指定需要使用到分析器,这个分析器可以是自己编写的分析器,默认情况下scan-build会开启一些核心的checker,可以通过指令查看:
scan-build--use-analyzer=/usr/bin/clang -h
这就会列出所有的checker,其默认开启的是前面会有"+"号,也可以使用-disable-checker关闭默认的checker。
检测完成,可以使用scan-view查看检测的结果。

一般情况下,上述都没有问题,但是在本人测试的时候遇到了问题,发现很多人也遇到同样的问题,在检测完后,出现:
> scan-build --use-c++ /usr/bin/clang++--use-analyzer=/usr/bin/clang  -enable-checkeralpha.NewZero.NewZero -k make
scan-build: Removing directory'/tmp/scan-build-2015-06-29-155436-13426-1' because it contains noreports.
scan-build: No bugs found.
查看一下Makefile:
>cat Makefile
new:new.cpp
clang++ new.cpp -o new
初步看来没有任何错误,但是经过仔细找原因, 官网上有这句话:
scan-build has little or no knowledge about how you build your code. It works by overriding the CC and CXX environment variables to (hopefully) change your build to use a "fake" compiler instead of the one that would normally build your project. This fake compiler executes either clang or gcc (depending on the platform) to compile your code and then executes the static analyzer to analyze your code.
The reason configure also needs to be run through scan-build is because scan-build scans your source files by interposing on the compiler. This interposition is currently done by scan-build temporarily setting the environment variable CC to ccc-analyzer. The programccc-analyzer acts like a fake compiler, forwarding its command line arguments over to the compiler to perform regular compilation andclang to perform static analysis
这就是说直接使用clang++,它就会直接使用ccc-analyzer作为默认的分析器,而不会得到结果,将Makefile改成如下所示,就解决的这个问题:
new:new.cpp
    $(CXX) new.cpp -o new
对于大型工程一般不会出现这个问题,因为他们C编译器一般就是用CC, C++使用的是CXX,这样只需要在scan-build后面加上--use-c=/usr/bin/clang 或者--use-c++=/usr/bin/clang++ 即可。

原创粉丝点击