c++ - 当 UBSAN (-fsanitize=undefined) 发现未定义行为时触发测试失败
问题描述
我在这里有一个小单元测试,它有未定义的行为。
源代码:
#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 等)?
解决方案
根据文档:
-fsanitize=...
:打印详细的错误报告并继续执行(默认);
-fno-sanitize-recover=...
:打印详细的错误报告并退出程序;
-fsanitize-trap=...
:执行陷阱指令(不需要 UBSan 运行时支持)。注意
trap
/recover
选项不启用相应的 sanitizer,一般需要附带一个合适的-fsanitize=
标志。
似乎当您使用-fsanitize=
与您正在谈论的完全相同的事情时。它注意到未定义的行为并报告它,但继续执行。所以附加 a-fno-sanitize-recover=all
应该退出程序。
推荐阅读
- mongodb - 错误重新启动 mongo.service 尝试在 mongodb 4.2 中添加多个绑定 ip
- javascript - Bootstrap 4侧栏多级 - 折叠显示隐藏不起作用
- prestashop - Prestashop - 如何在从代码创建产品时添加图像
- repast-simphony - GUI 不显示代理属性
- python - 迭代特定范围的索引和算法伪代码-> python
- python - 使用 PIL.ImageFont.truetype 加载 otf 文件时的未知文件格式
- java - 切换到另一个片段时如何删除某些布局获取的布局空间?
- r - 如何上传 R 代码使其通过源代码自动运行?
- geoserver - 是否可以在 GeoServer MapBox VectorTiles 层中使用 VIEWPARAMS?
- ios - Unity google VR 方向在 iOS 上是倾斜的