c++ - 当 UBSAN (-fsanitize=undefined) 发现未定义行为时触发测试失败

标签 c++ ubsan

我在这里有一个小的单元测试,它具有未定义的行为。
源代码:

#include <gtest/gtest.h>

TEST(test, test)
{
    int k = 0x7fffffff;
    k += 1; // cause integer overflow
}

GTEST_API_ int main(int argc, char** argv)
{
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
我在 CMakeLists.txt 中启用了 UBSAN:
cmake_minimum_required (VERSION 3.12)
project(ub CXX)

find_package(GTest REQUIRED)

add_executable        (ub_test ub_test.cpp)
target_link_libraries (ub_test GTest::GTest)
target_compile_options(ub_test PRIVATE -fsanitize=undefined)
target_link_options   (ub_test PRIVATE -fsanitize=undefined)
UBSAN 正确识别未定义的行为:
/home/steve/src/ub/ub_test.cpp:6:7: runtime error: signed integer overflow:
2147483647 + 1 cannot be represented in type 'int'

但是,我的测试仍然通过。
[==========] Running 1 test from 1 test suite.
[----------] Global test environment set-up.
[----------] 1 test from test
[ RUN      ] test.test
/home/steve/src/ub/ub_test.cpp:6:7: runtime error: signed integer overflow:
2147483647 + 1 cannot be represented in type 'int'
[       OK ] test.test (0 ms)
[----------] 1 test from test (0 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test suite ran. (0 ms total)
[  PASSED  ] 1 test.

当 UBSAN 发现问题时,是否有可能触发测试失败(抛出异常、退出 1 等)?

最佳答案

根据documentation :

  • -fsanitize=...: print a verbose error report and continue execution (default);

  • -fno-sanitize-recover=...: print a verbose error report and exit the program;

  • -fsanitize-trap=...: execute a trap instruction (doesn’t require UBSan run-time support).

Note that the trap / recover options do not enable the corresponding sanitizer, and in general need to be accompanied by a suitable -fsanitize= flag.


好像当你使用 -fsanitize= 时你所说的完全相同的事情发生了。它注意到未定义的行为并报告它,但继续执行。所以附加一个 -fno-sanitize-recover=all应该退出程序。

关于c++ - 当 UBSAN (-fsanitize=undefined) 发现未定义行为时触发测试失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67500933/

相关文章:

c++ - "lvalue required as left operand of assignment"写链表错误

c++ - Clang UBSAN 报告类型 'std::_Ios_Fmtflags' 的无效值

c++ - 使用 GCC Undefined Behavior Sanitizer

用于开发命令行的 C++ 库

c++ - Python中低级标准输入的重复重定向

c++ - 内联函数上的 static_assert 给出错误

c++ - 为什么 -fsanitize=undefined 导致 "undefined reference to typeinfo"?

c - 对 `__ubsan_handle_nonnull_arg' 的 undefined reference

c++ - 为类型 Y 的对象加载空间不足的地址 X

c++ - 有什么方法可以逃避 QDirIterator 中的 nameFilters 吗?