Clang 靜態分析工具的使用

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++ 即可。





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章