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.
5 #include "base/no_destructor.h"
12 #include "base/atomicops.h"
13 #include "base/barrier_closure.h"
14 #include "base/bind.h"
15 #include "base/check.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"
26 static_assert(!std::is_trivially_destructible_v<std::string>);
28 std::is_trivially_destructible_v<base::NoDestructor<std::string>>);
30 struct CheckOnDestroy {
31 ~CheckOnDestroy() { CHECK(false); }
34 TEST(NoDestructorTest, SkipsDestructors) {
35 NoDestructor<CheckOnDestroy> destructor_should_not_run;
38 struct UncopyableUnmovable {
39 UncopyableUnmovable() = default;
40 explicit UncopyableUnmovable(int value) : value(value) {}
42 UncopyableUnmovable(const UncopyableUnmovable&) = delete;
43 UncopyableUnmovable& operator=(const UncopyableUnmovable&) = delete;
46 std::string something_with_a_nontrivial_destructor;
52 CopyOnly(const CopyOnly&) = default;
53 CopyOnly& operator=(const CopyOnly&) = default;
55 CopyOnly(CopyOnly&&) = delete;
56 CopyOnly& operator=(CopyOnly&&) = delete;
62 MoveOnly(const MoveOnly&) = delete;
63 MoveOnly& operator=(const MoveOnly&) = delete;
65 MoveOnly(MoveOnly&&) = default;
66 MoveOnly& operator=(MoveOnly&&) = default;
69 struct ForwardingTestStruct {
70 ForwardingTestStruct(const CopyOnly&, MoveOnly&&) {}
72 std::string something_with_a_nontrivial_destructor;
75 TEST(NoDestructorTest, UncopyableUnmovable) {
76 static NoDestructor<UncopyableUnmovable> default_constructed;
77 EXPECT_EQ(1, default_constructed->value);
79 static NoDestructor<UncopyableUnmovable> constructed_with_arg(-1);
80 EXPECT_EQ(-1, constructed_with_arg->value);
83 TEST(NoDestructorTest, ForwardsArguments) {
87 static NoDestructor<ForwardingTestStruct> test_forwarding(
88 copy_only, std::move(move_only));
91 TEST(NoDestructorTest, Accessors) {
92 static NoDestructor<std::string> awesome("awesome");
94 EXPECT_EQ("awesome", *awesome);
95 EXPECT_EQ(0, awesome->compare("awesome"));
96 EXPECT_EQ(0, awesome.get()->compare("awesome"));
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__)
103 TEST(NoDestructorTest, InitializerList) {
104 static NoDestructor<std::vector<std::string>> vector({"a", "b", "c"});
111 // A class whose constructor busy-loops until it is told to complete
113 class 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;
123 BlockingConstructor(const BlockingConstructor&) = delete;
124 BlockingConstructor& operator=(const BlockingConstructor&) = delete;
125 ~BlockingConstructor() = delete;
127 // Returns true if BlockingConstructor() was entered.
128 static bool WasConstructorCalled() {
129 return subtle::NoBarrier_Load(&constructor_called_);
132 // Instructs BlockingConstructor() that it may now unblock its construction.
133 static void CompleteConstructionNow() {
134 subtle::NoBarrier_Store(&complete_construction_, 1);
137 bool done_construction() const { return done_construction_; }
140 // Use Atomic32 instead of AtomicFlag for them to be trivially initialized.
141 static subtle::Atomic32 constructor_called_;
142 static subtle::Atomic32 complete_construction_;
144 bool done_construction_ = false;
148 subtle::Atomic32 BlockingConstructor::constructor_called_ = 0;
150 subtle::Atomic32 BlockingConstructor::complete_construction_ = 0;
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 {
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&) =
164 void Run() override {
166 std::move(before_get_).Run();
168 static NoDestructor<BlockingConstructor> instance;
169 EXPECT_TRUE(instance->done_construction());
173 OnceClosure before_get_;
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).
185 TEST(NoDestructorTest, PriorityInversionAtStaticInitializationResolves) {
186 TimeTicks test_begin = TimeTicks::Now();
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,
194 background_getter.Start();
196 while (!BlockingConstructor::WasConstructorCalled())
197 PlatformThread::Sleep(Milliseconds(1));
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();
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();
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)
225 EXPECT_LT(TimeTicks::Now() - test_begin, Seconds(5));