1 // Copyright 2018 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 "base/no_destructor.h"
6
7 #include <memory>
8 #include <string>
9 #include <utility>
10 #include <vector>
11
12 #include "base/atomicops.h"
13 #include "base/barrier_closure.h"
14 #include "base/check.h"
15 #include "base/functional/bind.h"
16 #include "base/system/sys_info.h"
17 #include "base/threading/platform_thread.h"
18 #include "base/threading/simple_thread.h"
19 #include "build/build_config.h"
20 #include "testing/gtest/include/gtest/gtest.h"
21
22 namespace base {
23
24 namespace {
25
26 static_assert(!std::is_trivially_destructible_v<std::string>);
27 static_assert(
28 std::is_trivially_destructible_v<base::NoDestructor<std::string>>);
29
30 struct CheckOnDestroy {
~CheckOnDestroybase::__anonc85363690111::CheckOnDestroy31 ~CheckOnDestroy() { CHECK(false); }
32 };
33
TEST(NoDestructorTest,SkipsDestructors)34 TEST(NoDestructorTest, SkipsDestructors) {
35 NoDestructor<CheckOnDestroy> destructor_should_not_run;
36 }
37
38 struct UncopyableUnmovable {
39 UncopyableUnmovable() = default;
UncopyableUnmovablebase::__anonc85363690111::UncopyableUnmovable40 explicit UncopyableUnmovable(int value) : value(value) {}
41
42 UncopyableUnmovable(const UncopyableUnmovable&) = delete;
43 UncopyableUnmovable& operator=(const UncopyableUnmovable&) = delete;
44
45 int value = 1;
46 std::string something_with_a_nontrivial_destructor;
47 };
48
49 struct CopyOnly {
50 CopyOnly() = default;
51
52 CopyOnly(const CopyOnly&) = default;
53 CopyOnly& operator=(const CopyOnly&) = default;
54
55 CopyOnly(CopyOnly&&) = delete;
56 CopyOnly& operator=(CopyOnly&&) = delete;
57 };
58
59 struct MoveOnly {
60 MoveOnly() = default;
61
62 MoveOnly(const MoveOnly&) = delete;
63 MoveOnly& operator=(const MoveOnly&) = delete;
64
65 MoveOnly(MoveOnly&&) = default;
66 MoveOnly& operator=(MoveOnly&&) = default;
67 };
68
69 struct ForwardingTestStruct {
ForwardingTestStructbase::__anonc85363690111::ForwardingTestStruct70 ForwardingTestStruct(const CopyOnly&, MoveOnly&&) {}
71
72 std::string something_with_a_nontrivial_destructor;
73 };
74
TEST(NoDestructorTest,UncopyableUnmovable)75 TEST(NoDestructorTest, UncopyableUnmovable) {
76 static NoDestructor<UncopyableUnmovable> default_constructed;
77 EXPECT_EQ(1, default_constructed->value);
78
79 static NoDestructor<UncopyableUnmovable> constructed_with_arg(-1);
80 EXPECT_EQ(-1, constructed_with_arg->value);
81 }
82
TEST(NoDestructorTest,ForwardsArguments)83 TEST(NoDestructorTest, ForwardsArguments) {
84 CopyOnly copy_only;
85 MoveOnly move_only;
86
87 static NoDestructor<ForwardingTestStruct> test_forwarding(
88 copy_only, std::move(move_only));
89 }
90
TEST(NoDestructorTest,Accessors)91 TEST(NoDestructorTest, Accessors) {
92 static NoDestructor<std::string> awesome("awesome");
93
94 EXPECT_EQ("awesome", *awesome);
95 EXPECT_EQ(0, awesome->compare("awesome"));
96 EXPECT_EQ(0, awesome.get()->compare("awesome"));
97 }
98
99 // Passing initializer list to a NoDestructor like in this test
100 // is ambiguous in GCC.
101 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=84849
102 #if !defined(COMPILER_GCC) && !defined(__clang__)
TEST(NoDestructorTest,InitializerList)103 TEST(NoDestructorTest, InitializerList) {
104 static NoDestructor<std::vector<std::string>> vector({"a", "b", "c"});
105 }
106 #endif
107 } // namespace
108
109 namespace {
110
111 // A class whose constructor busy-loops until it is told to complete
112 // construction.
113 class BlockingConstructor {
114 public:
BlockingConstructor()115 BlockingConstructor() {
116 EXPECT_FALSE(WasConstructorCalled());
117 subtle::NoBarrier_Store(&constructor_called_, 1);
118 EXPECT_TRUE(WasConstructorCalled());
119 while (!subtle::NoBarrier_Load(&complete_construction_))
120 PlatformThread::YieldCurrentThread();
121 done_construction_ = true;
122 }
123 BlockingConstructor(const BlockingConstructor&) = delete;
124 BlockingConstructor& operator=(const BlockingConstructor&) = delete;
125 ~BlockingConstructor() = delete;
126
127 // Returns true if BlockingConstructor() was entered.
WasConstructorCalled()128 static bool WasConstructorCalled() {
129 return subtle::NoBarrier_Load(&constructor_called_);
130 }
131
132 // Instructs BlockingConstructor() that it may now unblock its construction.
CompleteConstructionNow()133 static void CompleteConstructionNow() {
134 subtle::NoBarrier_Store(&complete_construction_, 1);
135 }
136
done_construction() const137 bool done_construction() const { return done_construction_; }
138
139 private:
140 // Use Atomic32 instead of AtomicFlag for them to be trivially initialized.
141 static subtle::Atomic32 constructor_called_;
142 static subtle::Atomic32 complete_construction_;
143
144 bool done_construction_ = false;
145 };
146
147 // static
148 subtle::Atomic32 BlockingConstructor::constructor_called_ = 0;
149 // static
150 subtle::Atomic32 BlockingConstructor::complete_construction_ = 0;
151
152 // A SimpleThread running at |thread_type| which invokes |before_get| (optional)
153 // and then invokes thread-safe scoped-static-initializationconstruction on its
154 // NoDestructor instance.
155 class BlockingConstructorThread : public SimpleThread {
156 public:
BlockingConstructorThread(ThreadType thread_type,OnceClosure before_get)157 BlockingConstructorThread(ThreadType thread_type, OnceClosure before_get)
158 : SimpleThread("BlockingConstructorThread", Options(thread_type)),
159 before_get_(std::move(before_get)) {}
160 BlockingConstructorThread(const BlockingConstructorThread&) = delete;
161 BlockingConstructorThread& operator=(const BlockingConstructorThread&) =
162 delete;
163
Run()164 void Run() override {
165 if (before_get_)
166 std::move(before_get_).Run();
167
168 static NoDestructor<BlockingConstructor> instance;
169 EXPECT_TRUE(instance->done_construction());
170 }
171
172 private:
173 OnceClosure before_get_;
174 };
175
176 } // namespace
177
178 // Tests that if the thread assigned to construct the local-static
179 // initialization of the NoDestructor runs at background priority : the
180 // foreground threads will yield to it enough for it to eventually complete
181 // construction. While local-static thread-safe initialization isn't specific to
182 // NoDestructor, it is tested here as NoDestructor is set to replace
183 // LazyInstance and this is an important regression test for it
184 // (https://crbug.com/797129).
TEST(NoDestructorTest,PriorityInversionAtStaticInitializationResolves)185 TEST(NoDestructorTest, PriorityInversionAtStaticInitializationResolves) {
186 TimeTicks test_begin = TimeTicks::Now();
187
188 // Construct BlockingConstructor from a thread that is lower priority than the
189 // other threads that will be constructed. This thread used to be BACKGROUND
190 // priority but that caused it to be starved by other simultaneously running
191 // test processes, leading to false-positive failures.
192 BlockingConstructorThread background_getter(ThreadType::kDefault,
193 OnceClosure());
194 background_getter.Start();
195
196 while (!BlockingConstructor::WasConstructorCalled())
197 PlatformThread::Sleep(Milliseconds(1));
198
199 // Spin 4 foreground thread per core contending to get the already under
200 // construction NoDestructor. When they are all running and poking at it :
201 // allow the background thread to complete its work.
202 const int kNumForegroundThreads = 4 * SysInfo::NumberOfProcessors();
203 std::vector<std::unique_ptr<SimpleThread>> foreground_threads;
204 RepeatingClosure foreground_thread_ready_callback =
205 BarrierClosure(kNumForegroundThreads,
206 BindOnce(&BlockingConstructor::CompleteConstructionNow));
207 for (int i = 0; i < kNumForegroundThreads; ++i) {
208 // Create threads that are higher priority than background_getter. See above
209 // for why these particular priorities are chosen.
210 foreground_threads.push_back(std::make_unique<BlockingConstructorThread>(
211 ThreadType::kDisplayCritical, foreground_thread_ready_callback));
212 foreground_threads.back()->Start();
213 }
214
215 // This test will hang if the foreground threads become stuck in
216 // NoDestructor's construction per the background thread never being scheduled
217 // to complete construction.
218 for (auto& foreground_thread : foreground_threads)
219 foreground_thread->Join();
220 background_getter.Join();
221
222 // Fail if this test takes more than 5 seconds (it takes 5-10 seconds on a
223 // Z840 without https://crrev.com/527445 but is expected to be fast (~30ms)
224 // with the fix).
225 EXPECT_LT(TimeTicks::Now() - test_begin, Seconds(5));
226 }
227
228 } // namespace base
229