sanitizer_options.cmake 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # Copyright 2018 Google LLC
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # Adds Sanitzer options to the current build.
  15. option(WITH_ASAN "Build with Address Sanitizer" OFF)
  16. # TODO(varconst): msan
  17. # Memory sanitizer is more complicated:
  18. # - it requires all dependencies to be compiled with msan enabled (see
  19. # https://github.com/google/sanitizers/wiki/MemorySanitizerLibcxxHowTo);
  20. # - AppleClang doesn't support it.
  21. option(WITH_TSAN "Build with Thread Sanitizer (mutually exculsive with other sanitizers)" OFF)
  22. option(WITH_UBSAN "Build with Undefined Behavior sanitizer" OFF)
  23. macro(add_to_compile_and_link_flags flag)
  24. set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${flag}")
  25. set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${flag}")
  26. set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${flag}")
  27. set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} ${flag}")
  28. set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} ${flag}")
  29. endmacro()
  30. if(CXX_CLANG OR CXX_GNU)
  31. if(WITH_ASAN)
  32. add_to_compile_and_link_flags("-fsanitize=address")
  33. endif()
  34. if(WITH_TSAN)
  35. if(WITH_ASAN OR WITH_UBSAN)
  36. message(FATAL_ERROR "Cannot combine TSan with other santizers")
  37. endif()
  38. add_to_compile_and_link_flags("-fsanitize=thread")
  39. endif()
  40. if(WITH_UBSAN)
  41. add_to_compile_and_link_flags("-fsanitize=undefined")
  42. endif()
  43. if (WITH_ASAN OR WITH_TSAN OR WITH_UBSAN)
  44. # Recommended to "get nicer stack traces in error messages"
  45. # TODO(varconst): double-check that TSan actually needs this flag (it's
  46. # explicitly recommended in the docs for ASan and UBSan)
  47. set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-omit-frame-pointer")
  48. endif()
  49. else()
  50. if(WITH_ASAN OR WITH_TSAN OR WITH_UBSAN)
  51. message(FATAL_ERROR "Only Clang and GCC support sanitizers")
  52. endif()
  53. endif()