1 // Copyright 2022 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
7 #include "build/build_config.h"
8 #include "testing/gmock/include/gmock/gmock.h"
9 #include "testing/gtest/include/gtest/gtest.h"
13 #if !_LIBCPP_ENABLE_ASSERTIONS
15 "Define _LIBCPP_ENABLE_ASSERTIONS to 1 in \
16 buildtools/third_party/libc++/__config_site"
20 using ::testing::ContainsRegex;
23 // This test checks for two things:
25 // 0. Assertions are enabled for libc++ and cause the process to crash when
26 // invoked (in this test's case, when an out of bounds access is made in
28 // 1. The correct assertion handler is linked in depending on whether or not
29 // this test is built in debug mode. libc++ passes the string
30 // {file}:{line} assertion {expression} failed: {message}. The default
31 // libc++ handler, which we use in debug mode, prints this string to stderr,
32 // while the nondebug assertion handler just crashes immediately. Therefore,
33 // to check that we linked in the correct assertion handler, we check for the
34 // presence or absence of the above string.
35 TEST(LibcppHardeningTest, Assertions) {
36 std::vector<int> vec = {0, 1, 2};
38 // We have to explicitly check for the GTEST_HAS_DEATH_TEST macro instead of
39 // using EXPECT_DEATH_IF_SUPPORTED(...) for the following reasons:
41 // 0. EXPECT_DEATH(...) does not support (non-escaped) parentheses in the regex,
42 // so we can't use negative look arounds (https://stackoverflow.com/a/406408)
43 // to check that the error message doesn't exist.
44 // 1. EXPECT_DEATH_IF_SUPPORTED(...) does not support having gmock matchers as
45 // the second argument if GTEST_HAS_DEATH_TEST is false.
47 // We also have to prevent this test from running on Android because even though
48 // death tests are supported on Android, GTest death tests don't work with
49 // IMMEDIATE_CRASH() (https://crbug.com/1353549#c2).
50 #if GTEST_HAS_DEATH_TEST && !GTEST_OS_LINUX_ANDROID
51 EXPECT_DEATH(vec[3], Not(ContainsRegex(".*assertion.*failed:")));
53 GTEST_UNSUPPORTED_DEATH_TEST(vec[3], "", );
54 #endif // GTEST_HAS_DEATH_TEST && !GTEST_OS_LINUX_ANDROID
56 EXPECT_DEATH_IF_SUPPORTED(vec[3], ".*assertion.*failed:");
57 #endif // ifdef NDEBUG