1 /*
2  * Copyright (C) 2008 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 #include "monitor.h"
18 
19 #include <vector>
20 
21 #include "base/mutex.h"
22 #include "base/stl_util.h"
23 #include "class_linker.h"
24 #include "dex_file-inl.h"
25 #include "dex_instruction.h"
26 #include "lock_word-inl.h"
27 #include "mirror/art_method-inl.h"
28 #include "mirror/class-inl.h"
29 #include "mirror/object-inl.h"
30 #include "mirror/object_array-inl.h"
31 #include "scoped_thread_state_change.h"
32 #include "thread.h"
33 #include "thread_list.h"
34 #include "verifier/method_verifier.h"
35 #include "well_known_classes.h"
36 
37 namespace art {
38 
39 static constexpr uint64_t kLongWaitMs = 100;
40 
41 /*
42  * Every Object has a monitor associated with it, but not every Object is actually locked.  Even
43  * the ones that are locked do not need a full-fledged monitor until a) there is actual contention
44  * or b) wait() is called on the Object.
45  *
46  * For Android, we have implemented a scheme similar to the one described in Bacon et al.'s
47  * "Thin locks: featherweight synchronization for Java" (ACM 1998).  Things are even easier for us,
48  * though, because we have a full 32 bits to work with.
49  *
50  * The two states of an Object's lock are referred to as "thin" and "fat".  A lock may transition
51  * from the "thin" state to the "fat" state and this transition is referred to as inflation. Once
52  * a lock has been inflated it remains in the "fat" state indefinitely.
53  *
54  * The lock value itself is stored in mirror::Object::monitor_ and the representation is described
55  * in the LockWord value type.
56  *
57  * Monitors provide:
58  *  - mutually exclusive access to resources
59  *  - a way for multiple threads to wait for notification
60  *
61  * In effect, they fill the role of both mutexes and condition variables.
62  *
63  * Only one thread can own the monitor at any time.  There may be several threads waiting on it
64  * (the wait call unlocks it).  One or more waiting threads may be getting interrupted or notified
65  * at any given time.
66  */
67 
68 bool (*Monitor::is_sensitive_thread_hook_)() = NULL;
69 uint32_t Monitor::lock_profiling_threshold_ = 0;
70 
IsSensitiveThread()71 bool Monitor::IsSensitiveThread() {
72   if (is_sensitive_thread_hook_ != NULL) {
73     return (*is_sensitive_thread_hook_)();
74   }
75   return false;
76 }
77 
Init(uint32_t lock_profiling_threshold,bool (* is_sensitive_thread_hook)())78 void Monitor::Init(uint32_t lock_profiling_threshold, bool (*is_sensitive_thread_hook)()) {
79   lock_profiling_threshold_ = lock_profiling_threshold;
80   is_sensitive_thread_hook_ = is_sensitive_thread_hook;
81 }
82 
Monitor(Thread * self,Thread * owner,mirror::Object * obj,int32_t hash_code)83 Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code)
84     : monitor_lock_("a monitor lock", kMonitorLock),
85       monitor_contenders_("monitor contenders", monitor_lock_),
86       num_waiters_(0),
87       owner_(owner),
88       lock_count_(0),
89       obj_(GcRoot<mirror::Object>(obj)),
90       wait_set_(NULL),
91       hash_code_(hash_code),
92       locking_method_(NULL),
93       locking_dex_pc_(0),
94       monitor_id_(MonitorPool::ComputeMonitorId(this, self)) {
95 #ifdef __LP64__
96   DCHECK(false) << "Should not be reached in 64b";
97   next_free_ = nullptr;
98 #endif
99   // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
100   // with the owner unlocking the thin-lock.
101   CHECK(owner == nullptr || owner == self || owner->IsSuspended());
102   // The identity hash code is set for the life time of the monitor.
103 }
104 
Monitor(Thread * self,Thread * owner,mirror::Object * obj,int32_t hash_code,MonitorId id)105 Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code,
106                  MonitorId id)
107     : monitor_lock_("a monitor lock", kMonitorLock),
108       monitor_contenders_("monitor contenders", monitor_lock_),
109       num_waiters_(0),
110       owner_(owner),
111       lock_count_(0),
112       obj_(GcRoot<mirror::Object>(obj)),
113       wait_set_(NULL),
114       hash_code_(hash_code),
115       locking_method_(NULL),
116       locking_dex_pc_(0),
117       monitor_id_(id) {
118 #ifdef __LP64__
119   next_free_ = nullptr;
120 #endif
121   // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
122   // with the owner unlocking the thin-lock.
123   CHECK(owner == nullptr || owner == self || owner->IsSuspended());
124   // The identity hash code is set for the life time of the monitor.
125 }
126 
GetHashCode()127 int32_t Monitor::GetHashCode() {
128   while (!HasHashCode()) {
129     if (hash_code_.CompareExchangeWeakRelaxed(0, mirror::Object::GenerateIdentityHashCode())) {
130       break;
131     }
132   }
133   DCHECK(HasHashCode());
134   return hash_code_.LoadRelaxed();
135 }
136 
Install(Thread * self)137 bool Monitor::Install(Thread* self) {
138   MutexLock mu(self, monitor_lock_);  // Uncontended mutex acquisition as monitor isn't yet public.
139   CHECK(owner_ == nullptr || owner_ == self || owner_->IsSuspended());
140   // Propagate the lock state.
141   LockWord lw(GetObject()->GetLockWord(false));
142   switch (lw.GetState()) {
143     case LockWord::kThinLocked: {
144       CHECK_EQ(owner_->GetThreadId(), lw.ThinLockOwner());
145       lock_count_ = lw.ThinLockCount();
146       break;
147     }
148     case LockWord::kHashCode: {
149       CHECK_EQ(hash_code_.LoadRelaxed(), static_cast<int32_t>(lw.GetHashCode()));
150       break;
151     }
152     case LockWord::kFatLocked: {
153       // The owner_ is suspended but another thread beat us to install a monitor.
154       return false;
155     }
156     case LockWord::kUnlocked: {
157       LOG(FATAL) << "Inflating unlocked lock word";
158       break;
159     }
160     default: {
161       LOG(FATAL) << "Invalid monitor state " << lw.GetState();
162       return false;
163     }
164   }
165   LockWord fat(this);
166   // Publish the updated lock word, which may race with other threads.
167   bool success = GetObject()->CasLockWordWeakSequentiallyConsistent(lw, fat);
168   // Lock profiling.
169   if (success && owner_ != nullptr && lock_profiling_threshold_ != 0) {
170     // Do not abort on dex pc errors. This can easily happen when we want to dump a stack trace on
171     // abort.
172     locking_method_ = owner_->GetCurrentMethod(&locking_dex_pc_, false);
173   }
174   return success;
175 }
176 
~Monitor()177 Monitor::~Monitor() {
178   // Deflated monitors have a null object.
179 }
180 
181 /*
182  * Links a thread into a monitor's wait set.  The monitor lock must be
183  * held by the caller of this routine.
184  */
AppendToWaitSet(Thread * thread)185 void Monitor::AppendToWaitSet(Thread* thread) {
186   DCHECK(owner_ == Thread::Current());
187   DCHECK(thread != NULL);
188   DCHECK(thread->GetWaitNext() == nullptr) << thread->GetWaitNext();
189   if (wait_set_ == NULL) {
190     wait_set_ = thread;
191     return;
192   }
193 
194   // push_back.
195   Thread* t = wait_set_;
196   while (t->GetWaitNext() != nullptr) {
197     t = t->GetWaitNext();
198   }
199   t->SetWaitNext(thread);
200 }
201 
202 /*
203  * Unlinks a thread from a monitor's wait set.  The monitor lock must
204  * be held by the caller of this routine.
205  */
RemoveFromWaitSet(Thread * thread)206 void Monitor::RemoveFromWaitSet(Thread *thread) {
207   DCHECK(owner_ == Thread::Current());
208   DCHECK(thread != NULL);
209   if (wait_set_ == NULL) {
210     return;
211   }
212   if (wait_set_ == thread) {
213     wait_set_ = thread->GetWaitNext();
214     thread->SetWaitNext(nullptr);
215     return;
216   }
217 
218   Thread* t = wait_set_;
219   while (t->GetWaitNext() != NULL) {
220     if (t->GetWaitNext() == thread) {
221       t->SetWaitNext(thread->GetWaitNext());
222       thread->SetWaitNext(nullptr);
223       return;
224     }
225     t = t->GetWaitNext();
226   }
227 }
228 
SetObject(mirror::Object * object)229 void Monitor::SetObject(mirror::Object* object) {
230   obj_ = GcRoot<mirror::Object>(object);
231 }
232 
Lock(Thread * self)233 void Monitor::Lock(Thread* self) {
234   MutexLock mu(self, monitor_lock_);
235   while (true) {
236     if (owner_ == nullptr) {  // Unowned.
237       owner_ = self;
238       CHECK_EQ(lock_count_, 0);
239       // When debugging, save the current monitor holder for future
240       // acquisition failures to use in sampled logging.
241       if (lock_profiling_threshold_ != 0) {
242         locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
243       }
244       return;
245     } else if (owner_ == self) {  // Recursive.
246       lock_count_++;
247       return;
248     }
249     // Contended.
250     const bool log_contention = (lock_profiling_threshold_ != 0);
251     uint64_t wait_start_ms = log_contention ? MilliTime() : 0;
252     mirror::ArtMethod* owners_method = locking_method_;
253     uint32_t owners_dex_pc = locking_dex_pc_;
254     // Do this before releasing the lock so that we don't get deflated.
255     size_t num_waiters = num_waiters_;
256     ++num_waiters_;
257     monitor_lock_.Unlock(self);  // Let go of locks in order.
258     self->SetMonitorEnterObject(GetObject());
259     {
260       ScopedThreadStateChange tsc(self, kBlocked);  // Change to blocked and give up mutator_lock_.
261       MutexLock mu2(self, monitor_lock_);  // Reacquire monitor_lock_ without mutator_lock_ for Wait.
262       if (owner_ != NULL) {  // Did the owner_ give the lock up?
263         monitor_contenders_.Wait(self);  // Still contended so wait.
264         // Woken from contention.
265         if (log_contention) {
266           uint64_t wait_ms = MilliTime() - wait_start_ms;
267           uint32_t sample_percent;
268           if (wait_ms >= lock_profiling_threshold_) {
269             sample_percent = 100;
270           } else {
271             sample_percent = 100 * wait_ms / lock_profiling_threshold_;
272           }
273           if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
274             const char* owners_filename;
275             uint32_t owners_line_number;
276             TranslateLocation(owners_method, owners_dex_pc, &owners_filename, &owners_line_number);
277             if (wait_ms > kLongWaitMs && owners_method != nullptr) {
278               LOG(WARNING) << "Long monitor contention event with owner method="
279                   << PrettyMethod(owners_method) << " from " << owners_filename << ":"
280                   << owners_line_number << " waiters=" << num_waiters << " for "
281                   << PrettyDuration(MsToNs(wait_ms));
282             }
283             LogContentionEvent(self, wait_ms, sample_percent, owners_filename, owners_line_number);
284           }
285         }
286       }
287     }
288     self->SetMonitorEnterObject(nullptr);
289     monitor_lock_.Lock(self);  // Reacquire locks in order.
290     --num_waiters_;
291   }
292 }
293 
294 static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
295                                               __attribute__((format(printf, 1, 2)));
296 
ThrowIllegalMonitorStateExceptionF(const char * fmt,...)297 static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
298     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
299   va_list args;
300   va_start(args, fmt);
301   Thread* self = Thread::Current();
302   ThrowLocation throw_location = self->GetCurrentLocationForThrow();
303   self->ThrowNewExceptionV(throw_location, "Ljava/lang/IllegalMonitorStateException;", fmt, args);
304   if (!Runtime::Current()->IsStarted() || VLOG_IS_ON(monitor)) {
305     std::ostringstream ss;
306     self->Dump(ss);
307     LOG(Runtime::Current()->IsStarted() ? INFO : ERROR)
308         << self->GetException(NULL)->Dump() << "\n" << ss.str();
309   }
310   va_end(args);
311 }
312 
ThreadToString(Thread * thread)313 static std::string ThreadToString(Thread* thread) {
314   if (thread == NULL) {
315     return "NULL";
316   }
317   std::ostringstream oss;
318   // TODO: alternatively, we could just return the thread's name.
319   oss << *thread;
320   return oss.str();
321 }
322 
FailedUnlock(mirror::Object * o,Thread * expected_owner,Thread * found_owner,Monitor * monitor)323 void Monitor::FailedUnlock(mirror::Object* o, Thread* expected_owner, Thread* found_owner,
324                            Monitor* monitor) {
325   Thread* current_owner = NULL;
326   std::string current_owner_string;
327   std::string expected_owner_string;
328   std::string found_owner_string;
329   {
330     // TODO: isn't this too late to prevent threads from disappearing?
331     // Acquire thread list lock so threads won't disappear from under us.
332     MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
333     // Re-read owner now that we hold lock.
334     current_owner = (monitor != NULL) ? monitor->GetOwner() : NULL;
335     // Get short descriptions of the threads involved.
336     current_owner_string = ThreadToString(current_owner);
337     expected_owner_string = ThreadToString(expected_owner);
338     found_owner_string = ThreadToString(found_owner);
339   }
340   if (current_owner == NULL) {
341     if (found_owner == NULL) {
342       ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
343                                          " on thread '%s'",
344                                          PrettyTypeOf(o).c_str(),
345                                          expected_owner_string.c_str());
346     } else {
347       // Race: the original read found an owner but now there is none
348       ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
349                                          " (where now the monitor appears unowned) on thread '%s'",
350                                          found_owner_string.c_str(),
351                                          PrettyTypeOf(o).c_str(),
352                                          expected_owner_string.c_str());
353     }
354   } else {
355     if (found_owner == NULL) {
356       // Race: originally there was no owner, there is now
357       ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
358                                          " (originally believed to be unowned) on thread '%s'",
359                                          current_owner_string.c_str(),
360                                          PrettyTypeOf(o).c_str(),
361                                          expected_owner_string.c_str());
362     } else {
363       if (found_owner != current_owner) {
364         // Race: originally found and current owner have changed
365         ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
366                                            " owned by '%s') on object of type '%s' on thread '%s'",
367                                            found_owner_string.c_str(),
368                                            current_owner_string.c_str(),
369                                            PrettyTypeOf(o).c_str(),
370                                            expected_owner_string.c_str());
371       } else {
372         ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
373                                            " on thread '%s",
374                                            current_owner_string.c_str(),
375                                            PrettyTypeOf(o).c_str(),
376                                            expected_owner_string.c_str());
377       }
378     }
379   }
380 }
381 
Unlock(Thread * self)382 bool Monitor::Unlock(Thread* self) {
383   DCHECK(self != NULL);
384   MutexLock mu(self, monitor_lock_);
385   Thread* owner = owner_;
386   if (owner == self) {
387     // We own the monitor, so nobody else can be in here.
388     if (lock_count_ == 0) {
389       owner_ = NULL;
390       locking_method_ = NULL;
391       locking_dex_pc_ = 0;
392       // Wake a contender.
393       monitor_contenders_.Signal(self);
394     } else {
395       --lock_count_;
396     }
397   } else {
398     // We don't own this, so we're not allowed to unlock it.
399     // The JNI spec says that we should throw IllegalMonitorStateException
400     // in this case.
401     FailedUnlock(GetObject(), self, owner, this);
402     return false;
403   }
404   return true;
405 }
406 
407 /*
408  * Wait on a monitor until timeout, interrupt, or notification.  Used for
409  * Object.wait() and (somewhat indirectly) Thread.sleep() and Thread.join().
410  *
411  * If another thread calls Thread.interrupt(), we throw InterruptedException
412  * and return immediately if one of the following are true:
413  *  - blocked in wait(), wait(long), or wait(long, int) methods of Object
414  *  - blocked in join(), join(long), or join(long, int) methods of Thread
415  *  - blocked in sleep(long), or sleep(long, int) methods of Thread
416  * Otherwise, we set the "interrupted" flag.
417  *
418  * Checks to make sure that "ns" is in the range 0-999999
419  * (i.e. fractions of a millisecond) and throws the appropriate
420  * exception if it isn't.
421  *
422  * The spec allows "spurious wakeups", and recommends that all code using
423  * Object.wait() do so in a loop.  This appears to derive from concerns
424  * about pthread_cond_wait() on multiprocessor systems.  Some commentary
425  * on the web casts doubt on whether these can/should occur.
426  *
427  * Since we're allowed to wake up "early", we clamp extremely long durations
428  * to return at the end of the 32-bit time epoch.
429  */
Wait(Thread * self,int64_t ms,int32_t ns,bool interruptShouldThrow,ThreadState why)430 void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
431                    bool interruptShouldThrow, ThreadState why) {
432   DCHECK(self != NULL);
433   DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
434 
435   monitor_lock_.Lock(self);
436 
437   // Make sure that we hold the lock.
438   if (owner_ != self) {
439     monitor_lock_.Unlock(self);
440     ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
441     return;
442   }
443 
444   // We need to turn a zero-length timed wait into a regular wait because
445   // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
446   if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
447     why = kWaiting;
448   }
449 
450   // Enforce the timeout range.
451   if (ms < 0 || ns < 0 || ns > 999999) {
452     monitor_lock_.Unlock(self);
453     ThrowLocation throw_location = self->GetCurrentLocationForThrow();
454     self->ThrowNewExceptionF(throw_location, "Ljava/lang/IllegalArgumentException;",
455                              "timeout arguments out of range: ms=%" PRId64 " ns=%d", ms, ns);
456     return;
457   }
458 
459   /*
460    * Add ourselves to the set of threads waiting on this monitor, and
461    * release our hold.  We need to let it go even if we're a few levels
462    * deep in a recursive lock, and we need to restore that later.
463    *
464    * We append to the wait set ahead of clearing the count and owner
465    * fields so the subroutine can check that the calling thread owns
466    * the monitor.  Aside from that, the order of member updates is
467    * not order sensitive as we hold the pthread mutex.
468    */
469   AppendToWaitSet(self);
470   ++num_waiters_;
471   int prev_lock_count = lock_count_;
472   lock_count_ = 0;
473   owner_ = NULL;
474   mirror::ArtMethod* saved_method = locking_method_;
475   locking_method_ = NULL;
476   uintptr_t saved_dex_pc = locking_dex_pc_;
477   locking_dex_pc_ = 0;
478 
479   /*
480    * Update thread state. If the GC wakes up, it'll ignore us, knowing
481    * that we won't touch any references in this state, and we'll check
482    * our suspend mode before we transition out.
483    */
484   self->TransitionFromRunnableToSuspended(why);
485 
486   bool was_interrupted = false;
487   {
488     // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
489     MutexLock mu(self, *self->GetWaitMutex());
490 
491     // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
492     // non-NULL a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
493     // up.
494     DCHECK(self->GetWaitMonitor() == nullptr);
495     self->SetWaitMonitor(this);
496 
497     // Release the monitor lock.
498     monitor_contenders_.Signal(self);
499     monitor_lock_.Unlock(self);
500 
501     // Handle the case where the thread was interrupted before we called wait().
502     if (self->IsInterruptedLocked()) {
503       was_interrupted = true;
504     } else {
505       // Wait for a notification or a timeout to occur.
506       if (why == kWaiting) {
507         self->GetWaitConditionVariable()->Wait(self);
508       } else {
509         DCHECK(why == kTimedWaiting || why == kSleeping) << why;
510         self->GetWaitConditionVariable()->TimedWait(self, ms, ns);
511       }
512       if (self->IsInterruptedLocked()) {
513         was_interrupted = true;
514       }
515       self->SetInterruptedLocked(false);
516     }
517   }
518 
519   // Set self->status back to kRunnable, and self-suspend if needed.
520   self->TransitionFromSuspendedToRunnable();
521 
522   {
523     // We reset the thread's wait_monitor_ field after transitioning back to runnable so
524     // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
525     // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
526     // are waiting on "null".)
527     MutexLock mu(self, *self->GetWaitMutex());
528     DCHECK(self->GetWaitMonitor() != nullptr);
529     self->SetWaitMonitor(nullptr);
530   }
531 
532   // Re-acquire the monitor and lock.
533   Lock(self);
534   monitor_lock_.Lock(self);
535   self->GetWaitMutex()->AssertNotHeld(self);
536 
537   /*
538    * We remove our thread from wait set after restoring the count
539    * and owner fields so the subroutine can check that the calling
540    * thread owns the monitor. Aside from that, the order of member
541    * updates is not order sensitive as we hold the pthread mutex.
542    */
543   owner_ = self;
544   lock_count_ = prev_lock_count;
545   locking_method_ = saved_method;
546   locking_dex_pc_ = saved_dex_pc;
547   --num_waiters_;
548   RemoveFromWaitSet(self);
549 
550   monitor_lock_.Unlock(self);
551 
552   if (was_interrupted) {
553     /*
554      * We were interrupted while waiting, or somebody interrupted an
555      * un-interruptible thread earlier and we're bailing out immediately.
556      *
557      * The doc sayeth: "The interrupted status of the current thread is
558      * cleared when this exception is thrown."
559      */
560     {
561       MutexLock mu(self, *self->GetWaitMutex());
562       self->SetInterruptedLocked(false);
563     }
564     if (interruptShouldThrow) {
565       ThrowLocation throw_location = self->GetCurrentLocationForThrow();
566       self->ThrowNewException(throw_location, "Ljava/lang/InterruptedException;", NULL);
567     }
568   }
569 }
570 
Notify(Thread * self)571 void Monitor::Notify(Thread* self) {
572   DCHECK(self != NULL);
573   MutexLock mu(self, monitor_lock_);
574   // Make sure that we hold the lock.
575   if (owner_ != self) {
576     ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
577     return;
578   }
579   // Signal the first waiting thread in the wait set.
580   while (wait_set_ != NULL) {
581     Thread* thread = wait_set_;
582     wait_set_ = thread->GetWaitNext();
583     thread->SetWaitNext(nullptr);
584 
585     // Check to see if the thread is still waiting.
586     MutexLock mu(self, *thread->GetWaitMutex());
587     if (thread->GetWaitMonitor() != nullptr) {
588       thread->GetWaitConditionVariable()->Signal(self);
589       return;
590     }
591   }
592 }
593 
NotifyAll(Thread * self)594 void Monitor::NotifyAll(Thread* self) {
595   DCHECK(self != NULL);
596   MutexLock mu(self, monitor_lock_);
597   // Make sure that we hold the lock.
598   if (owner_ != self) {
599     ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
600     return;
601   }
602   // Signal all threads in the wait set.
603   while (wait_set_ != NULL) {
604     Thread* thread = wait_set_;
605     wait_set_ = thread->GetWaitNext();
606     thread->SetWaitNext(nullptr);
607     thread->Notify();
608   }
609 }
610 
Deflate(Thread * self,mirror::Object * obj)611 bool Monitor::Deflate(Thread* self, mirror::Object* obj) {
612   DCHECK(obj != nullptr);
613   // Don't need volatile since we only deflate with mutators suspended.
614   LockWord lw(obj->GetLockWord(false));
615   // If the lock isn't an inflated monitor, then we don't need to deflate anything.
616   if (lw.GetState() == LockWord::kFatLocked) {
617     Monitor* monitor = lw.FatLockMonitor();
618     DCHECK(monitor != nullptr);
619     MutexLock mu(self, monitor->monitor_lock_);
620     // Can't deflate if we have anybody waiting on the CV.
621     if (monitor->num_waiters_ > 0) {
622       return false;
623     }
624     Thread* owner = monitor->owner_;
625     if (owner != nullptr) {
626       // Can't deflate if we are locked and have a hash code.
627       if (monitor->HasHashCode()) {
628         return false;
629       }
630       // Can't deflate if our lock count is too high.
631       if (monitor->lock_count_ > LockWord::kThinLockMaxCount) {
632         return false;
633       }
634       // Deflate to a thin lock.
635       obj->SetLockWord(LockWord::FromThinLockId(owner->GetThreadId(), monitor->lock_count_), false);
636       VLOG(monitor) << "Deflated " << obj << " to thin lock " << owner->GetTid() << " / "
637           << monitor->lock_count_;
638     } else if (monitor->HasHashCode()) {
639       obj->SetLockWord(LockWord::FromHashCode(monitor->GetHashCode()), false);
640       VLOG(monitor) << "Deflated " << obj << " to hash monitor " << monitor->GetHashCode();
641     } else {
642       // No lock and no hash, just put an empty lock word inside the object.
643       obj->SetLockWord(LockWord(), false);
644       VLOG(monitor) << "Deflated" << obj << " to empty lock word";
645     }
646     // The monitor is deflated, mark the object as nullptr so that we know to delete it during the
647     // next GC.
648     monitor->obj_ = GcRoot<mirror::Object>(nullptr);
649   }
650   return true;
651 }
652 
Inflate(Thread * self,Thread * owner,mirror::Object * obj,int32_t hash_code)653 void Monitor::Inflate(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code) {
654   DCHECK(self != nullptr);
655   DCHECK(obj != nullptr);
656   // Allocate and acquire a new monitor.
657   Monitor* m = MonitorPool::CreateMonitor(self, owner, obj, hash_code);
658   DCHECK(m != nullptr);
659   if (m->Install(self)) {
660     if (owner != nullptr) {
661       VLOG(monitor) << "monitor: thread" << owner->GetThreadId()
662           << " created monitor " << m << " for object " << obj;
663     } else {
664       VLOG(monitor) << "monitor: Inflate with hashcode " << hash_code
665           << " created monitor " << m << " for object " << obj;
666     }
667     Runtime::Current()->GetMonitorList()->Add(m);
668     CHECK_EQ(obj->GetLockWord(true).GetState(), LockWord::kFatLocked);
669   } else {
670     MonitorPool::ReleaseMonitor(self, m);
671   }
672 }
673 
InflateThinLocked(Thread * self,Handle<mirror::Object> obj,LockWord lock_word,uint32_t hash_code)674 void Monitor::InflateThinLocked(Thread* self, Handle<mirror::Object> obj, LockWord lock_word,
675                                 uint32_t hash_code) {
676   DCHECK_EQ(lock_word.GetState(), LockWord::kThinLocked);
677   uint32_t owner_thread_id = lock_word.ThinLockOwner();
678   if (owner_thread_id == self->GetThreadId()) {
679     // We own the monitor, we can easily inflate it.
680     Inflate(self, self, obj.Get(), hash_code);
681   } else {
682     ThreadList* thread_list = Runtime::Current()->GetThreadList();
683     // Suspend the owner, inflate. First change to blocked and give up mutator_lock_.
684     self->SetMonitorEnterObject(obj.Get());
685     bool timed_out;
686     Thread* owner;
687     {
688       ScopedThreadStateChange tsc(self, kBlocked);
689       // Take suspend thread lock to avoid races with threads trying to suspend this one.
690       MutexLock mu(self, *Locks::thread_list_suspend_thread_lock_);
691       owner = thread_list->SuspendThreadByThreadId(owner_thread_id, false, &timed_out);
692     }
693     if (owner != nullptr) {
694       // We succeeded in suspending the thread, check the lock's status didn't change.
695       lock_word = obj->GetLockWord(true);
696       if (lock_word.GetState() == LockWord::kThinLocked &&
697           lock_word.ThinLockOwner() == owner_thread_id) {
698         // Go ahead and inflate the lock.
699         Inflate(self, owner, obj.Get(), hash_code);
700       }
701       thread_list->Resume(owner, false);
702     }
703     self->SetMonitorEnterObject(nullptr);
704   }
705 }
706 
707 // Fool annotalysis into thinking that the lock on obj is acquired.
FakeLock(mirror::Object * obj)708 static mirror::Object* FakeLock(mirror::Object* obj)
709     EXCLUSIVE_LOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
710   return obj;
711 }
712 
713 // Fool annotalysis into thinking that the lock on obj is release.
FakeUnlock(mirror::Object * obj)714 static mirror::Object* FakeUnlock(mirror::Object* obj)
715     UNLOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
716   return obj;
717 }
718 
MonitorEnter(Thread * self,mirror::Object * obj)719 mirror::Object* Monitor::MonitorEnter(Thread* self, mirror::Object* obj) {
720   DCHECK(self != NULL);
721   DCHECK(obj != NULL);
722   obj = FakeLock(obj);
723   uint32_t thread_id = self->GetThreadId();
724   size_t contention_count = 0;
725   StackHandleScope<1> hs(self);
726   Handle<mirror::Object> h_obj(hs.NewHandle(obj));
727   while (true) {
728     LockWord lock_word = h_obj->GetLockWord(true);
729     switch (lock_word.GetState()) {
730       case LockWord::kUnlocked: {
731         LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0));
732         if (h_obj->CasLockWordWeakSequentiallyConsistent(lock_word, thin_locked)) {
733           // CasLockWord enforces more than the acquire ordering we need here.
734           return h_obj.Get();  // Success!
735         }
736         continue;  // Go again.
737       }
738       case LockWord::kThinLocked: {
739         uint32_t owner_thread_id = lock_word.ThinLockOwner();
740         if (owner_thread_id == thread_id) {
741           // We own the lock, increase the recursion count.
742           uint32_t new_count = lock_word.ThinLockCount() + 1;
743           if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
744             LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count));
745             h_obj->SetLockWord(thin_locked, true);
746             return h_obj.Get();  // Success!
747           } else {
748             // We'd overflow the recursion count, so inflate the monitor.
749             InflateThinLocked(self, h_obj, lock_word, 0);
750           }
751         } else {
752           // Contention.
753           contention_count++;
754           Runtime* runtime = Runtime::Current();
755           if (contention_count <= runtime->GetMaxSpinsBeforeThinkLockInflation()) {
756             // TODO: Consider switching the thread state to kBlocked when we are yielding.
757             // Use sched_yield instead of NanoSleep since NanoSleep can wait much longer than the
758             // parameter you pass in. This can cause thread suspension to take excessively long
759             // and make long pauses. See b/16307460.
760             sched_yield();
761           } else {
762             contention_count = 0;
763             InflateThinLocked(self, h_obj, lock_word, 0);
764           }
765         }
766         continue;  // Start from the beginning.
767       }
768       case LockWord::kFatLocked: {
769         Monitor* mon = lock_word.FatLockMonitor();
770         mon->Lock(self);
771         return h_obj.Get();  // Success!
772       }
773       case LockWord::kHashCode:
774         // Inflate with the existing hashcode.
775         Inflate(self, nullptr, h_obj.Get(), lock_word.GetHashCode());
776         continue;  // Start from the beginning.
777       default: {
778         LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
779         return h_obj.Get();
780       }
781     }
782   }
783 }
784 
MonitorExit(Thread * self,mirror::Object * obj)785 bool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
786   DCHECK(self != NULL);
787   DCHECK(obj != NULL);
788   obj = FakeUnlock(obj);
789   LockWord lock_word = obj->GetLockWord(true);
790   StackHandleScope<1> hs(self);
791   Handle<mirror::Object> h_obj(hs.NewHandle(obj));
792   switch (lock_word.GetState()) {
793     case LockWord::kHashCode:
794       // Fall-through.
795     case LockWord::kUnlocked:
796       FailedUnlock(h_obj.Get(), self, nullptr, nullptr);
797       return false;  // Failure.
798     case LockWord::kThinLocked: {
799       uint32_t thread_id = self->GetThreadId();
800       uint32_t owner_thread_id = lock_word.ThinLockOwner();
801       if (owner_thread_id != thread_id) {
802         // TODO: there's a race here with the owner dying while we unlock.
803         Thread* owner =
804             Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
805         FailedUnlock(h_obj.Get(), self, owner, nullptr);
806         return false;  // Failure.
807       } else {
808         // We own the lock, decrease the recursion count.
809         if (lock_word.ThinLockCount() != 0) {
810           uint32_t new_count = lock_word.ThinLockCount() - 1;
811           LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count));
812           h_obj->SetLockWord(thin_locked, true);
813         } else {
814           h_obj->SetLockWord(LockWord(), true);
815         }
816         return true;  // Success!
817       }
818     }
819     case LockWord::kFatLocked: {
820       Monitor* mon = lock_word.FatLockMonitor();
821       return mon->Unlock(self);
822     }
823     default: {
824       LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
825       return false;
826     }
827   }
828 }
829 
830 /*
831  * Object.wait().  Also called for class init.
832  */
Wait(Thread * self,mirror::Object * obj,int64_t ms,int32_t ns,bool interruptShouldThrow,ThreadState why)833 void Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
834                    bool interruptShouldThrow, ThreadState why) {
835   DCHECK(self != nullptr);
836   DCHECK(obj != nullptr);
837   LockWord lock_word = obj->GetLockWord(true);
838   while (lock_word.GetState() != LockWord::kFatLocked) {
839     switch (lock_word.GetState()) {
840       case LockWord::kHashCode:
841         // Fall-through.
842       case LockWord::kUnlocked:
843         ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
844         return;  // Failure.
845       case LockWord::kThinLocked: {
846         uint32_t thread_id = self->GetThreadId();
847         uint32_t owner_thread_id = lock_word.ThinLockOwner();
848         if (owner_thread_id != thread_id) {
849           ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
850           return;  // Failure.
851         } else {
852           // We own the lock, inflate to enqueue ourself on the Monitor. May fail spuriously so
853           // re-load.
854           Inflate(self, self, obj, 0);
855           lock_word = obj->GetLockWord(true);
856         }
857         break;
858       }
859       case LockWord::kFatLocked:  // Unreachable given the loop condition above. Fall-through.
860       default: {
861         LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
862         return;
863       }
864     }
865   }
866   Monitor* mon = lock_word.FatLockMonitor();
867   mon->Wait(self, ms, ns, interruptShouldThrow, why);
868 }
869 
DoNotify(Thread * self,mirror::Object * obj,bool notify_all)870 void Monitor::DoNotify(Thread* self, mirror::Object* obj, bool notify_all) {
871   DCHECK(self != nullptr);
872   DCHECK(obj != nullptr);
873   LockWord lock_word = obj->GetLockWord(true);
874   switch (lock_word.GetState()) {
875     case LockWord::kHashCode:
876       // Fall-through.
877     case LockWord::kUnlocked:
878       ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
879       return;  // Failure.
880     case LockWord::kThinLocked: {
881       uint32_t thread_id = self->GetThreadId();
882       uint32_t owner_thread_id = lock_word.ThinLockOwner();
883       if (owner_thread_id != thread_id) {
884         ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
885         return;  // Failure.
886       } else {
887         // We own the lock but there's no Monitor and therefore no waiters.
888         return;  // Success.
889       }
890     }
891     case LockWord::kFatLocked: {
892       Monitor* mon = lock_word.FatLockMonitor();
893       if (notify_all) {
894         mon->NotifyAll(self);
895       } else {
896         mon->Notify(self);
897       }
898       return;  // Success.
899     }
900     default: {
901       LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
902       return;
903     }
904   }
905 }
906 
GetLockOwnerThreadId(mirror::Object * obj)907 uint32_t Monitor::GetLockOwnerThreadId(mirror::Object* obj) {
908   DCHECK(obj != nullptr);
909   LockWord lock_word = obj->GetLockWord(true);
910   switch (lock_word.GetState()) {
911     case LockWord::kHashCode:
912       // Fall-through.
913     case LockWord::kUnlocked:
914       return ThreadList::kInvalidThreadId;
915     case LockWord::kThinLocked:
916       return lock_word.ThinLockOwner();
917     case LockWord::kFatLocked: {
918       Monitor* mon = lock_word.FatLockMonitor();
919       return mon->GetOwnerThreadId();
920     }
921     default: {
922       LOG(FATAL) << "Unreachable";
923       return ThreadList::kInvalidThreadId;
924     }
925   }
926 }
927 
DescribeWait(std::ostream & os,const Thread * thread)928 void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
929   // Determine the wait message and object we're waiting or blocked upon.
930   mirror::Object* pretty_object = nullptr;
931   const char* wait_message = nullptr;
932   uint32_t lock_owner = ThreadList::kInvalidThreadId;
933   ThreadState state = thread->GetState();
934   if (state == kWaiting || state == kTimedWaiting || state == kSleeping) {
935     wait_message = (state == kSleeping) ? "  - sleeping on " : "  - waiting on ";
936     Thread* self = Thread::Current();
937     MutexLock mu(self, *thread->GetWaitMutex());
938     Monitor* monitor = thread->GetWaitMonitor();
939     if (monitor != nullptr) {
940       pretty_object = monitor->GetObject();
941     }
942   } else if (state == kBlocked) {
943     wait_message = "  - waiting to lock ";
944     pretty_object = thread->GetMonitorEnterObject();
945     if (pretty_object != nullptr) {
946       lock_owner = pretty_object->GetLockOwnerThreadId();
947     }
948   }
949 
950   if (wait_message != nullptr) {
951     if (pretty_object == nullptr) {
952       os << wait_message << "an unknown object";
953     } else {
954       if ((pretty_object->GetLockWord(true).GetState() == LockWord::kThinLocked) &&
955           Locks::mutator_lock_->IsExclusiveHeld(Thread::Current())) {
956         // Getting the identity hashcode here would result in lock inflation and suspension of the
957         // current thread, which isn't safe if this is the only runnable thread.
958         os << wait_message << StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)",
959                                            reinterpret_cast<intptr_t>(pretty_object),
960                                            PrettyTypeOf(pretty_object).c_str());
961       } else {
962         // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
963         os << wait_message << StringPrintf("<0x%08x> (a %s)", pretty_object->IdentityHashCode(),
964                                            PrettyTypeOf(pretty_object).c_str());
965       }
966     }
967     // - waiting to lock <0x613f83d8> (a java.lang.Object) held by thread 5
968     if (lock_owner != ThreadList::kInvalidThreadId) {
969       os << " held by thread " << lock_owner;
970     }
971     os << "\n";
972   }
973 }
974 
GetContendedMonitor(Thread * thread)975 mirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
976   // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
977   // definition of contended that includes a monitor a thread is trying to enter...
978   mirror::Object* result = thread->GetMonitorEnterObject();
979   if (result == NULL) {
980     // ...but also a monitor that the thread is waiting on.
981     MutexLock mu(Thread::Current(), *thread->GetWaitMutex());
982     Monitor* monitor = thread->GetWaitMonitor();
983     if (monitor != NULL) {
984       result = monitor->GetObject();
985     }
986   }
987   return result;
988 }
989 
VisitLocks(StackVisitor * stack_visitor,void (* callback)(mirror::Object *,void *),void * callback_context,bool abort_on_failure)990 void Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
991                          void* callback_context, bool abort_on_failure) {
992   mirror::ArtMethod* m = stack_visitor->GetMethod();
993   CHECK(m != NULL);
994 
995   // Native methods are an easy special case.
996   // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
997   if (m->IsNative()) {
998     if (m->IsSynchronized()) {
999       mirror::Object* jni_this = stack_visitor->GetCurrentHandleScope()->GetReference(0);
1000       callback(jni_this, callback_context);
1001     }
1002     return;
1003   }
1004 
1005   // Proxy methods should not be synchronized.
1006   if (m->IsProxyMethod()) {
1007     CHECK(!m->IsSynchronized());
1008     return;
1009   }
1010 
1011   // Is there any reason to believe there's any synchronization in this method?
1012   const DexFile::CodeItem* code_item = m->GetCodeItem();
1013   CHECK(code_item != NULL) << PrettyMethod(m);
1014   if (code_item->tries_size_ == 0) {
1015     return;  // No "tries" implies no synchronization, so no held locks to report.
1016   }
1017 
1018   // Get the dex pc. If abort_on_failure is false, GetDexPc will not abort in the case it cannot
1019   // find the dex pc, and instead return kDexNoIndex. Then bail out, as it indicates we have an
1020   // inconsistent stack anyways.
1021   uint32_t dex_pc = stack_visitor->GetDexPc(abort_on_failure);
1022   if (!abort_on_failure && dex_pc == DexFile::kDexNoIndex) {
1023     LOG(ERROR) << "Could not find dex_pc for " << PrettyMethod(m);
1024     return;
1025   }
1026 
1027   // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
1028   // the locks held in this stack frame.
1029   std::vector<uint32_t> monitor_enter_dex_pcs;
1030   verifier::MethodVerifier::FindLocksAtDexPc(m, dex_pc, &monitor_enter_dex_pcs);
1031   if (monitor_enter_dex_pcs.empty()) {
1032     return;
1033   }
1034 
1035   for (size_t i = 0; i < monitor_enter_dex_pcs.size(); ++i) {
1036     // The verifier works in terms of the dex pcs of the monitor-enter instructions.
1037     // We want the registers used by those instructions (so we can read the values out of them).
1038     uint32_t dex_pc = monitor_enter_dex_pcs[i];
1039     uint16_t monitor_enter_instruction = code_item->insns_[dex_pc];
1040 
1041     // Quick sanity check.
1042     if ((monitor_enter_instruction & 0xff) != Instruction::MONITOR_ENTER) {
1043       LOG(FATAL) << "expected monitor-enter @" << dex_pc << "; was "
1044                  << reinterpret_cast<void*>(monitor_enter_instruction);
1045     }
1046 
1047     uint16_t monitor_register = ((monitor_enter_instruction >> 8) & 0xff);
1048     mirror::Object* o = reinterpret_cast<mirror::Object*>(stack_visitor->GetVReg(m, monitor_register,
1049                                                                                  kReferenceVReg));
1050     callback(o, callback_context);
1051   }
1052 }
1053 
IsValidLockWord(LockWord lock_word)1054 bool Monitor::IsValidLockWord(LockWord lock_word) {
1055   switch (lock_word.GetState()) {
1056     case LockWord::kUnlocked:
1057       // Nothing to check.
1058       return true;
1059     case LockWord::kThinLocked:
1060       // Basic sanity check of owner.
1061       return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
1062     case LockWord::kFatLocked: {
1063       // Check the  monitor appears in the monitor list.
1064       Monitor* mon = lock_word.FatLockMonitor();
1065       MonitorList* list = Runtime::Current()->GetMonitorList();
1066       MutexLock mu(Thread::Current(), list->monitor_list_lock_);
1067       for (Monitor* list_mon : list->list_) {
1068         if (mon == list_mon) {
1069           return true;  // Found our monitor.
1070         }
1071       }
1072       return false;  // Fail - unowned monitor in an object.
1073     }
1074     case LockWord::kHashCode:
1075       return true;
1076     default:
1077       LOG(FATAL) << "Unreachable";
1078       return false;
1079   }
1080 }
1081 
IsLocked()1082 bool Monitor::IsLocked() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1083   MutexLock mu(Thread::Current(), monitor_lock_);
1084   return owner_ != nullptr;
1085 }
1086 
TranslateLocation(mirror::ArtMethod * method,uint32_t dex_pc,const char ** source_file,uint32_t * line_number) const1087 void Monitor::TranslateLocation(mirror::ArtMethod* method, uint32_t dex_pc,
1088                                 const char** source_file, uint32_t* line_number) const {
1089   // If method is null, location is unknown
1090   if (method == NULL) {
1091     *source_file = "";
1092     *line_number = 0;
1093     return;
1094   }
1095   *source_file = method->GetDeclaringClassSourceFile();
1096   if (*source_file == NULL) {
1097     *source_file = "";
1098   }
1099   *line_number = method->GetLineNumFromDexPC(dex_pc);
1100 }
1101 
GetOwnerThreadId()1102 uint32_t Monitor::GetOwnerThreadId() {
1103   MutexLock mu(Thread::Current(), monitor_lock_);
1104   Thread* owner = owner_;
1105   if (owner != NULL) {
1106     return owner->GetThreadId();
1107   } else {
1108     return ThreadList::kInvalidThreadId;
1109   }
1110 }
1111 
MonitorList()1112 MonitorList::MonitorList()
1113     : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock", kMonitorListLock),
1114       monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
1115 }
1116 
~MonitorList()1117 MonitorList::~MonitorList() {
1118   Thread* self = Thread::Current();
1119   MutexLock mu(self, monitor_list_lock_);
1120   // Release all monitors to the pool.
1121   // TODO: Is it an invariant that *all* open monitors are in the list? Then we could
1122   // clear faster in the pool.
1123   MonitorPool::ReleaseMonitors(self, &list_);
1124 }
1125 
DisallowNewMonitors()1126 void MonitorList::DisallowNewMonitors() {
1127   MutexLock mu(Thread::Current(), monitor_list_lock_);
1128   allow_new_monitors_ = false;
1129 }
1130 
AllowNewMonitors()1131 void MonitorList::AllowNewMonitors() {
1132   Thread* self = Thread::Current();
1133   MutexLock mu(self, monitor_list_lock_);
1134   allow_new_monitors_ = true;
1135   monitor_add_condition_.Broadcast(self);
1136 }
1137 
Add(Monitor * m)1138 void MonitorList::Add(Monitor* m) {
1139   Thread* self = Thread::Current();
1140   MutexLock mu(self, monitor_list_lock_);
1141   while (UNLIKELY(!allow_new_monitors_)) {
1142     monitor_add_condition_.WaitHoldingLocks(self);
1143   }
1144   list_.push_front(m);
1145 }
1146 
SweepMonitorList(IsMarkedCallback * callback,void * arg)1147 void MonitorList::SweepMonitorList(IsMarkedCallback* callback, void* arg) {
1148   Thread* self = Thread::Current();
1149   MutexLock mu(self, monitor_list_lock_);
1150   for (auto it = list_.begin(); it != list_.end(); ) {
1151     Monitor* m = *it;
1152     // Disable the read barrier in GetObject() as this is called by GC.
1153     mirror::Object* obj = m->GetObject<kWithoutReadBarrier>();
1154     // The object of a monitor can be null if we have deflated it.
1155     mirror::Object* new_obj = obj != nullptr ? callback(obj, arg) : nullptr;
1156     if (new_obj == nullptr) {
1157       VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
1158                     << obj;
1159       MonitorPool::ReleaseMonitor(self, m);
1160       it = list_.erase(it);
1161     } else {
1162       m->SetObject(new_obj);
1163       ++it;
1164     }
1165   }
1166 }
1167 
1168 struct MonitorDeflateArgs {
MonitorDeflateArgsart::MonitorDeflateArgs1169   MonitorDeflateArgs() : self(Thread::Current()), deflate_count(0) {}
1170   Thread* const self;
1171   size_t deflate_count;
1172 };
1173 
MonitorDeflateCallback(mirror::Object * object,void * arg)1174 static mirror::Object* MonitorDeflateCallback(mirror::Object* object, void* arg)
1175     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1176   MonitorDeflateArgs* args = reinterpret_cast<MonitorDeflateArgs*>(arg);
1177   if (Monitor::Deflate(args->self, object)) {
1178     DCHECK_NE(object->GetLockWord(true).GetState(), LockWord::kFatLocked);
1179     ++args->deflate_count;
1180     // If we deflated, return nullptr so that the monitor gets removed from the array.
1181     return nullptr;
1182   }
1183   return object;  // Monitor was not deflated.
1184 }
1185 
DeflateMonitors()1186 size_t MonitorList::DeflateMonitors() {
1187   MonitorDeflateArgs args;
1188   Locks::mutator_lock_->AssertExclusiveHeld(args.self);
1189   SweepMonitorList(MonitorDeflateCallback, &args);
1190   return args.deflate_count;
1191 }
1192 
MonitorInfo(mirror::Object * obj)1193 MonitorInfo::MonitorInfo(mirror::Object* obj) : owner_(NULL), entry_count_(0) {
1194   DCHECK(obj != nullptr);
1195   LockWord lock_word = obj->GetLockWord(true);
1196   switch (lock_word.GetState()) {
1197     case LockWord::kUnlocked:
1198       // Fall-through.
1199     case LockWord::kForwardingAddress:
1200       // Fall-through.
1201     case LockWord::kHashCode:
1202       break;
1203     case LockWord::kThinLocked:
1204       owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
1205       entry_count_ = 1 + lock_word.ThinLockCount();
1206       // Thin locks have no waiters.
1207       break;
1208     case LockWord::kFatLocked: {
1209       Monitor* mon = lock_word.FatLockMonitor();
1210       owner_ = mon->owner_;
1211       entry_count_ = 1 + mon->lock_count_;
1212       for (Thread* waiter = mon->wait_set_; waiter != NULL; waiter = waiter->GetWaitNext()) {
1213         waiters_.push_back(waiter);
1214       }
1215       break;
1216     }
1217   }
1218 }
1219 
1220 }  // namespace art
1221