1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef BASE_THREADING_THREAD_COLLISION_WARNER_H_
6 #define BASE_THREADING_THREAD_COLLISION_WARNER_H_
7 
8 #include <memory>
9 
10 #include "base/atomicops.h"
11 #include "base/base_export.h"
12 #include "base/compiler_specific.h"
13 #include "base/macros.h"
14 
15 // A helper class alongside macros to be used to verify assumptions about thread
16 // safety of a class.
17 //
18 // Example: Queue implementation non thread-safe but still usable if clients
19 //          are synchronized somehow.
20 //
21 //          In this case the macro DFAKE_SCOPED_LOCK has to be
22 //          used, it checks that if a thread is inside the push/pop then
23 //          noone else is still inside the pop/push
24 //
25 // class NonThreadSafeQueue {
26 //  public:
27 //   ...
28 //   void push(int) { DFAKE_SCOPED_LOCK(push_pop_); ... }
29 //   int pop() { DFAKE_SCOPED_LOCK(push_pop_); ... }
30 //   ...
31 //  private:
32 //   DFAKE_MUTEX(push_pop_);
33 // };
34 //
35 //
36 // Example: Queue implementation non thread-safe but still usable if clients
37 //          are synchronized somehow, it calls a method to "protect" from
38 //          a "protected" method
39 //
40 //          In this case the macro DFAKE_SCOPED_RECURSIVE_LOCK
41 //          has to be used, it checks that if a thread is inside the push/pop
42 //          then noone else is still inside the pop/push
43 //
44 // class NonThreadSafeQueue {
45 //  public:
46 //   void push(int) {
47 //     DFAKE_SCOPED_LOCK(push_pop_);
48 //     ...
49 //   }
50 //   int pop() {
51 //     DFAKE_SCOPED_RECURSIVE_LOCK(push_pop_);
52 //     bar();
53 //     ...
54 //   }
55 //   void bar() { DFAKE_SCOPED_RECURSIVE_LOCK(push_pop_); ... }
56 //   ...
57 //  private:
58 //   DFAKE_MUTEX(push_pop_);
59 // };
60 //
61 //
62 // Example: Queue implementation not usable even if clients are synchronized,
63 //          so only one thread in the class life cycle can use the two members
64 //          push/pop.
65 //
66 //          In this case the macro DFAKE_SCOPED_LOCK_THREAD_LOCKED pins the
67 //          specified
68 //          critical section the first time a thread enters push or pop, from
69 //          that time on only that thread is allowed to execute push or pop.
70 //
71 // class NonThreadSafeQueue {
72 //  public:
73 //   ...
74 //   void push(int) { DFAKE_SCOPED_LOCK_THREAD_LOCKED(push_pop_); ... }
75 //   int pop() { DFAKE_SCOPED_LOCK_THREAD_LOCKED(push_pop_); ... }
76 //   ...
77 //  private:
78 //   DFAKE_MUTEX(push_pop_);
79 // };
80 //
81 //
82 // Example: Class that has to be contructed/destroyed on same thread, it has
83 //          a "shareable" method (with external synchronization) and a not
84 //          shareable method (even with external synchronization).
85 //
86 //          In this case 3 Critical sections have to be defined
87 //
88 // class ExoticClass {
89 //  public:
90 //   ExoticClass() { DFAKE_SCOPED_LOCK_THREAD_LOCKED(ctor_dtor_); ... }
91 //   ~ExoticClass() { DFAKE_SCOPED_LOCK_THREAD_LOCKED(ctor_dtor_); ... }
92 //
93 //   void Shareable() { DFAKE_SCOPED_LOCK(shareable_section_); ... }
94 //   void NotShareable() { DFAKE_SCOPED_LOCK_THREAD_LOCKED(ctor_dtor_); ... }
95 //   ...
96 //  private:
97 //   DFAKE_MUTEX(ctor_dtor_);
98 //   DFAKE_MUTEX(shareable_section_);
99 // };
100 
101 
102 #if !defined(NDEBUG)
103 
104 #define DFAKE_UNIQUE_VARIABLE_CONCAT(a, b) a##b
105 // CONCAT1 provides extra level of indirection so that __LINE__ macro expands.
106 #define DFAKE_UNIQUE_VARIABLE_CONCAT1(a, b) DFAKE_UNIQUE_VARIABLE_CONCAT(a, b)
107 #define DFAKE_UNIQUE_VARIABLE_NAME(a) DFAKE_UNIQUE_VARIABLE_CONCAT1(a, __LINE__)
108 
109 // Defines a class member that acts like a mutex. It is used only as a
110 // verification tool.
111 #define DFAKE_MUTEX(obj) \
112      mutable base::ThreadCollisionWarner obj
113 // Asserts the call is never called simultaneously in two threads. Used at
114 // member function scope.
115 #define DFAKE_SCOPED_LOCK(obj)                                         \
116   base::ThreadCollisionWarner::ScopedCheck DFAKE_UNIQUE_VARIABLE_NAME( \
117       s_check_)(&obj)
118 // Asserts the call is never called simultaneously in two threads. Used at
119 // member function scope. Same as DFAKE_SCOPED_LOCK but allows recursive locks.
120 #define DFAKE_SCOPED_RECURSIVE_LOCK(obj)            \
121   base::ThreadCollisionWarner::ScopedRecursiveCheck \
122       DFAKE_UNIQUE_VARIABLE_NAME(sr_check)(&obj)
123 // Asserts the code is always executed in the same thread.
124 #define DFAKE_SCOPED_LOCK_THREAD_LOCKED(obj) \
125   base::ThreadCollisionWarner::Check DFAKE_UNIQUE_VARIABLE_NAME(check_)(&obj)
126 
127 #else
128 
129 #define DFAKE_MUTEX(obj) typedef void InternalFakeMutexType##obj
130 #define DFAKE_SCOPED_LOCK(obj) ((void)0)
131 #define DFAKE_SCOPED_RECURSIVE_LOCK(obj) ((void)0)
132 #define DFAKE_SCOPED_LOCK_THREAD_LOCKED(obj) ((void)0)
133 
134 #endif
135 
136 namespace base {
137 
138 // The class ThreadCollisionWarner uses an Asserter to notify the collision
139 // AsserterBase is the interfaces and DCheckAsserter is the default asserter
140 // used. During the unit tests is used another class that doesn't "DCHECK"
141 // in case of collision (check thread_collision_warner_unittests.cc)
142 struct BASE_EXPORT AsserterBase {
143   virtual ~AsserterBase() = default;
144   virtual void warn() = 0;
145 };
146 
147 struct BASE_EXPORT DCheckAsserter : public AsserterBase {
148   ~DCheckAsserter() override = default;
149   void warn() override;
150 };
151 
152 class BASE_EXPORT ThreadCollisionWarner {
153  public:
154   // The parameter asserter is there only for test purpose
155   explicit ThreadCollisionWarner(AsserterBase* asserter = new DCheckAsserter())
156       : valid_thread_id_(0),
157         counter_(0),
158         asserter_(asserter) {}
159 
~ThreadCollisionWarner()160   ~ThreadCollisionWarner() {
161     delete asserter_;
162   }
163 
164   // This class is meant to be used through the macro
165   // DFAKE_SCOPED_LOCK_THREAD_LOCKED
166   // it doesn't leave the critical section, as opposed to ScopedCheck,
167   // because the critical section being pinned is allowed to be used only
168   // from one thread
169   class BASE_EXPORT Check {
170    public:
Check(ThreadCollisionWarner * warner)171     explicit Check(ThreadCollisionWarner* warner)
172         : warner_(warner) {
173       warner_->EnterSelf();
174     }
175 
176     ~Check() = default;
177 
178    private:
179     ThreadCollisionWarner* warner_;
180 
181     DISALLOW_COPY_AND_ASSIGN(Check);
182   };
183 
184   // This class is meant to be used through the macro
185   // DFAKE_SCOPED_LOCK
186   class BASE_EXPORT ScopedCheck {
187    public:
ScopedCheck(ThreadCollisionWarner * warner)188     explicit ScopedCheck(ThreadCollisionWarner* warner)
189         : warner_(warner) {
190       warner_->Enter();
191     }
192 
~ScopedCheck()193     ~ScopedCheck() {
194       warner_->Leave();
195     }
196 
197    private:
198     ThreadCollisionWarner* warner_;
199 
200     DISALLOW_COPY_AND_ASSIGN(ScopedCheck);
201   };
202 
203   // This class is meant to be used through the macro
204   // DFAKE_SCOPED_RECURSIVE_LOCK
205   class BASE_EXPORT ScopedRecursiveCheck {
206    public:
ScopedRecursiveCheck(ThreadCollisionWarner * warner)207     explicit ScopedRecursiveCheck(ThreadCollisionWarner* warner)
208         : warner_(warner) {
209       warner_->EnterSelf();
210     }
211 
~ScopedRecursiveCheck()212     ~ScopedRecursiveCheck() {
213       warner_->Leave();
214     }
215 
216    private:
217     ThreadCollisionWarner* warner_;
218 
219     DISALLOW_COPY_AND_ASSIGN(ScopedRecursiveCheck);
220   };
221 
222  private:
223   // This method stores the current thread identifier and does a DCHECK
224   // if a another thread has already done it, it is safe if same thread
225   // calls this multiple time (recursion allowed).
226   void EnterSelf();
227 
228   // Same as EnterSelf but recursion is not allowed.
229   void Enter();
230 
231   // Removes the thread_id stored in order to allow other threads to
232   // call EnterSelf or Enter.
233   void Leave();
234 
235   // This stores the thread id that is inside the critical section, if the
236   // value is 0 then no thread is inside.
237   volatile subtle::Atomic32 valid_thread_id_;
238 
239   // Counter to trace how many time a critical section was "pinned"
240   // (when allowed) in order to unpin it when counter_ reaches 0.
241   volatile subtle::Atomic32 counter_;
242 
243   // Here only for class unit tests purpose, during the test I need to not
244   // DCHECK but notify the collision with something else.
245   AsserterBase* asserter_;
246 
247   DISALLOW_COPY_AND_ASSIGN(ThreadCollisionWarner);
248 };
249 
250 }  // namespace base
251 
252 #endif  // BASE_THREADING_THREAD_COLLISION_WARNER_H_
253