• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.
4 
5 #include <vector>
6 
7 #include "build/build_config.h"
8 #include "testing/gmock/include/gmock/gmock.h"
9 #include "testing/gtest/include/gtest/gtest.h"
10 
11 namespace {
12 
13 // TODO(thakis): Remove _LIBCPP_ENABLE_ASSERTIONS here once
14 // pnacl-saigo's libc++ is new enough.
15 #if !_LIBCPP_ENABLE_ASSERTIONS && \
16     _LIBCPP_HARDENING_MODE != _LIBCPP_HARDENING_MODE_EXTENSIVE
17 #error "_LIBCPP_HARDENING_MODE not defined"
18 #endif
19 
20 using ::testing::ContainsRegex;
21 using ::testing::Not;
22 
23 // This test checks for two things:
24 //
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
27 //    std::vector.
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.
TEST(LibcppHardeningTest,Assertions)35 TEST(LibcppHardeningTest, Assertions) {
36   std::vector<int> vec = {0, 1, 2};
37 #ifdef NDEBUG
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:
40 //
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.
46 //
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 // base::ImmediateCrash() (https://crbug.com/1353549#c2).
50 #if GTEST_HAS_DEATH_TEST && !GTEST_OS_LINUX_ANDROID
51   EXPECT_DEATH(vec[3], Not(ContainsRegex(".*assertion.*failed:")));
52 #else
53   GTEST_UNSUPPORTED_DEATH_TEST(vec[3], "", );
54 #endif  // GTEST_HAS_DEATH_TEST && !GTEST_OS_LINUX_ANDROID
55 #else
56   EXPECT_DEATH_IF_SUPPORTED(vec[3], ".*assertion.*failed:");
57 #endif  // ifdef NDEBUG
58 }
59 
60 }  // namespace
61