在Windows系統中配置Google AddressSanitizer

Google AddressSanitizer簡介

AddressSanitizer (ASan) 是 C 和 C++ 的記憶體錯誤檢測軟體,它可以檢測:

  • 釋放指針後繼續使用
  • 堆緩衝區溢出
  • 棧緩衝區溢出
  • 全局緩衝區溢出
  • 返回後繼續使用
  • 在範圍之外繼續使用
  • 初始化順序的bug
  • 記憶體泄漏

在 Windows 系統中,可以在 LLVM 和 MSVC 中進行使用。

Visual Studio 2019的配置

先上兩個鏈接:

//devblogs.microsoft.com/cppblog/addresssanitizer-asan-for-windows-with-msvc/

//devblogs.microsoft.com/cppblog/asan-for-windows-x64-and-debug-build-support/#16-9-preview-3-and-later

根據這兩個鏈接進行安裝配置應該問題不大,Visual Studio 16.9 Preview 3及其以後的版本不需要額外手動配置鏈接庫,建議安裝這個版本之後的軟體,能省點事情,這樣就只需要配置一下項目的屬性即可,下面是簡單的配置及測試結果。

VS2019.png

AddressSaniziter.png

CLion中的配置

先放個CLion的官方教程鏈接

配置ToolChains

CLion 中的配置稍微複雜一點,首先配置CLion的工具鏈,添加一個新的 Visual Studio的配置,正常情況下添加配置的時候會自動識別,但是我的社區版VS2019在CLion 2020.3這個版本下是無法自動識別的。我嘗試過手動指定環境也沒有識別,幾經折騰後我放棄了,轉頭就安裝了個企業版😂。這下還是無法自動識別,但是手動指定環境後就識別了,Architecture根據需要設定即可,Platform建議默認,Version根據需要設定即可,編譯器直接使用自動檢測的配置即可,如果安裝了 Clang的編譯器也可以手動指定為Clang的編譯器,不過在後面配置CMakeLists.txt的時候需要更改鏈接庫的路徑為Clang對應的目錄。

CLion_VS2019.png

配置CMake選項

CLion_VS2019_02.png

編寫CMakeLists.txt

這個CMakeLists.txt文件會遍歷所在目錄下的所有 .cpp 源文件,每個源文件創建一個單獨的可執行項目

cmake_minimum_required(VERSION 3.17)
project(LeetCode VERSION 1.0.0 LANGUAGES CXX)

# Retrieve all cpp file in the current cmake source directory
file(GLOB SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.cpp)

# debug message
function(debug_message MESSAGE)
    message("==============================")
    message(${MESSAGE})
    message("==============================")
endfunction()

if (CMAKE_BUILD_TYPE STREQUAL "Debug")
    set(BuildType "dbg_")
endif ()

# add all to executable target
foreach (SRC IN LISTS SOURCES)
    string(REGEX REPLACE "(^.+)\\.(.+$)" \\1 TMP_SRC ${SRC})
    string(REPLACE " " "_" TARGET_NAME ${TMP_SRC})
    add_executable(${TARGET_NAME} ${SRC})
    target_include_directories(${TARGET_NAME} PRIVATE include)
    if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")
        target_compile_options(${TARGET_NAME} PRIVATE -fsanitize=address)
        # set link directories
        target_link_directories(${TARGET_NAME} PRIVATE
                "D:/Microsoft Visual Studio/2019/Enterprise/VC/Tools/MSVC/14.28.29333/lib/x64/")
        target_link_libraries(${TARGET_NAME} PRIVATE
                clang_rt.asan_${BuildType}dynamic-x86_64
                clang_rt.asan_${BuildType}dynamic_runtime_thunk-x86_64)
        target_link_options(${TARGET_NAME} PRIVATE
                /wholearchive:clang_rt.asan_${BuildType}dynamic_runtime_thunk-x86_64.lib)
    endif ()
endforeach ()

測試

運行的時候可能會失敗,把缺失的動態庫拷貝到可執行文件目錄下即可,不想拷貝就在環境變數裡面添加與Visual Studio工具鏈匹配的路徑也可。例如,我上面工具鏈設置的是amd64,CLion自動檢測到的編譯器是「D:\Microsoft Visual Studio\2019\Enterprise\VC\Tools\MSVC\14.28.29910\bin\Hostx64\x64\cl.exe」,這時候把「D:\Microsoft Visual Studio\2019\Enterprise\VC\Tools\MSVC\14.28.29910\bin\Hostx64\x64\」這個路徑添加到環境變數中重啟CLion即可正常運行。

CLion_VS2019_03.png

本文部落格地址