fuzzing_options.cmake 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. # Copyright 2018 Google
  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. # Add fuzz testing options to the current build.
  15. include(compiler_id)
  16. option(FUZZING "Build for Fuzz Testing (local fuzzing and OSS Fuzz)" OFF)
  17. # Assume OSS Fuzz if LIB_FUZZING_ENGINE environment variable is set. OSS Fuzz
  18. # provides its required compiler-specific flags in CXXFLAGS, which are
  19. # automatically added to CMAKE_CXX_FLAGS. For local fuzzing, multiple compile
  20. # and linking flags must be set. These flags depend on the compiler version.
  21. if(FUZZING AND NOT DEFINED ENV{LIB_FUZZING_ENGINE})
  22. if(WIN32)
  23. # Currently, libFuzzer cannot be built on Windows.
  24. message(FATAL_ERROR "Fuzzing is currently not supported on Windows.")
  25. endif()
  26. # Address sanitizer must be enabled during fuzzing to detect memory errors.
  27. if(NOT WITH_ASAN)
  28. message(FATAL_ERROR "Fuzzing requires WITH_ASAN=ON to detect memory errors.")
  29. endif()
  30. # Set the flag to enable code coverage instrumentation. Fuzzing engines use
  31. # code coverage as a metric to guide the fuzzing. We use the basic code
  32. # coverage level (trace-pc). This flag has different values in Clang and GNU.
  33. # Other values, such as trace-cmp, can be used to trace data flow. See the
  34. # official documentation for the compiler flags.
  35. if(CXX_CLANG)
  36. # TODO(minafarid): Check the version of Clang. Clang versions >= 5.0 should
  37. # have libFuzzer by default.
  38. set(fuzzing_flags -fsanitize-coverage=trace-pc-guard)
  39. elseif(CXX_GNU)
  40. set(fuzzing_flags -fsanitize-coverage=trace-pc)
  41. else()
  42. message(FATAL_ERROR "Only Clang and GCC support fuzzing.")
  43. endif()
  44. foreach(flag ${fuzzing_flags})
  45. set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${flag}")
  46. endforeach()
  47. endif()