1 /*
2  * Copyright (C) 2011 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef ART_RUNTIME_BASE_MUTEX_H_
18 #define ART_RUNTIME_BASE_MUTEX_H_
19 
20 #include <limits.h>  // for INT_MAX
21 #include <pthread.h>
22 #include <stdint.h>
23 #include <unistd.h>  // for pid_t
24 
25 #include <iosfwd>
26 #include <string>
27 
28 #include <android-base/logging.h>
29 
30 #include "base/aborting.h"
31 #include "base/atomic.h"
32 #include "runtime_globals.h"
33 #include "base/macros.h"
34 #include "locks.h"
35 
36 #if defined(__linux__)
37 #define ART_USE_FUTEXES 1
38 #else
39 #define ART_USE_FUTEXES 0
40 #endif
41 
42 // Currently Darwin doesn't support locks with timeouts.
43 #if !defined(__APPLE__)
44 #define HAVE_TIMED_RWLOCK 1
45 #else
46 #define HAVE_TIMED_RWLOCK 0
47 #endif
48 
49 namespace art HIDDEN {
50 
51 class SHARED_LOCKABLE ReaderWriterMutex;
52 class SHARED_LOCKABLE MutatorMutex;
53 class ScopedContentionRecorder;
54 class Thread;
55 class LOCKABLE Mutex;
56 
57 constexpr bool kDebugLocking = kIsDebugBuild;
58 
59 // Record Log contention information, dumpable via SIGQUIT.
60 #if ART_USE_FUTEXES
61 // To enable lock contention logging, set this to true.
62 constexpr bool kLogLockContentions = false;
63 // FUTEX_WAKE first argument:
64 constexpr int kWakeOne = 1;
65 constexpr int kWakeAll = INT_MAX;
66 #else
67 // Keep this false as lock contention logging is supported only with
68 // futex.
69 constexpr bool kLogLockContentions = false;
70 #endif
71 constexpr size_t kContentionLogSize = 4;
72 constexpr size_t kContentionLogDataSize = kLogLockContentions ? 1 : 0;
73 constexpr size_t kAllMutexDataSize = kLogLockContentions ? 1 : 0;
74 
75 // Base class for all Mutex implementations
76 class BaseMutex {
77  public:
GetName()78   const char* GetName() const {
79     return name_;
80   }
81 
IsMutex()82   virtual bool IsMutex() const { return false; }
IsReaderWriterMutex()83   virtual bool IsReaderWriterMutex() const { return false; }
IsMutatorMutex()84   virtual bool IsMutatorMutex() const { return false; }
85 
86   virtual void Dump(std::ostream& os) const = 0;
87 
88   static void DumpAll(std::ostream& os);
89 
ShouldRespondToEmptyCheckpointRequest()90   bool ShouldRespondToEmptyCheckpointRequest() const {
91     return should_respond_to_empty_checkpoint_request_;
92   }
93 
SetShouldRespondToEmptyCheckpointRequest(bool value)94   void SetShouldRespondToEmptyCheckpointRequest(bool value) {
95     should_respond_to_empty_checkpoint_request_ = value;
96   }
97 
98   virtual void WakeupToRespondToEmptyCheckpoint() = 0;
99 
100  protected:
101   friend class ConditionVariable;
102 
103   BaseMutex(const char* name, LockLevel level);
104   virtual ~BaseMutex();
105 
106   // Add this mutex to those owned by self, and optionally perform lock order checking.  Caller
107   // may wish to disable checking for trylock calls that cannot result in deadlock.  For this call
108   // only, self may also be another suspended thread.
109   void RegisterAsLocked(Thread* self, bool check = kDebugLocking);
110   void RegisterAsLockedImpl(Thread* self, LockLevel level, bool check);
111 
112   void RegisterAsUnlocked(Thread* self);
113   void RegisterAsUnlockedImpl(Thread* self, LockLevel level);
114 
115   void CheckSafeToWait(Thread* self);
116 
117   friend class ScopedContentionRecorder;
118 
119   void RecordContention(uint64_t blocked_tid, uint64_t owner_tid, uint64_t nano_time_blocked);
120   void DumpContention(std::ostream& os) const;
121 
122   const char* const name_;
123 
124   // A log entry that records contention but makes no guarantee that either tid will be held live.
125   struct ContentionLogEntry {
ContentionLogEntryContentionLogEntry126     ContentionLogEntry() : blocked_tid(0), owner_tid(0) {}
127     uint64_t blocked_tid;
128     uint64_t owner_tid;
129     AtomicInteger count;
130   };
131   struct ContentionLogData {
132     ContentionLogEntry contention_log[kContentionLogSize];
133     // The next entry in the contention log to be updated. Value ranges from 0 to
134     // kContentionLogSize - 1.
135     AtomicInteger cur_content_log_entry;
136     // Number of times the Mutex has been contended.
137     AtomicInteger contention_count;
138     // Sum of time waited by all contenders in ns.
139     Atomic<uint64_t> wait_time;
140     void AddToWaitTime(uint64_t value);
ContentionLogDataContentionLogData141     ContentionLogData() : wait_time(0) {}
142   };
143   ContentionLogData contention_log_data_[kContentionLogDataSize];
144 
145   const LockLevel level_;  // Support for lock hierarchy.
146   bool should_respond_to_empty_checkpoint_request_;
147 
148  public:
HasEverContended()149   bool HasEverContended() const {
150     if (kLogLockContentions) {
151       return contention_log_data_->contention_count.load(std::memory_order_seq_cst) > 0;
152     }
153     return false;
154   }
155 };
156 
157 // A Mutex is used to achieve mutual exclusion between threads. A Mutex can be used to gain
158 // exclusive access to what it guards. A Mutex can be in one of two states:
159 // - Free - not owned by any thread,
160 // - Exclusive - owned by a single thread.
161 //
162 // The effect of locking and unlocking operations on the state is:
163 // State     | ExclusiveLock | ExclusiveUnlock
164 // -------------------------------------------
165 // Free      | Exclusive     | error
166 // Exclusive | Block*        | Free
167 // * Mutex is not reentrant unless recursive is true. An attempt to ExclusiveLock on a
168 // recursive=false Mutex on a thread already owning the Mutex results in an error.
169 //
170 // TODO(b/140590186): Remove support for recursive == true.
171 //
172 // Some mutexes, including those associated with Java monitors may be accessed (in particular
173 // acquired) by a thread in suspended state. Suspending all threads does NOT prevent mutex state
174 // from changing.
175 std::ostream& operator<<(std::ostream& os, const Mutex& mu);
176 class EXPORT LOCKABLE Mutex : public BaseMutex {
177  public:
178   explicit Mutex(const char* name, LockLevel level = kDefaultMutexLevel, bool recursive = false);
179   ~Mutex();
180 
IsMutex()181   bool IsMutex() const override { return true; }
182 
183   // Block until mutex is free then acquire exclusive access.
184   void ExclusiveLock(Thread* self) ACQUIRE();
Lock(Thread * self)185   void Lock(Thread* self) ACQUIRE() {  ExclusiveLock(self); }
186 
187   // Returns true if acquires exclusive access, false otherwise. The `check` argument specifies
188   // whether lock level checking should be performed.  Should be defaulted unless we are using
189   // TryLock instead of Lock for deadlock avoidance.
190   template <bool kCheck = kDebugLocking>
191   bool ExclusiveTryLock(Thread* self) TRY_ACQUIRE(true);
TryLock(Thread * self)192   bool TryLock(Thread* self) TRY_ACQUIRE(true) { return ExclusiveTryLock(self); }
193   // Equivalent to ExclusiveTryLock, but retry for a short period before giving up.
194   bool ExclusiveTryLockWithSpinning(Thread* self) TRY_ACQUIRE(true);
195 
196   // Release exclusive access.
197   void ExclusiveUnlock(Thread* self) RELEASE();
Unlock(Thread * self)198   void Unlock(Thread* self) RELEASE() {  ExclusiveUnlock(self); }
199 
200   // Is the current thread the exclusive holder of the Mutex.
201   ALWAYS_INLINE bool IsExclusiveHeld(const Thread* self) const;
202 
203   // Assert that the Mutex is exclusively held by the current thread.
204   ALWAYS_INLINE void AssertExclusiveHeld(const Thread* self) const ASSERT_CAPABILITY(this);
205   ALWAYS_INLINE void AssertHeld(const Thread* self) const ASSERT_CAPABILITY(this);
206 
207   // Assert that the Mutex is not held by the current thread.
AssertNotHeldExclusive(const Thread * self)208   void AssertNotHeldExclusive(const Thread* self) ASSERT_CAPABILITY(!*this) {
209     if (kDebugLocking && (gAborting == 0)) {
210       CHECK(!IsExclusiveHeld(self)) << *this;
211     }
212   }
AssertNotHeld(const Thread * self)213   void AssertNotHeld(const Thread* self) ASSERT_CAPABILITY(!*this) {
214     AssertNotHeldExclusive(self);
215   }
216 
217   // Id associated with exclusive owner. No memory ordering semantics if called from a thread
218   // other than the owner. GetTid() == GetExclusiveOwnerTid() is a reliable way to determine
219   // whether we hold the lock; any other information may be invalidated before we return.
220   pid_t GetExclusiveOwnerTid() const;
221 
222   // Returns how many times this Mutex has been locked, it is typically better to use
223   // AssertHeld/NotHeld. For a simply held mutex this method returns 1. Should only be called
224   // while holding the mutex or threads are suspended.
GetDepth()225   unsigned int GetDepth() const {
226     return recursion_count_;
227   }
228 
229   void Dump(std::ostream& os) const override;
230 
231   void DumpStack(Thread *self, uint64_t wait_start_ms, uint64_t try_times = 1);
232 
233   static bool IsDumpFrequent(Thread *self, uint64_t try_times = 1);
234 
setEnableMonitorTimeout()235   void setEnableMonitorTimeout() {
236     enable_monitor_timeout_ = true;
237   }
238 
setMonitorId(uint32_t monitorId)239   void setMonitorId(uint32_t monitorId) {
240     monitor_id_ = monitorId;
241   }
242 
243   // For negative capabilities in clang annotations.
244   const Mutex& operator!() const { return *this; }
245 
246   void WakeupToRespondToEmptyCheckpoint() override;
247 
248 #if ART_USE_FUTEXES
249   // Acquire the mutex, possibly on behalf of another thread. Acquisition must be
250   // uncontended. New_owner must be current thread or suspended.
251   // Mutex must be at level kMonitorLock.
252   // Not implementable for the pthreads version, so we must avoid calling it there.
253   void ExclusiveLockUncontendedFor(Thread* new_owner);
254 
255   // Undo the effect of the previous calling, setting the mutex back to unheld.
256   // Still assumes no concurrent access.
257   void ExclusiveUnlockUncontended();
258 #endif  // ART_USE_FUTEXES
259 
260  private:
261 #if ART_USE_FUTEXES
262   // Low order bit: 0 is unheld, 1 is held.
263   // High order bits: Number of waiting contenders.
264   AtomicInteger state_and_contenders_;
265 
266   static constexpr int32_t kHeldMask = 1;
267 
268   static constexpr int32_t kContenderShift = 1;
269 
270   static constexpr int32_t kContenderIncrement = 1 << kContenderShift;
271 
increment_contenders()272   void increment_contenders() {
273     state_and_contenders_.fetch_add(kContenderIncrement);
274   }
275 
decrement_contenders()276   void decrement_contenders() {
277     state_and_contenders_.fetch_sub(kContenderIncrement);
278   }
279 
get_contenders()280   int32_t get_contenders() {
281     // Result is guaranteed to include any contention added by this thread; otherwise approximate.
282     // Treat contenders as unsigned because we're concerned about overflow; should never matter.
283     return static_cast<uint32_t>(state_and_contenders_.load(std::memory_order_relaxed))
284         >> kContenderShift;
285   }
286 
287   // Exclusive owner.
288   Atomic<pid_t> exclusive_owner_;
289 #else
290   pthread_mutex_t mutex_;
291   Atomic<pid_t> exclusive_owner_;  // Guarded by mutex_. Asynchronous reads are OK.
292 #endif
293 
294   unsigned int recursion_count_;
295   const bool recursive_;  // Can the lock be recursively held?
296 
297   bool enable_monitor_timeout_ = false;
298 
299   uint32_t monitor_id_;
300 
301   friend class ConditionVariable;
302   DISALLOW_COPY_AND_ASSIGN(Mutex);
303 };
304 
305 // A ReaderWriterMutex is used to achieve mutual exclusion between threads, similar to a Mutex.
306 // Unlike a Mutex a ReaderWriterMutex can be used to gain exclusive (writer) or shared (reader)
307 // access to what it guards. A flaw in relation to a Mutex is that it cannot be used with a
308 // condition variable. A ReaderWriterMutex can be in one of three states:
309 // - Free - not owned by any thread,
310 // - Exclusive - owned by a single thread,
311 // - Shared(n) - shared amongst n threads.
312 //
313 // The effect of locking and unlocking operations on the state is:
314 //
315 // State     | ExclusiveLock | ExclusiveUnlock | SharedLock       | SharedUnlock
316 // ----------------------------------------------------------------------------
317 // Free      | Exclusive     | error           | SharedLock(1)    | error
318 // Exclusive | Block         | Free            | Block            | error
319 // Shared(n) | Block         | error           | SharedLock(n+1)* | Shared(n-1) or Free
320 // * for large values of n the SharedLock may block.
321 EXPORT std::ostream& operator<<(std::ostream& os, const ReaderWriterMutex& mu);
322 class EXPORT SHARED_LOCKABLE ReaderWriterMutex : public BaseMutex {
323  public:
324   explicit ReaderWriterMutex(const char* name, LockLevel level = kDefaultMutexLevel);
325   ~ReaderWriterMutex();
326 
IsReaderWriterMutex()327   bool IsReaderWriterMutex() const override { return true; }
328 
329   // Block until ReaderWriterMutex is free then acquire exclusive access.
330   void ExclusiveLock(Thread* self) ACQUIRE();
WriterLock(Thread * self)331   void WriterLock(Thread* self) ACQUIRE() {  ExclusiveLock(self); }
332 
333   // Release exclusive access.
334   void ExclusiveUnlock(Thread* self) RELEASE();
WriterUnlock(Thread * self)335   void WriterUnlock(Thread* self) RELEASE() {  ExclusiveUnlock(self); }
336 
337   // Block until ReaderWriterMutex is free and acquire exclusive access. Returns true on success
338   // or false if timeout is reached.
339 #if HAVE_TIMED_RWLOCK
340   bool ExclusiveLockWithTimeout(Thread* self, int64_t ms, int32_t ns)
341       EXCLUSIVE_TRYLOCK_FUNCTION(true);
342 #endif
343 
344   // Block until ReaderWriterMutex is shared or free then acquire a share on the access.
345   void SharedLock(Thread* self) ACQUIRE_SHARED() ALWAYS_INLINE;
ReaderLock(Thread * self)346   void ReaderLock(Thread* self) ACQUIRE_SHARED() { SharedLock(self); }
347 
348   // Try to acquire share of ReaderWriterMutex.
349   bool SharedTryLock(Thread* self, bool check = kDebugLocking) SHARED_TRYLOCK_FUNCTION(true);
350 
351   // Release a share of the access.
352   void SharedUnlock(Thread* self) RELEASE_SHARED() ALWAYS_INLINE;
ReaderUnlock(Thread * self)353   void ReaderUnlock(Thread* self) RELEASE_SHARED() { SharedUnlock(self); }
354 
355   // Is the current thread the exclusive holder of the ReaderWriterMutex.
356   ALWAYS_INLINE bool IsExclusiveHeld(const Thread* self) const;
357 
358   // Assert the current thread has exclusive access to the ReaderWriterMutex.
359   ALWAYS_INLINE void AssertExclusiveHeld(const Thread* self) const ASSERT_CAPABILITY(this);
360   ALWAYS_INLINE void AssertWriterHeld(const Thread* self) const ASSERT_CAPABILITY(this);
361 
362   // Assert the current thread doesn't have exclusive access to the ReaderWriterMutex.
AssertNotExclusiveHeld(const Thread * self)363   void AssertNotExclusiveHeld(const Thread* self) ASSERT_CAPABILITY(!this) {
364     if (kDebugLocking && (gAborting == 0)) {
365       CHECK(!IsExclusiveHeld(self)) << *this;
366     }
367   }
AssertNotWriterHeld(const Thread * self)368   void AssertNotWriterHeld(const Thread* self) ASSERT_CAPABILITY(!this) {
369     AssertNotExclusiveHeld(self);
370   }
371 
372   // Is the current thread a shared holder of the ReaderWriterMutex.
373   bool IsSharedHeld(const Thread* self) const;
374 
375   // Assert the current thread has shared access to the ReaderWriterMutex.
AssertSharedHeld(const Thread * self)376   ALWAYS_INLINE void AssertSharedHeld(const Thread* self) ASSERT_SHARED_CAPABILITY(this) {
377     if (kDebugLocking && (gAborting == 0)) {
378       // TODO: we can only assert this well when self != null.
379       CHECK(IsSharedHeld(self) || self == nullptr) << *this;
380     }
381   }
AssertReaderHeld(const Thread * self)382   ALWAYS_INLINE void AssertReaderHeld(const Thread* self) ASSERT_SHARED_CAPABILITY(this) {
383     AssertSharedHeld(self);
384   }
385 
386   // Assert the current thread doesn't hold this ReaderWriterMutex either in shared or exclusive
387   // mode.
AssertNotHeld(const Thread * self)388   ALWAYS_INLINE void AssertNotHeld(const Thread* self) ASSERT_CAPABILITY(!this) {
389     if (kDebugLocking && (gAborting == 0)) {
390       CHECK(!IsExclusiveHeld(self)) << *this;
391       CHECK(!IsSharedHeld(self)) << *this;
392     }
393   }
394 
395   // Id associated with exclusive owner. No memory ordering semantics if called from a thread other
396   // than the owner. Returns 0 if the lock is not held. Returns either 0 or -1 if it is held by
397   // one or more readers.
398   pid_t GetExclusiveOwnerTid() const;
399 
400   void Dump(std::ostream& os) const override;
401 
402   // For negative capabilities in clang annotations.
403   const ReaderWriterMutex& operator!() const { return *this; }
404 
405   void WakeupToRespondToEmptyCheckpoint() override;
406 
407  private:
408 #if ART_USE_FUTEXES
409   // Out-of-inline path for handling contention for a SharedLock.
410   void HandleSharedLockContention(Thread* self, int32_t cur_state);
411 
412   // -1 implies held exclusive, >= 0: shared held by state_ many owners.
413   AtomicInteger state_;
414   // Exclusive owner. Modification guarded by this mutex.
415   Atomic<pid_t> exclusive_owner_;
416   // Number of contenders waiting for either a reader share or exclusive access.  We only maintain
417   // the sum, since we would otherwise need to read both in all unlock operations.
418   // We keep this separate from the state, since futexes are limited to 32 bits, and obvious
419   // approaches to combining with state_ risk overflow.
420   AtomicInteger num_contenders_;
421 #else
422   pthread_rwlock_t rwlock_;
423   Atomic<pid_t> exclusive_owner_;  // Writes guarded by rwlock_. Asynchronous reads are OK.
424 #endif
425   DISALLOW_COPY_AND_ASSIGN(ReaderWriterMutex);
426 };
427 
428 // MutatorMutex is a special kind of ReaderWriterMutex created specifically for the
429 // Locks::mutator_lock_ mutex. The behaviour is identical to the ReaderWriterMutex except that
430 // thread state changes also play a part in lock ownership. The mutator_lock_ will not be truly
431 // held by any mutator threads. However, a thread in the kRunnable state is considered to have
432 // shared ownership of the mutator lock and therefore transitions in and out of the kRunnable
433 // state have associated implications on lock ownership. Extra methods to handle the state
434 // transitions have been added to the interface but are only accessible to the methods dealing
435 // with state transitions. The thread state and flags attributes are used to ensure thread state
436 // transitions are consistent with the permitted behaviour of the mutex.
437 //
438 // *) The most important consequence of this behaviour is that all threads must be in one of the
439 // suspended states before exclusive ownership of the mutator mutex is sought.
440 //
441 std::ostream& operator<<(std::ostream& os, const MutatorMutex& mu);
442 class SHARED_LOCKABLE MutatorMutex : public ReaderWriterMutex {
443  public:
444   explicit MutatorMutex(const char* name, LockLevel level = kDefaultMutexLevel)
ReaderWriterMutex(name,level)445     : ReaderWriterMutex(name, level) {}
~MutatorMutex()446   ~MutatorMutex() {}
447 
IsMutatorMutex()448   virtual bool IsMutatorMutex() const { return true; }
449 
450   // For negative capabilities in clang annotations.
451   const MutatorMutex& operator!() const { return *this; }
452 
453  private:
454   friend class Thread;
455   void TransitionFromRunnableToSuspended(Thread* self) UNLOCK_FUNCTION() ALWAYS_INLINE;
456   void TransitionFromSuspendedToRunnable(Thread* self) SHARED_LOCK_FUNCTION() ALWAYS_INLINE;
457 
458   DISALLOW_COPY_AND_ASSIGN(MutatorMutex);
459 };
460 
461 // ConditionVariables allow threads to queue and sleep. Threads may then be resumed individually
462 // (Signal) or all at once (Broadcast).
463 class EXPORT ConditionVariable {
464  public:
465   ConditionVariable(const char* name, Mutex& mutex);
466   ~ConditionVariable();
467 
468   // Requires the mutex to be held.
469   void Broadcast(Thread* self);
470   // Requires the mutex to be held.
471   void Signal(Thread* self);
472   // TODO: No thread safety analysis on Wait and TimedWait as they call mutex operations via their
473   //       pointer copy, thereby defeating annotalysis.
474   void Wait(Thread* self) NO_THREAD_SAFETY_ANALYSIS;
475   bool TimedWait(Thread* self, int64_t ms, int32_t ns) NO_THREAD_SAFETY_ANALYSIS;
476   // Variant of Wait that should be used with caution. Doesn't validate that no mutexes are held
477   // when waiting.
478   // TODO: remove this.
479   void WaitHoldingLocks(Thread* self) NO_THREAD_SAFETY_ANALYSIS;
480 
CheckSafeToWait(Thread * self)481   void CheckSafeToWait(Thread* self) NO_THREAD_SAFETY_ANALYSIS {
482     if (kDebugLocking) {
483       guard_.CheckSafeToWait(self);
484     }
485   }
486 
487  private:
488   const char* const name_;
489   // The Mutex being used by waiters. It is an error to mix condition variables between different
490   // Mutexes.
491   Mutex& guard_;
492 #if ART_USE_FUTEXES
493   // A counter that is modified by signals and broadcasts. This ensures that when a waiter gives up
494   // their Mutex and another thread takes it and signals, the waiting thread observes that sequence_
495   // changed and doesn't enter the wait. Modified while holding guard_, but is read by futex wait
496   // without guard_ held.
497   AtomicInteger sequence_;
498   // Number of threads that have come into to wait, not the length of the waiters on the futex as
499   // waiters may have been requeued onto guard_. Guarded by guard_.
500   int32_t num_waiters_;
501 
502   void RequeueWaiters(int32_t count);
503 #else
504   pthread_cond_t cond_;
505 #endif
506   DISALLOW_COPY_AND_ASSIGN(ConditionVariable);
507 };
508 
509 // Scoped locker/unlocker for a regular Mutex that acquires mu upon construction and releases it
510 // upon destruction.
511 class SCOPED_CAPABILITY MutexLock {
512  public:
MutexLock(Thread * self,Mutex & mu)513   MutexLock(Thread* self, Mutex& mu) ACQUIRE(mu) : self_(self), mu_(mu) {
514     mu_.ExclusiveLock(self_);
515   }
516 
RELEASE()517   ~MutexLock() RELEASE() {
518     mu_.ExclusiveUnlock(self_);
519   }
520 
521  private:
522   Thread* const self_;
523   Mutex& mu_;
524   DISALLOW_COPY_AND_ASSIGN(MutexLock);
525 };
526 
527 // Pretend to acquire a mutex for checking purposes, without actually doing so. Use with
528 // extreme caution when it is known the condition that the mutex would guard against cannot arise.
529 class SCOPED_CAPABILITY FakeMutexLock {
530  public:
FakeMutexLock(Mutex & mu)531   explicit FakeMutexLock(Mutex& mu) ACQUIRE(mu) NO_THREAD_SAFETY_ANALYSIS {}
532 
RELEASE()533   ~FakeMutexLock() RELEASE() NO_THREAD_SAFETY_ANALYSIS {}
534 
535  private:
536   DISALLOW_COPY_AND_ASSIGN(FakeMutexLock);
537 };
538 
539 // Scoped locker/unlocker for a ReaderWriterMutex that acquires read access to mu upon
540 // construction and releases it upon destruction.
541 class SCOPED_CAPABILITY ReaderMutexLock {
542  public:
543   ALWAYS_INLINE ReaderMutexLock(Thread* self, ReaderWriterMutex& mu) ACQUIRE(mu);
544 
545   ALWAYS_INLINE ~ReaderMutexLock() RELEASE();
546 
547  private:
548   Thread* const self_;
549   ReaderWriterMutex& mu_;
550   DISALLOW_COPY_AND_ASSIGN(ReaderMutexLock);
551 };
552 
553 // Scoped locker/unlocker for a ReaderWriterMutex that acquires write access to mu upon
554 // construction and releases it upon destruction.
555 class SCOPED_CAPABILITY WriterMutexLock {
556  public:
WriterMutexLock(Thread * self,ReaderWriterMutex & mu)557   WriterMutexLock(Thread* self, ReaderWriterMutex& mu) EXCLUSIVE_LOCK_FUNCTION(mu) :
558       self_(self), mu_(mu) {
559     mu_.ExclusiveLock(self_);
560   }
561 
UNLOCK_FUNCTION()562   ~WriterMutexLock() UNLOCK_FUNCTION() {
563     mu_.ExclusiveUnlock(self_);
564   }
565 
566  private:
567   Thread* const self_;
568   ReaderWriterMutex& mu_;
569   DISALLOW_COPY_AND_ASSIGN(WriterMutexLock);
570 };
571 
572 }  // namespace art
573 
574 #endif  // ART_RUNTIME_BASE_MUTEX_H_
575