dotnet 使用 Infer# 自動分析代碼缺陷


本文告訴大家如何使用 Infer# 開源庫配合 GitHub 的 Action 實現自動分析代碼缺陷,如找到可空引用或線程安全等問題

這是一個在 GitHub 上完全開源的倉庫,請看 https://github.com/microsoft/infersharp

剛好今天收到了 Infer# 發布 1.2 版本博客,請看 Infer# v1.2: Interprocedural Memory Safety Analysis For C# - .NET Blog

關於 GitHub 的 Action 的基礎入門請看 dotnet 部署 github 的 Action 進行持續集成

使用的方法非常簡單,只需要在 GitHub 的 Action 的配置文件里面添加如下代碼

    - name: Run Infer#      
      uses: microsoft/infersharpaction@v1.2
      with:
        binary-path: 輸出二進制文件夾路徑

如我在 https://github.com/dotnet-campus/AsyncWorkerCollection 開源倉庫上的配置代碼如下

    - name: Run Infer#      
      uses: microsoft/infersharpaction@v1.2
      with:
        binary-path: AsyncWorkerCollection/bin/Release/netcoreapp3.1

此輸出的二進制文件夾路徑里面要求是包含 dll 和 pdb 文件,通過 dll 進行分析,通過 pdb 從而告訴你是哪個文件

效果如下

可以看到輸出了資源沒有釋放和線程安全問題

Found 3 issues
                        Issue Type(ISSUED_TYPE_ID): #
  Thread Safety Violation(THREAD_SAFETY_VIOLATION): 2
        Dotnet Resource Leak(DOTNET_RESOURCE_LEAK): 1


Analysis Result
==================================================
#0
/home/runner/work/AsyncWorkerCollection/AsyncWorkerCollection/AsyncWorkerCollection/AsyncTaskQueue_/AsyncTaskQueue.cs:72: error: Dotnet Resource Leak
  Leaked { n$1 -> 1 } resource(s) in method "AwaitableTask AsyncTaskQueue.GetExecutableTask(Action)" at type(s) System.Threading.Tasks.Task.

#1
/home/runner/work/AsyncWorkerCollection/AsyncWorkerCollection/AsyncWorkerCollection/DoubleBuffer_/DoubleBufferLazyInitializeTask.cs:47: warning: Thread Safety Violation
  Unprotected write. Non-private method `DoubleBufferLazyInitializeTask`1<T>.OnInitialized()` writes to field `this.dotnetCampus.Threading.DoubleBufferLazyInitializeTask`1<T>._isInitialized` outside of synchronization.
 Reporting because this access may occur on a background thread.

#2
/home/runner/work/AsyncWorkerCollection/AsyncWorkerCollection/AsyncWorkerCollection/DoubleBuffer_/DoubleBufferLazyInitializeTask.cs:41: warning: Thread Safety Violation
  Read/Write race. Non-private method `DoubleBufferLazyInitializeTask`1<T>.OnInitialized()` reads without synchronization from `this.dotnetCampus.Threading.DoubleBufferLazyInitializeTask`1<T>._isInitialized`. Potentially races with write in method `DoubleBufferLazyInitializeTask`1<T>.OnInitialized()`.
 Reporting because this access may occur on a background thread.

Found 3 issues
                        Issue Type(ISSUED_TYPE_ID): #
  Thread Safety Violation(THREAD_SAFETY_VIOLATION): 2
        Dotnet Resource Leak(DOTNET_RESOURCE_LEAK): 1

此工具只能在 Linux 下運行,官方有制作好一個 docker 文件,可以從 https://github.com/microsoft/infersharpaction 拉到。但是問題不大,因為此工具是對輸出文件進行分析的,所以可以在 Windows 平台上進行構建,只是將輸出的二進制文件使用此工具

在現有的倉庫加添加此工具的例子請看 https://github.com/dotnet-campus/AsyncWorkerCollection/pull/66


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM