1 // Copyright 2017 The Abseil Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include <cstdlib>
16 #include <thread> // NOLINT(build/c++11), Abseil test
17 #include <type_traits>
18
19 #include "absl/base/attributes.h"
20 #include "absl/base/const_init.h"
21 #include "absl/base/internal/raw_logging.h"
22 #include "absl/base/thread_annotations.h"
23 #include "absl/synchronization/mutex.h"
24 #include "absl/synchronization/notification.h"
25
26 namespace {
27
28 // A two-threaded test which checks that Mutex, CondVar, and Notification have
29 // correct basic functionality. The intent is to establish that they
30 // function correctly in various phases of construction and destruction.
31 //
32 // Thread one acquires a lock on 'mutex', wakes thread two via 'notification',
33 // then waits for 'state' to be set, as signalled by 'condvar'.
34 //
35 // Thread two waits on 'notification', then sets 'state' inside the 'mutex',
36 // signalling the change via 'condvar'.
37 //
38 // These tests use ABSL_RAW_CHECK to validate invariants, rather than EXPECT or
39 // ASSERT from gUnit, because we need to invoke them during global destructors,
40 // when gUnit teardown would have already begun.
ThreadOne(absl::Mutex * mutex,absl::CondVar * condvar,absl::Notification * notification,bool * state)41 void ThreadOne(absl::Mutex* mutex, absl::CondVar* condvar,
42 absl::Notification* notification, bool* state) {
43 // Test that the notification is in a valid initial state.
44 ABSL_RAW_CHECK(!notification->HasBeenNotified(), "invalid Notification");
45 ABSL_RAW_CHECK(*state == false, "*state not initialized");
46
47 {
48 absl::MutexLock lock(mutex);
49
50 notification->Notify();
51 ABSL_RAW_CHECK(notification->HasBeenNotified(), "invalid Notification");
52
53 while (*state == false) {
54 condvar->Wait(mutex);
55 }
56 }
57 }
58
ThreadTwo(absl::Mutex * mutex,absl::CondVar * condvar,absl::Notification * notification,bool * state)59 void ThreadTwo(absl::Mutex* mutex, absl::CondVar* condvar,
60 absl::Notification* notification, bool* state) {
61 ABSL_RAW_CHECK(*state == false, "*state not initialized");
62
63 // Wake thread one
64 notification->WaitForNotification();
65 ABSL_RAW_CHECK(notification->HasBeenNotified(), "invalid Notification");
66 {
67 absl::MutexLock lock(mutex);
68 *state = true;
69 condvar->Signal();
70 }
71 }
72
73 // Launch thread 1 and thread 2, and block on their completion.
74 // If any of 'mutex', 'condvar', or 'notification' is nullptr, use a locally
75 // constructed instance instead.
RunTests(absl::Mutex * mutex,absl::CondVar * condvar)76 void RunTests(absl::Mutex* mutex, absl::CondVar* condvar) {
77 absl::Mutex default_mutex;
78 absl::CondVar default_condvar;
79 absl::Notification notification;
80 if (!mutex) {
81 mutex = &default_mutex;
82 }
83 if (!condvar) {
84 condvar = &default_condvar;
85 }
86 bool state = false;
87 std::thread thread_one(ThreadOne, mutex, condvar, ¬ification, &state);
88 std::thread thread_two(ThreadTwo, mutex, condvar, ¬ification, &state);
89 thread_one.join();
90 thread_two.join();
91 }
92
TestLocals()93 void TestLocals() {
94 absl::Mutex mutex;
95 absl::CondVar condvar;
96 RunTests(&mutex, &condvar);
97 }
98
99 // Normal kConstInit usage
100 ABSL_CONST_INIT absl::Mutex const_init_mutex(absl::kConstInit);
TestConstInitGlobal()101 void TestConstInitGlobal() { RunTests(&const_init_mutex, nullptr); }
102
103 // Global variables during start and termination
104 //
105 // In a translation unit, static storage duration variables are initialized in
106 // the order of their definitions, and destroyed in the reverse order of their
107 // definitions. We can use this to arrange for tests to be run on these objects
108 // before they are created, and after they are destroyed.
109
110 using Function = void (*)();
111
112 class OnConstruction {
113 public:
OnConstruction(Function fn)114 explicit OnConstruction(Function fn) { fn(); }
115 };
116
117 class OnDestruction {
118 public:
OnDestruction(Function fn)119 explicit OnDestruction(Function fn) : fn_(fn) {}
~OnDestruction()120 ~OnDestruction() { fn_(); }
121 private:
122 Function fn_;
123 };
124
125 // These tests require that the compiler correctly supports C++11 constant
126 // initialization... but MSVC has a known regression since v19.10:
127 // https://developercommunity.visualstudio.com/content/problem/336946/class-with-constexpr-constructor-not-using-static.html
128 // TODO(epastor): Limit the affected range once MSVC fixes this bug.
129 #if defined(__clang__) || !(defined(_MSC_VER) && _MSC_VER > 1900)
130 // kConstInit
131 // Test early usage. (Declaration comes first; definitions must appear after
132 // the test runner.)
133 extern absl::Mutex early_const_init_mutex;
134 // (Normally I'd write this +[], to make the cast-to-function-pointer explicit,
135 // but in some MSVC setups we support, lambdas provide conversion operators to
136 // different flavors of function pointers, making this trick ambiguous.)
__anone238ffbc0202null137 OnConstruction test_early_const_init([] {
138 RunTests(&early_const_init_mutex, nullptr);
139 });
140 // This definition appears before test_early_const_init, but it should be
141 // initialized first (due to constant initialization). Test that the object
142 // actually works when constructed this way.
143 ABSL_CONST_INIT absl::Mutex early_const_init_mutex(absl::kConstInit);
144
145 // Furthermore, test that the const-init c'tor doesn't stomp over the state of
146 // a Mutex. Really, this is a test that the platform under test correctly
147 // supports C++11 constant initialization. (The constant-initialization
148 // constructors of globals "happen at link time"; memory is pre-initialized,
149 // before the constructors of either grab_lock or check_still_locked are run.)
150 extern absl::Mutex const_init_sanity_mutex;
__anone238ffbc0302() 151 OnConstruction grab_lock([]() ABSL_NO_THREAD_SAFETY_ANALYSIS {
152 const_init_sanity_mutex.Lock();
153 });
154 ABSL_CONST_INIT absl::Mutex const_init_sanity_mutex(absl::kConstInit);
__anone238ffbc0402() 155 OnConstruction check_still_locked([]() ABSL_NO_THREAD_SAFETY_ANALYSIS {
156 const_init_sanity_mutex.AssertHeld();
157 const_init_sanity_mutex.Unlock();
158 });
159 #endif // defined(__clang__) || !(defined(_MSC_VER) && _MSC_VER > 1900)
160
161 // Test shutdown usage. (Declarations come first; definitions must appear after
162 // the test runner.)
163 extern absl::Mutex late_const_init_mutex;
164 // OnDestruction is being used here as a global variable, even though it has a
165 // non-trivial destructor. This is against the style guide. We're violating
166 // that rule here to check that the exception we allow for kConstInit is safe.
167 // NOLINTNEXTLINE
__anone238ffbc0502null168 OnDestruction test_late_const_init([] {
169 RunTests(&late_const_init_mutex, nullptr);
170 });
171 ABSL_CONST_INIT absl::Mutex late_const_init_mutex(absl::kConstInit);
172
173 } // namespace
174
main()175 int main() {
176 TestLocals();
177 TestConstInitGlobal();
178 // Explicitly call exit(0) here, to make it clear that we intend for the
179 // above global object destructors to run.
180 std::exit(0);
181 }
182