在适用于 Xcode 的 CMake 中启用 AddressSanitizer 的正确方法是什么

2021-12-26 00:00:00 clang cmake c++ address-sanitizer

我添加了 AddressSanitizer 标志如下:

I've added AddressSanitizer flag as follow:

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

使用 Unix Makefiles 时,一切构建和运行良好.

Everything builds and runs fine when using Unix Makefiles.

问题是在生成Xcode项目的时候,它只是不想链接,因为它找不到ASan库.

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

我已经找到了两个解决方案,但决定不使用它们,因为它们无法仅使用 CMake 实现自动化:

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

  1. -Wl,-undefined,dynamic_lookup 添加到链接标志,因此它跳过链接到动态库.
  2. 直接与 libclang_rt.asan_osx_dynamic.dylib 链接.
  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?

  • 使用解决方案 #1 时,我必须在 Xcode 中手动打开目标方案并添加指向 libclang_rt.asan_osx_dynamic.dylibDYLD_INSERT_LIBRARIES 环境变量.
  • 使用解决方案 #2 时,ASan 库的路径因计算机而异.

此外,作为另一种解决方案,我尝试从 Xcode 目标方案启用 Address Sanitizer 标志,但有趣的是它没有检测到我添加的问题,所以我没有将其列为解决方案,因为它没有通过我的测试.

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.

任何帮助将不胜感激.

推荐答案

您也需要向链接器提供标志.我是这样做的:

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")

相关文章