Fangrui Song a853fe25df
[nsan] Add nsan_preinit.cpp and make it static library only
#94322 defines .preinit_array to initialize nsan early.
DT_PREINIT_ARRAY can only be used with the main executable. GNU ld would
complain when a DSO has .preinit_array. Therefore,
nsan_preinit.cpp cannot be linked into `libclang_rt.nsan.so` (#98415).

Working with @alexander-shaposhnikov, we noticed that `Nsan-x86_64-Test
--gtest_output=json` without `.preinit_array` will sigsegv. This is
because googletest with the JSON output calls `localtime_r` , which
calls `free(0)` and fails when `REAL(free)` remains uninitialized
(nullptr). This is benign with the default output because malloc/free
are all paired and `REAL(free)(ptr)` is not called.

To fix the unittest failure, `__nsan_init` needs to be called early
(.preinit_array).
`asan/tests/CMakeLists.txt:ASAN_UNITTEST_INSTRUMENTED_LINK_FLAGS` ues
`-fsanitize=address` to ensure `asan_preinit.cpp.o` is linked into the
unittest executable. Port the approach and remove
`NSAN_TEST_RUNTIME_OBJECTS`.

Fix #98523

Pull Request: https://github.com/llvm/llvm-project/pull/98564
2024-07-11 18:22:52 -07:00

43 lines
1.3 KiB
CMake

include(CompilerRTCompile)
set(NSAN_UNITTEST_CFLAGS
${COMPILER_RT_UNITTEST_CFLAGS}
${COMPILER_RT_GTEST_CFLAGS}
${SANITIZER_TEST_CXX_CFLAGS}
-I${COMPILER_RT_SOURCE_DIR}/include
-I${COMPILER_RT_SOURCE_DIR}/lib
-DSANITIZER_COMMON_REDEFINE_BUILTINS_IN_STD
-O2
-g
-fno-omit-frame-pointer)
set(NSAN_UNITTEST_LINK_FLAGS
${COMPILER_RT_UNITTEST_LINK_FLAGS}
${COMPILER_RT_UNWINDER_LINK_LIBS}
${SANITIZER_TEST_CXX_LIBRARIES})
set(NSAN_UNITTEST_INSTRUMENTED_LINK_FLAGS ${NSAN_UNITTEST_LINK_FLAGS})
list(APPEND NSAN_UNITTEST_INSTRUMENTED_LINK_FLAGS -fsanitize=numerical)
file(GLOB NSAN_HEADERS ../*.h)
set(NSAN_UNITTESTS
NSanUnitTest.cpp
nsan_unit_test_main.cpp)
add_custom_target(NsanUnitTests)
if(COMPILER_RT_DEFAULT_TARGET_ARCH IN_LIST NSAN_SUPPORTED_ARCH)
# NSan unit tests are only run on the host machine.
set(arch ${COMPILER_RT_DEFAULT_TARGET_ARCH})
set(NsanTestObjects)
generate_compiler_rt_tests(NsanTestObjects
NsanUnitTests "Nsan-${arch}-Test" ${arch}
SOURCES ${NSAN_UNITTESTS} ${COMPILER_RT_GTEST_SOURCE}
DEPS ${NSAN_UNIT_TEST_HEADERS}
CFLAGS ${NSAN_UNITTEST_CFLAGS}
LINK_FLAGS ${NSAN_UNITTEST_INSTRUMENTED_LINK_FLAGS})
set_target_properties(NsanUnitTests PROPERTIES
RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})
endif()