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