What's the proper way to enable AddressSanitizer in CMake that works in Xcode

混江龙づ霸主 提交于 2020-05-10 03:46:17

问题


I've added AddressSanitizer flag as follow:

set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=address")

Everything builds and runs fine when using Unix Makefiles.

The problem comes when generating the Xcode project, it just doesn't want to link because it cannot find the ASan library.

I already found two solutions, but decided not to use them because they cannot be automated using just CMake:

  1. Adding -Wl,-undefined,dynamic_lookup to the linked flags, so it skips linking to dynamic libraries.
  2. Link with libclang_rt.asan_osx_dynamic.dylib directly.

So what's the problem with these two solutions?

  • When using solution #1, I have to manually open the target scheme in Xcode and add DYLD_INSERT_LIBRARIES environment variable pointing to libclang_rt.asan_osx_dynamic.dylib.
  • When using solution #2, the path for the ASan library varies between computers.

Additionally as another solution, I tried enabling Address Sanitizer flag from the Xcode target scheme but interestingly it didn't detect the issues I added, so I didn't list this as a solution because it failed my test.

Any help will be much appreciated.


回答1:


You need to provide the flag(s) to the linker too. I'm doing it like this:

set (CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -fno-omit-frame-pointer -fsanitize=address")
set (CMAKE_LINKER_FLAGS_DEBUG "${CMAKE_LINKER_FLAGS_DEBUG} -fno-omit-frame-pointer -fsanitize=address")



回答2:


cmake 3.13
introduce configuration for xcode schema

in CMake

cmake_minimum_required(VERSION 3.13)
set(CMAKE_XCODE_GENERATE_SCHEME ON)
set(CMAKE_XCODE_SCHEME_ADDRESS_SANITIZER ON)
set(CMAKE_XCODE_SCHEME_ADDRESS_SANITIZER_USE_AFTER_RETURN ON)

When Build

xcodebuild -enableAddressSanitizer YES



回答3:


The simplest solution that I currently found is

cmake -DCMAKE_BUILD_TYPE=ASAN .

I prefer this option since it expresses the intent (run sanitizers) rather than modifies a number of flags.

I do not know when this option was added. I also cannot find any documentation to it.



来源:https://stackoverflow.com/questions/44320465/whats-the-proper-way-to-enable-addresssanitizer-in-cmake-that-works-in-xcode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!