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