OCLint 初探

文章結構:

1. 什么是 OCLint

OCLint 是針對于 C,C++,Objective-C 代碼的靜態(tài)分析工具,目的是提高軟件質量并且減少代碼中存在的潛在問題,OCLint 旨于分析以下潛在問題:

  • 可能出現的 bug:if/else/try/catch 等條件語句空的聲明
  • 未使用的代碼: 未使用的局部變量以及參數
  • 復雜的代碼邏輯:高循環(huán)復雜度、NP 復雜度(懵)、 高 NCSS(懵)
  • 冗余代碼:冗余的條件表達式以及無效的括號
  • 代碼嗅覺:方法代碼行過長或者參數過多
  • 不好的代碼習慣:顛倒的邏輯和參數的錯誤分配
  • ...

靜態(tài)代碼分析工具是偵測編譯器不可見的潛在缺陷的關鍵技術。OCLint 具有以下先進的代碼檢驗特性:

  • 依靠源碼的抽象語法樹來提高分析的精確度以及效率,誤報率低
  • 動態(tài)規(guī)則
  • 靈活可擴展的配置,確保用戶可以自定義分析行為
  • 命令行式的調用使持續(xù)集成成為可能

2. OCLint 安裝

下載 OCLint

2.1. Homebrew 安裝

確保你已經安裝了 Homebrew

$ brew install oclint

近些天使用 Homebrew 安裝 OCLint 經常失敗,遂放棄了這種安裝方式。

2.2. 下載并設置下載目錄為環(huán)境變量

添加以下代碼到命令行啟動文件中,默認啟動文件是 .bashrc.bash_profile ,安裝 oh-my-zsh 后是 .zshrc 文件。

$ OCLINT_HOME=path-to-oclint-release
$ export PATH=$OCLINT_HOME/bin:$PATH

解釋path-to-oclint-release是 OCLint 安裝包的路徑

使用以下命令判斷是否添加環(huán)境變量成功

echo $PATH

2.3. 下載并拷貝至系統(tǒng)環(huán)境變量中

也可以直接將 OCLint 的可執(zhí)行文件拷貝至系統(tǒng)文件夾 /usr/local/bin。可以注意到 /usr/local/bin 也在 PATH 中。

cd oclint
cp bin/oclint* /usr/local/bin/
cp -rp lib/* /usr/local/lib/

3. OCLint 工具的組成

OCLint 工具集由一下三部分組成

  • oclint
  • oclint-json-compilation-database
  • oclint-xcodebuild

具體的使用手冊還是建議大家去閱讀他們的官方文檔,其功能可以簡單概括為:

  • oclint 是 OCLint 工具集最主要的指令,主要作用是規(guī)則加載、編譯分析選項以及生成分析報告
  • oclint-json-compilation-database 的作用是在 JSON Compilation Database format 類型的編譯文件 compile_commands.json 中提取必要的信息。
  • oclint-xcodebuild 用于將 xcodebuild 生成的 log 文件 xcodebuild.log 轉換為 JSON Compilation Database format 類型

可以使用時序圖來概括我們使用這幾個指令的場景:


oclint-sequence

4. OCLint 的使用

4.1. OCLint 結合 xcodebuild 的使用

xcodebuild 命令用來編譯 Xcode 工程,xcodebuild 可以編譯 Xcode 工程里面的一個或多個 target,也可以用來編譯 Xcode workspace 或者 Xcode project 中的任意一個 scheme。

OCLint 結合 xcodebuild 的使用主要分為一下幾個步驟

  1. 使用 xcodebuild clean 清理工程(可選)
  2. 使用 xcodebuild build 編譯工程 并且使用 xcpretty 輸出編譯文件
  3. 使用 oclint-json-compilation-database 輸出分析結果

4.1.1. 清理工程(可選)

假設一個源文件已經使用 xcodebuild 編譯過了,并且沒有被修改,那么下次編譯的時候改源文件不參與編譯,也就是說生成的 compile_commands.json 文件里面是不含有該源文件的內容的。如果你希望該源文件每次都編譯,可以使用 xcodebuild clean 指令來清理編譯緩存。

然而 clean 過后,編譯過程會變得相當漫長,這種現象在大項目中表現最為明顯。所以說如果你的項目文件沒改動,工程的編譯選項也未修改。使用上次的 xcodebuildcompile_commands.json 進行分析也是可取的。這里是否可以得出增量編譯的條件下,項目中未變動代碼的部分是不會出現在新的編譯報告中的。

4.1.2. 編譯工程,輸出編譯報告

使用 xcodebuild 命令編譯工程,例如使用一下命令編譯 OCLintDemo.xcworkspace 下的 OCLintDemo scheme。

xcodebuild -workspace       OCLintDemo.xcworkspace \
           -scheme          OCLintDemo \
           -configuration   Debug \
           -sdks            iphonesimulator10.3 \
           build

此時就有兩種方式生成 compile_commands.json

方式一:使用 tee 指令獲取輸出結果為 xcodebuild.log ,使用 oclint-xcodebuild 將 xcodebuild.log 輸出為 compile_commands.json 文件

xcodebuild -workspace       OCLintDemo.xcworkspace \
           -scheme          OCLintDemo \
           -configuration   Debug \
           -sdks            iphonesimulator10.3 \
           build | tee xcodebuild.log

oclint-xcodebuild

方式二:使用 xcpretty 直接將編譯結果輸出為 compile_commands.json

xcodebuild -workspace       OCLintDemo.xcworkspace \
           -scheme          OCLintDemo \
           -configuration   Debug \
           -sdks            iphonesimulator10.3 \
           build | xcpretty -r json-compilation-database -o compile_commands.json

推薦使用 xcpretty 的方式生成 json-compilation-database 類型的編譯報告。

4.1.3. 輸出分析結果

使用 oclint-json-compilation-database 指令來解析 json-compilation-database 類型的編譯報告。

$ oclint-json-compilation-database --help
usage: oclint-json-compilation-database [-h] [-v] [-debug] [-i INCLUDES]
                                        [-e EXCLUDES]
                                        [oclint_args [oclint_args ...]]

OCLint for JSON Compilation Database (compile_commands.json)

positional arguments:
  oclint_args           arguments that are passed to OCLint invocation

optional arguments:
  -h, --help            show this help message and exit
  -v                    show invocation command with arguments
  -debug, --debug       invoke OCLint in debug mode
  -i INCLUDES, -include INCLUDES, --include INCLUDES
                        extract files matching pattern
  -e EXCLUDES, -exclude EXCLUDES, --exclude EXCLUDES
                        remove files matching pattern

從引導上來看,oclint-json-compilation-database 可以通過 -e 選項來忽略對制定路徑文件的分析,對于使用 Cocoapods 來管理依賴的工程,我們往往會忽略 Pods 文件夾。

oclint-json-compilation-database -e Pods -- xxxx

通常使用 -- 來分割 oclint-json-compilation-database 的參數與 oclint_argsoclint_args 就是 oclint 命令的參數,接下來我們來看看 oclint 指令支持的參數。

$ oclint --help
USAGE: oclint [options] <source0> [... <sourceN>]

OPTIONS:

OCLint options:

  -R=<directory>                - Add directory to rule loading path
  -allow-duplicated-violations  - Allow duplicated violations in the OCLint report
  -disable-rule=<rule name>     - Disable rules
  -enable-clang-static-analyzer - Enable Clang Static Analyzer, and integrate results into OCLint report
  -enable-global-analysis       - Compile every source, and analyze across global contexts (depends on number of source files, could results in high memory load)
  -extra-arg=<string>           - Additional argument to append to the compiler command line
  -extra-arg-before=<string>    - Additional argument to prepend to the compiler command line
  -list-enabled-rules           - List enabled rules
  -max-priority-1=<threshold>   - The max allowed number of priority 1 violations
  -max-priority-2=<threshold>   - The max allowed number of priority 2 violations
  -max-priority-3=<threshold>   - The max allowed number of priority 3 violations
  -no-analytics                 - Disable the anonymous analytics
  -o=<path>                     - Write output to <path>
  -p=<string>                   - Build path
  -rc=<parameter>=<value>       - Override the default behavior of rules
  -report-type=<name>           - Change output report type
  -rule=<rule name>             - Explicitly pick rules

Generic Options:

  -help                         - Display available options (-help-hidden for more)
  -help-list                    - Display list of available options (-help-list-hidden for more)
  -version                      - Display the version of this program

-p <build-path> is used to read a compile command database.

    For example, it can be a CMake build directory in which a file named
    compile_commands.json exists (use -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
    CMake option to get this output). When no build path is specified,
    a search for compile_commands.json will be attempted through all
    parent paths of the first input file . See:
    http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html for an
    example of setting up Clang Tooling on a source tree.

<source0> ... specify the paths of source files. These paths are
    looked up in the compile command database. If the path of a file is
    absolute, it needs to point into CMake's source tree. If the path is
    relative, the current working directory needs to be in the CMake
    source tree and the file must be in a subdirectory of the current
    working directory. "./" prefixes in the relative files will be
    automatically removed, but the rest of a relative path must be a
    suffix of a path in the compile command database.

For more information, please visit http://oclint.org

如果想最終輸出一個 HTML 類型的分析報告,一個完整的 oclint-json-compile-database 指令應該這么寫

$ oclint-json-compilation-database -e Pods -- -o=report.html

4.2. 使用 OCLint 分析 Xcode 工程

Using OCLint with Xcode

5. OCLint 與持續(xù)集成

6. 遇到的問題

6.1. PCH 錯誤

Compiler Errors: (please be aware that these errors will prevent OCLint from analyzing this source code) :0:0: input is not a PCH file: '/xxx/PrefixHeader.pch.pch' :0:0: file '/xxx/PrefixHeader.pch.pch' is not a valid precompiled PCH file :0:0: input is not a PCH file: '/xxx/PrefixHeader.pch.pch' :0:0: file '/xxx/PrefixHeader.pch.pch' is not a valid precompiled PCH file OCLint Report Summary: TotalFiles=0 FilesWithViolations=0 P1=0 P2=0 P3=0 [OCLint (http://oclint.org) v0.12]

沒找到問題原因,目前只知道將編譯選項 Precompile prefix header 設置為 NO 可以解決問題。

6.2. oclint: error: violations exceed threshold

運行 oclint-json-compilation-databse 以下錯誤

$ oclint-json-compilation-database -e Pods -- -o=report.html
oclint: error: violations exceed threshold
P1=0[0] P2=1637[10] P3=53904[20]

出現這個的原因是項目中的 issue 超過了限制,使用以下 option 來約定最大的 issue 閾值。

-max-priority-1=9999 -max-priority-2=9999 -max-priority-3=9999

7. 引用文檔

OCLint Documentation

Using OCLint with xcodebuild

Using OCLint with Xcode

oclint-json-compilation-database

json-compilation-database

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 寫在前面 剛入職的時候,博哥交代給我一個任務,讓我調研一款叫SonarQube的靜態(tài)代碼分析工具,我當時跪在了Ce...
    雨潤聽潮閱讀 2,286評論 0 5
  • OCLint是一個強大的靜態(tài)代碼分析工具,可以用來提高代碼質量,查找潛在的bug,主要針對c,c++和Object...
    劉應閱讀 1,313評論 0 1
  • OCLint工具介紹 OCLint是一個靜態(tài)代碼掃描分析工具,可用于提高代碼質量和減少潛在的缺陷,目前支持C,C+...
    Lojii閱讀 6,053評論 5 5
  • 失去的那個人 是 一次曾誓死相知卻遭到背棄 最后成為記憶中 永遠 卻無法再一次親密的 那一個人 失去的那個人 和 ...
    因為愛所以執(zhí)著閱讀 479評論 0 1
  • 直接先把方法貼出來(參考了Stack Overflow) 下面解釋下方法中用到的一些類型(參考MDN) Array...
    KimYYX閱讀 16,546評論 4 6