monitor.cc revision eb8167a4f4d27fce0530f6724ab8032610cd146b
15f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes/*
25f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * Copyright (C) 2008 The Android Open Source Project
35f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes *
45f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * Licensed under the Apache License, Version 2.0 (the "License");
55f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * you may not use this file except in compliance with the License.
65f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * You may obtain a copy of the License at
75f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes *
85f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes *      http://www.apache.org/licenses/LICENSE-2.0
95f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes *
105f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * Unless required by applicable law or agreed to in writing, software
115f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * distributed under the License is distributed on an "AS IS" BASIS,
125f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
135f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * See the License for the specific language governing permissions and
145f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * limitations under the License.
155f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes */
165f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
1754e7df1896a4066cbb9fe6f72249829f0b8c49c6Elliott Hughes#include "monitor.h"
185f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
1908fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes#include <vector>
2008fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes
2176b6167407c2b6f5d40ad895b2793a6b037f54b2Elliott Hughes#include "base/mutex.h"
221aa246dec5abe212f699de1413a0c4a191ca364aElliott Hughes#include "base/stl_util.h"
2333dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao#include "class_linker.h"
244f6ad8ab428038129b2d0d6c40b7fd625cca15e1Ian Rogers#include "dex_file-inl.h"
2508fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes#include "dex_instruction.h"
26d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers#include "lock_word-inl.h"
27ea46f950e7a51585db293cd7f047de190a482414Brian Carlstrom#include "mirror/art_method-inl.h"
284f6ad8ab428038129b2d0d6c40b7fd625cca15e1Ian Rogers#include "mirror/class-inl.h"
2905f3057d6a4d23d712092ccd36a531590bff323bIan Rogers#include "mirror/object-inl.h"
302dd0e2cea360bc9206eb88ecc40d259e796c239dIan Rogers#include "mirror/object_array-inl.h"
316d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers#include "object_utils.h"
3200f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers#include "scoped_thread_state_change.h"
335f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes#include "thread.h"
348e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes#include "thread_list.h"
3508fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes#include "verifier/method_verifier.h"
36044288fb8f69e154862763a6b3bfea2bac1b397eElliott Hughes#include "well_known_classes.h"
375f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
385f79133a435ebcb20000370d56046fe01201dd80Elliott Hughesnamespace art {
395f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
405f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes/*
41d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers * Every Object has a monitor associated with it, but not every Object is actually locked.  Even
42d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers * the ones that are locked do not need a full-fledged monitor until a) there is actual contention
43d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers * or b) wait() is called on the Object.
445f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes *
45d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers * For Android, we have implemented a scheme similar to the one described in Bacon et al.'s
46d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers * "Thin locks: featherweight synchronization for Java" (ACM 1998).  Things are even easier for us,
47d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers * though, because we have a full 32 bits to work with.
485f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes *
49d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers * The two states of an Object's lock are referred to as "thin" and "fat".  A lock may transition
50d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers * from the "thin" state to the "fat" state and this transition is referred to as inflation. Once
51d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers * a lock has been inflated it remains in the "fat" state indefinitely.
525f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes *
53d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers * The lock value itself is stored in mirror::Object::monitor_ and the representation is described
54d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers * in the LockWord value type.
5554e7df1896a4066cbb9fe6f72249829f0b8c49c6Elliott Hughes *
565f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * Monitors provide:
575f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes *  - mutually exclusive access to resources
585f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes *  - a way for multiple threads to wait for notification
595f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes *
605f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * In effect, they fill the role of both mutexes and condition variables.
615f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes *
62d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers * Only one thread can own the monitor at any time.  There may be several threads waiting on it
63d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers * (the wait call unlocks it).  One or more waiting threads may be getting interrupted or notified
64d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers * at any given time.
655f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes */
6654e7df1896a4066cbb9fe6f72249829f0b8c49c6Elliott Hughes
67fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughesbool (*Monitor::is_sensitive_thread_hook_)() = NULL;
68fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughesuint32_t Monitor::lock_profiling_threshold_ = 0;
6932d6e1e5654433d7eadede89e1c770b2c839aee9Elliott Hughes
70fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughesbool Monitor::IsSensitiveThread() {
71fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes  if (is_sensitive_thread_hook_ != NULL) {
72fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes    return (*is_sensitive_thread_hook_)();
73fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes  }
74fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes  return false;
75fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes}
76fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes
774dd9b4d95eec9db5338fb9bf132f9bb8facf6cf4Elliott Hughesvoid Monitor::Init(uint32_t lock_profiling_threshold, bool (*is_sensitive_thread_hook)()) {
78fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes  lock_profiling_threshold_ = lock_profiling_threshold;
79fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes  is_sensitive_thread_hook_ = is_sensitive_thread_hook;
8032d6e1e5654433d7eadede89e1c770b2c839aee9Elliott Hughes}
8132d6e1e5654433d7eadede89e1c770b2c839aee9Elliott Hughes
82ef7d42fca18c16fbaf103822ad16f23246e2905dIan RogersMonitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code)
8300f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    : monitor_lock_("a monitor lock", kMonitorLock),
84d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      monitor_contenders_("monitor contenders", monitor_lock_),
8546bc778f1feed02b20d25e3d03470c93ca2c0506Mathieu Chartier      num_waiters_(0),
8600f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      owner_(owner),
875f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      lock_count_(0),
885f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      obj_(obj),
895f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      wait_set_(NULL),
90ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier      hash_code_(hash_code),
9133dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao      locking_method_(NULL),
92ef7d42fca18c16fbaf103822ad16f23246e2905dIan Rogers      locking_dex_pc_(0),
93ef7d42fca18c16fbaf103822ad16f23246e2905dIan Rogers      monitor_id_(MonitorPool::CreateMonitorId(self, this)) {
94d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
95d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  // with the owner unlocking the thin-lock.
96ef7d42fca18c16fbaf103822ad16f23246e2905dIan Rogers  CHECK(owner == nullptr || owner == self || owner->IsSuspended());
97ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier  // The identity hash code is set for the life time of the monitor.
98d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers}
99d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers
1004e6a31eb97f22f4480827474b30b9e64f396eaceMathieu Chartierint32_t Monitor::GetHashCode() {
1014e6a31eb97f22f4480827474b30b9e64f396eaceMathieu Chartier  while (!HasHashCode()) {
102b122a4bbed34ab22b4c1541ee25e5cf22f12a926Ian Rogers    if (hash_code_.CompareAndSwap(0, mirror::Object::GenerateIdentityHashCode())) {
1034e6a31eb97f22f4480827474b30b9e64f396eaceMathieu Chartier      break;
1044e6a31eb97f22f4480827474b30b9e64f396eaceMathieu Chartier    }
1054e6a31eb97f22f4480827474b30b9e64f396eaceMathieu Chartier  }
1064e6a31eb97f22f4480827474b30b9e64f396eaceMathieu Chartier  DCHECK(HasHashCode());
107b122a4bbed34ab22b4c1541ee25e5cf22f12a926Ian Rogers  return hash_code_.Load();
1084e6a31eb97f22f4480827474b30b9e64f396eaceMathieu Chartier}
1094e6a31eb97f22f4480827474b30b9e64f396eaceMathieu Chartier
110d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogersbool Monitor::Install(Thread* self) {
111d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  MutexLock mu(self, monitor_lock_);  // Uncontended mutex acquisition as monitor isn't yet public.
112ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier  CHECK(owner_ == nullptr || owner_ == self || owner_->IsSuspended());
11300f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  // Propagate the lock state.
1144d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  LockWord lw(obj_->GetLockWord(false));
115ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier  switch (lw.GetState()) {
116ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    case LockWord::kThinLocked: {
117ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier      CHECK_EQ(owner_->GetThreadId(), lw.ThinLockOwner());
118ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier      lock_count_ = lw.ThinLockCount();
119ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier      break;
120ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    }
121ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    case LockWord::kHashCode: {
1224e6a31eb97f22f4480827474b30b9e64f396eaceMathieu Chartier      CHECK_EQ(hash_code_, static_cast<int32_t>(lw.GetHashCode()));
123ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier      break;
124ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    }
125ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    case LockWord::kFatLocked: {
126ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier      // The owner_ is suspended but another thread beat us to install a monitor.
127ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier      return false;
128ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    }
129ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    case LockWord::kUnlocked: {
130ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier      LOG(FATAL) << "Inflating unlocked lock word";
131ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier      break;
132ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    }
133590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    default: {
134590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      LOG(FATAL) << "Invalid monitor state " << lw.GetState();
135590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      return false;
136590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    }
137d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  }
138d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  LockWord fat(this);
139d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  // Publish the updated lock word, which may race with other threads.
140ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier  bool success = obj_->CasLockWord(lw, fat);
14100f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  // Lock profiling.
1429728f91a63016136261231ff5213bde703bd27b6Mathieu Chartier  if (success && owner_ != nullptr && lock_profiling_threshold_ != 0) {
143d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    locking_method_ = owner_->GetCurrentMethod(&locking_dex_pc_);
14400f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  }
145d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  return success;
1465f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
1475f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
1485f79133a435ebcb20000370d56046fe01201dd80Elliott HughesMonitor::~Monitor() {
149ef7d42fca18c16fbaf103822ad16f23246e2905dIan Rogers  MonitorPool::ReleaseMonitorId(monitor_id_);
150590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier  // Deflated monitors have a null object.
1515f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
1525f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
1535f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes/*
1545f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * Links a thread into a monitor's wait set.  The monitor lock must be
1555f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * held by the caller of this routine.
1565f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes */
1575f79133a435ebcb20000370d56046fe01201dd80Elliott Hughesvoid Monitor::AppendToWaitSet(Thread* thread) {
1585f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  DCHECK(owner_ == Thread::Current());
1595f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  DCHECK(thread != NULL);
160dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers  DCHECK(thread->GetWaitNext() == nullptr) << thread->GetWaitNext();
1615f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  if (wait_set_ == NULL) {
1625f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    wait_set_ = thread;
1635f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    return;
1645f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
1655f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
1665f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  // push_back.
1675f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  Thread* t = wait_set_;
168dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers  while (t->GetWaitNext() != nullptr) {
169dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    t = t->GetWaitNext();
1705f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
171dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers  t->SetWaitNext(thread);
1725f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
1735f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
1745f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes/*
1755f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * Unlinks a thread from a monitor's wait set.  The monitor lock must
1765f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * be held by the caller of this routine.
1775f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes */
1785f79133a435ebcb20000370d56046fe01201dd80Elliott Hughesvoid Monitor::RemoveFromWaitSet(Thread *thread) {
1795f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  DCHECK(owner_ == Thread::Current());
1805f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  DCHECK(thread != NULL);
1815f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  if (wait_set_ == NULL) {
1825f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    return;
1835f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
1845f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  if (wait_set_ == thread) {
185dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    wait_set_ = thread->GetWaitNext();
186dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    thread->SetWaitNext(nullptr);
1875f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    return;
1885f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
1895f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
1905f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  Thread* t = wait_set_;
191dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers  while (t->GetWaitNext() != NULL) {
192dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    if (t->GetWaitNext() == thread) {
193dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers      t->SetWaitNext(thread->GetWaitNext());
194dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers      thread->SetWaitNext(nullptr);
1955f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      return;
1965f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    }
197dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    t = t->GetWaitNext();
1985f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
1995f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
2005f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
2016aa3df965395566ed6a4fec4af37c2b7577992e9Mathieu Chartiervoid Monitor::SetObject(mirror::Object* object) {
2026aa3df965395566ed6a4fec4af37c2b7577992e9Mathieu Chartier  obj_ = object;
2036aa3df965395566ed6a4fec4af37c2b7577992e9Mathieu Chartier}
2046aa3df965395566ed6a4fec4af37c2b7577992e9Mathieu Chartier
2055f79133a435ebcb20000370d56046fe01201dd80Elliott Hughesvoid Monitor::Lock(Thread* self) {
206d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  MutexLock mu(self, monitor_lock_);
207d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  while (true) {
208440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier    if (owner_ == nullptr) {  // Unowned.
209d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      owner_ = self;
210d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      CHECK_EQ(lock_count_, 0);
211d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      // When debugging, save the current monitor holder for future
212d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      // acquisition failures to use in sampled logging.
213d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      if (lock_profiling_threshold_ != 0) {
214d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
215fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes      }
216d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return;
217d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    } else if (owner_ == self) {  // Recursive.
218d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      lock_count_++;
219d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return;
220fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes    }
221d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    // Contended.
222d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    const bool log_contention = (lock_profiling_threshold_ != 0);
223d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    uint64_t wait_start_ms = log_contention ? 0 : MilliTime();
224ef7d42fca18c16fbaf103822ad16f23246e2905dIan Rogers    mirror::ArtMethod* owners_method = locking_method_;
225d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    uint32_t owners_dex_pc = locking_dex_pc_;
226440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier    // Do this before releasing the lock so that we don't get deflated.
227440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier    ++num_waiters_;
228d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    monitor_lock_.Unlock(self);  // Let go of locks in order.
229d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    {
230d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      ScopedThreadStateChange tsc(self, kBlocked);  // Change to blocked and give up mutator_lock_.
231dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers      self->SetMonitorEnterObject(obj_);
232d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      MutexLock mu2(self, monitor_lock_);  // Reacquire monitor_lock_ without mutator_lock_ for Wait.
233d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      if (owner_ != NULL) {  // Did the owner_ give the lock up?
234d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        monitor_contenders_.Wait(self);  // Still contended so wait.
235d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        // Woken from contention.
236d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        if (log_contention) {
237d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          uint64_t wait_ms = MilliTime() - wait_start_ms;
238d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          uint32_t sample_percent;
239d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          if (wait_ms >= lock_profiling_threshold_) {
240d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers            sample_percent = 100;
241d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          } else {
242d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers            sample_percent = 100 * wait_ms / lock_profiling_threshold_;
243d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          }
244d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
245d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers            const char* owners_filename;
246d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers            uint32_t owners_line_number;
247d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers            TranslateLocation(owners_method, owners_dex_pc, &owners_filename, &owners_line_number);
248d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers            LogContentionEvent(self, wait_ms, sample_percent, owners_filename, owners_line_number);
249d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          }
250d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        }
251fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes      }
252dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers      self->SetMonitorEnterObject(nullptr);
2535f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    }
254d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    monitor_lock_.Lock(self);  // Reacquire locks in order.
255440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier    --num_waiters_;
256fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes  }
2575f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
2585f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
2596d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogersstatic void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
2606d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers                                              __attribute__((format(printf, 1, 2)));
2616d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers
26200f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogersstatic void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
263b726dcb581bf72da46527378ccb6889020f0e6e9Ian Rogers    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2646d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers  va_list args;
2656d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers  va_start(args, fmt);
26662d6c772205b8859f0ebf7ad105402ec4c3e2e01Ian Rogers  Thread* self = Thread::Current();
26762d6c772205b8859f0ebf7ad105402ec4c3e2e01Ian Rogers  ThrowLocation throw_location = self->GetCurrentLocationForThrow();
26862d6c772205b8859f0ebf7ad105402ec4c3e2e01Ian Rogers  self->ThrowNewExceptionV(throw_location, "Ljava/lang/IllegalMonitorStateException;", fmt, args);
269d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  if (!Runtime::Current()->IsStarted() || VLOG_IS_ON(monitor)) {
27064277f38032208a0c1081ff9e466c04009b96383Brian Carlstrom    std::ostringstream ss;
27162d6c772205b8859f0ebf7ad105402ec4c3e2e01Ian Rogers    self->Dump(ss);
272d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    LOG(Runtime::Current()->IsStarted() ? INFO : ERROR)
273d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        << self->GetException(NULL)->Dump() << "\n" << ss.str();
27464277f38032208a0c1081ff9e466c04009b96383Brian Carlstrom  }
2756d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers  va_end(args);
2766d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers}
2776d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers
278d423741f91526cada9d081c64ee295ec9863032dElliott Hughesstatic std::string ThreadToString(Thread* thread) {
279d423741f91526cada9d081c64ee295ec9863032dElliott Hughes  if (thread == NULL) {
280d423741f91526cada9d081c64ee295ec9863032dElliott Hughes    return "NULL";
281d423741f91526cada9d081c64ee295ec9863032dElliott Hughes  }
282d423741f91526cada9d081c64ee295ec9863032dElliott Hughes  std::ostringstream oss;
283d423741f91526cada9d081c64ee295ec9863032dElliott Hughes  // TODO: alternatively, we could just return the thread's name.
284d423741f91526cada9d081c64ee295ec9863032dElliott Hughes  oss << *thread;
285d423741f91526cada9d081c64ee295ec9863032dElliott Hughes  return oss.str();
286d423741f91526cada9d081c64ee295ec9863032dElliott Hughes}
287d423741f91526cada9d081c64ee295ec9863032dElliott Hughes
2882dd0e2cea360bc9206eb88ecc40d259e796c239dIan Rogersvoid Monitor::FailedUnlock(mirror::Object* o, Thread* expected_owner, Thread* found_owner,
289ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                           Monitor* monitor) {
290ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  Thread* current_owner = NULL;
291ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  std::string current_owner_string;
292ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  std::string expected_owner_string;
293ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  std::string found_owner_string;
294ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  {
295ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes    // TODO: isn't this too late to prevent threads from disappearing?
296ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes    // Acquire thread list lock so threads won't disappear from under us.
29750b35e2fd1a68cd1240e4a9d9f363e11764957d1Ian Rogers    MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
298ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes    // Re-read owner now that we hold lock.
299d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    current_owner = (monitor != NULL) ? monitor->GetOwner() : NULL;
300ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes    // Get short descriptions of the threads involved.
301ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes    current_owner_string = ThreadToString(current_owner);
302ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes    expected_owner_string = ThreadToString(expected_owner);
303ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes    found_owner_string = ThreadToString(found_owner);
304ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  }
3056d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers  if (current_owner == NULL) {
3066d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers    if (found_owner == NULL) {
3076d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers      ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
3086d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers                                         " on thread '%s'",
309ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                         PrettyTypeOf(o).c_str(),
310ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                         expected_owner_string.c_str());
3116d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers    } else {
3126d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers      // Race: the original read found an owner but now there is none
3136d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers      ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
3146d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers                                         " (where now the monitor appears unowned) on thread '%s'",
315ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                         found_owner_string.c_str(),
316ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                         PrettyTypeOf(o).c_str(),
317ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                         expected_owner_string.c_str());
3186d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers    }
3196d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers  } else {
3206d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers    if (found_owner == NULL) {
3216d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers      // Race: originally there was no owner, there is now
3226d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers      ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
3236d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers                                         " (originally believed to be unowned) on thread '%s'",
324ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                         current_owner_string.c_str(),
325ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                         PrettyTypeOf(o).c_str(),
326ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                         expected_owner_string.c_str());
3276d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers    } else {
3286d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers      if (found_owner != current_owner) {
3296d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers        // Race: originally found and current owner have changed
3306d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers        ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
3316d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers                                           " owned by '%s') on object of type '%s' on thread '%s'",
332ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                           found_owner_string.c_str(),
333ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                           current_owner_string.c_str(),
334ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                           PrettyTypeOf(o).c_str(),
335ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                           expected_owner_string.c_str());
3366d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers      } else {
3376d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers        ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
3386d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers                                           " on thread '%s",
339ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                           current_owner_string.c_str(),
340ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                           PrettyTypeOf(o).c_str(),
341ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                           expected_owner_string.c_str());
3426d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers      }
3436d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers    }
3446d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers  }
3455f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
3465f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
347d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogersbool Monitor::Unlock(Thread* self) {
3485f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  DCHECK(self != NULL);
349d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  MutexLock mu(self, monitor_lock_);
3506d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers  Thread* owner = owner_;
3516d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers  if (owner == self) {
3525f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    // We own the monitor, so nobody else can be in here.
3535f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    if (lock_count_ == 0) {
3545f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      owner_ = NULL;
35533dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao      locking_method_ = NULL;
3560399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers      locking_dex_pc_ = 0;
357d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      // Wake a contender.
358d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      monitor_contenders_.Signal(self);
3595f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    } else {
3605f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      --lock_count_;
3615f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    }
3625f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  } else {
3635f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    // We don't own this, so we're not allowed to unlock it.
3645f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    // The JNI spec says that we should throw IllegalMonitorStateException
3655f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    // in this case.
3666d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers    FailedUnlock(obj_, self, owner, this);
3675f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    return false;
3685f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
3695f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  return true;
3705f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
3715f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
3725f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes/*
3735f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * Wait on a monitor until timeout, interrupt, or notification.  Used for
3745f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * Object.wait() and (somewhat indirectly) Thread.sleep() and Thread.join().
3755f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes *
3765f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * If another thread calls Thread.interrupt(), we throw InterruptedException
3775f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * and return immediately if one of the following are true:
3785f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes *  - blocked in wait(), wait(long), or wait(long, int) methods of Object
3795f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes *  - blocked in join(), join(long), or join(long, int) methods of Thread
3805f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes *  - blocked in sleep(long), or sleep(long, int) methods of Thread
3815f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * Otherwise, we set the "interrupted" flag.
3825f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes *
3835f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * Checks to make sure that "ns" is in the range 0-999999
3845f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * (i.e. fractions of a millisecond) and throws the appropriate
3855f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * exception if it isn't.
3865f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes *
3875f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * The spec allows "spurious wakeups", and recommends that all code using
3885f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * Object.wait() do so in a loop.  This appears to derive from concerns
3895f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * about pthread_cond_wait() on multiprocessor systems.  Some commentary
3905f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * on the web casts doubt on whether these can/should occur.
3915f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes *
3925f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * Since we're allowed to wake up "early", we clamp extremely long durations
3935f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * to return at the end of the 32-bit time epoch.
3945f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes */
3954cd121ef0cb35fced70c7d9de378277be7a727d9Elliott Hughesvoid Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
3964cd121ef0cb35fced70c7d9de378277be7a727d9Elliott Hughes                   bool interruptShouldThrow, ThreadState why) {
3975f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  DCHECK(self != NULL);
3984cd121ef0cb35fced70c7d9de378277be7a727d9Elliott Hughes  DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
3995f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
400d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  monitor_lock_.Lock(self);
401d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers
4025f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  // Make sure that we hold the lock.
4035f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  if (owner_ != self) {
4046d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers    ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
405d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    monitor_lock_.Unlock(self);
4065f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    return;
4075f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
4084cd121ef0cb35fced70c7d9de378277be7a727d9Elliott Hughes
409df42c4815c30b9df15aacb88070c1e94f41d0226Elliott Hughes  // We need to turn a zero-length timed wait into a regular wait because
410df42c4815c30b9df15aacb88070c1e94f41d0226Elliott Hughes  // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
411df42c4815c30b9df15aacb88070c1e94f41d0226Elliott Hughes  if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
412df42c4815c30b9df15aacb88070c1e94f41d0226Elliott Hughes    why = kWaiting;
413df42c4815c30b9df15aacb88070c1e94f41d0226Elliott Hughes  }
414df42c4815c30b9df15aacb88070c1e94f41d0226Elliott Hughes
4155f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  // Enforce the timeout range.
4165f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  if (ms < 0 || ns < 0 || ns > 999999) {
41762d6c772205b8859f0ebf7ad105402ec4c3e2e01Ian Rogers    ThrowLocation throw_location = self->GetCurrentLocationForThrow();
41862d6c772205b8859f0ebf7ad105402ec4c3e2e01Ian Rogers    self->ThrowNewExceptionF(throw_location, "Ljava/lang/IllegalArgumentException;",
419ef7d42fca18c16fbaf103822ad16f23246e2905dIan Rogers                             "timeout arguments out of range: ms=%" PRId64 " ns=%d", ms, ns);
420d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    monitor_lock_.Unlock(self);
4215f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    return;
4225f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
4235f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
4245f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  /*
4255f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   * Add ourselves to the set of threads waiting on this monitor, and
4265f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   * release our hold.  We need to let it go even if we're a few levels
4275f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   * deep in a recursive lock, and we need to restore that later.
4285f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   *
4295f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   * We append to the wait set ahead of clearing the count and owner
4305f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   * fields so the subroutine can check that the calling thread owns
4315f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   * the monitor.  Aside from that, the order of member updates is
4325f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   * not order sensitive as we hold the pthread mutex.
4335f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   */
4345f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  AppendToWaitSet(self);
435440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier  ++num_waiters_;
4360399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  int prev_lock_count = lock_count_;
4375f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  lock_count_ = 0;
4385f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  owner_ = NULL;
439ef7d42fca18c16fbaf103822ad16f23246e2905dIan Rogers  mirror::ArtMethod* saved_method = locking_method_;
44033dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao  locking_method_ = NULL;
4410399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  uintptr_t saved_dex_pc = locking_dex_pc_;
4420399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  locking_dex_pc_ = 0;
4435f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
4445f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  /*
4454cd121ef0cb35fced70c7d9de378277be7a727d9Elliott Hughes   * Update thread state. If the GC wakes up, it'll ignore us, knowing
4465f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   * that we won't touch any references in this state, and we'll check
4475f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   * our suspend mode before we transition out.
4485f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   */
4494cd121ef0cb35fced70c7d9de378277be7a727d9Elliott Hughes  self->TransitionFromRunnableToSuspended(why);
4505f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
451b4e94fd380a84c755264e8668a16052442c7ec32Elliott Hughes  bool was_interrupted = false;
45200f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  {
45300f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
454dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    MutexLock mu(self, *self->GetWaitMutex());
4555f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
45600f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
45700f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    // non-NULL a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
45800f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    // up.
459dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    DCHECK(self->GetWaitMonitor() == nullptr);
460dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    self->SetWaitMonitor(this);
4615f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
46200f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    // Release the monitor lock.
463d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    monitor_contenders_.Signal(self);
464d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    monitor_lock_.Unlock(self);
46500f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers
466b4e94fd380a84c755264e8668a16052442c7ec32Elliott Hughes    // Handle the case where the thread was interrupted before we called wait().
467dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    if (self->IsInterruptedLocked()) {
468b4e94fd380a84c755264e8668a16052442c7ec32Elliott Hughes      was_interrupted = true;
46900f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    } else {
47000f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      // Wait for a notification or a timeout to occur.
4714cd121ef0cb35fced70c7d9de378277be7a727d9Elliott Hughes      if (why == kWaiting) {
472dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers        self->GetWaitConditionVariable()->Wait(self);
47300f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      } else {
4744cd121ef0cb35fced70c7d9de378277be7a727d9Elliott Hughes        DCHECK(why == kTimedWaiting || why == kSleeping) << why;
475dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers        self->GetWaitConditionVariable()->TimedWait(self, ms, ns);
47600f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      }
477dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers      if (self->IsInterruptedLocked()) {
478b4e94fd380a84c755264e8668a16052442c7ec32Elliott Hughes        was_interrupted = true;
47900f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      }
480dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers      self->SetInterruptedLocked(false);
48100f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    }
4825f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
4835f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
48400f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  // Set self->status back to kRunnable, and self-suspend if needed.
48500f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  self->TransitionFromSuspendedToRunnable();
4865f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
487b4e94fd380a84c755264e8668a16052442c7ec32Elliott Hughes  {
488b4e94fd380a84c755264e8668a16052442c7ec32Elliott Hughes    // We reset the thread's wait_monitor_ field after transitioning back to runnable so
489b4e94fd380a84c755264e8668a16052442c7ec32Elliott Hughes    // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
490b4e94fd380a84c755264e8668a16052442c7ec32Elliott Hughes    // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
491b4e94fd380a84c755264e8668a16052442c7ec32Elliott Hughes    // are waiting on "null".)
492dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    MutexLock mu(self, *self->GetWaitMutex());
493dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    DCHECK(self->GetWaitMonitor() != nullptr);
494dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    self->SetWaitMonitor(nullptr);
495b4e94fd380a84c755264e8668a16052442c7ec32Elliott Hughes  }
496b4e94fd380a84c755264e8668a16052442c7ec32Elliott Hughes
497d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  // Re-acquire the monitor and lock.
49800f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  Lock(self);
499d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  monitor_lock_.Lock(self);
500dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers  self->GetWaitMutex()->AssertNotHeld(self);
5015f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
5025f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  /*
5035f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   * We remove our thread from wait set after restoring the count
5045f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   * and owner fields so the subroutine can check that the calling
5055f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   * thread owns the monitor. Aside from that, the order of member
5065f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   * updates is not order sensitive as we hold the pthread mutex.
5075f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   */
5085f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  owner_ = self;
5090399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  lock_count_ = prev_lock_count;
5100399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  locking_method_ = saved_method;
5110399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  locking_dex_pc_ = saved_dex_pc;
512440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier  --num_waiters_;
5135f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  RemoveFromWaitSet(self);
5145f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
515b4e94fd380a84c755264e8668a16052442c7ec32Elliott Hughes  if (was_interrupted) {
5165f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    /*
5175f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes     * We were interrupted while waiting, or somebody interrupted an
5185f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes     * un-interruptible thread earlier and we're bailing out immediately.
5195f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes     *
5205f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes     * The doc sayeth: "The interrupted status of the current thread is
5215f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes     * cleared when this exception is thrown."
5225f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes     */
52300f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    {
524dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers      MutexLock mu(self, *self->GetWaitMutex());
525dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers      self->SetInterruptedLocked(false);
52600f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    }
5275f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    if (interruptShouldThrow) {
52862d6c772205b8859f0ebf7ad105402ec4c3e2e01Ian Rogers      ThrowLocation throw_location = self->GetCurrentLocationForThrow();
52962d6c772205b8859f0ebf7ad105402ec4c3e2e01Ian Rogers      self->ThrowNewException(throw_location, "Ljava/lang/InterruptedException;", NULL);
5305f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    }
5315f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
532d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  monitor_lock_.Unlock(self);
5335f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
5345f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
5355f79133a435ebcb20000370d56046fe01201dd80Elliott Hughesvoid Monitor::Notify(Thread* self) {
5365f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  DCHECK(self != NULL);
537d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  MutexLock mu(self, monitor_lock_);
5385f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  // Make sure that we hold the lock.
5395f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  if (owner_ != self) {
5406d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers    ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
5415f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    return;
5425f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
5435f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  // Signal the first waiting thread in the wait set.
5445f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  while (wait_set_ != NULL) {
5455f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    Thread* thread = wait_set_;
546dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    wait_set_ = thread->GetWaitNext();
547dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    thread->SetWaitNext(nullptr);
5485f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
5495f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    // Check to see if the thread is still waiting.
550dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    MutexLock mu(self, *thread->GetWaitMutex());
551dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    if (thread->GetWaitMonitor() != nullptr) {
552dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers      thread->GetWaitConditionVariable()->Signal(self);
5535f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      return;
5545f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    }
5555f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
5565f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
5575f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
5585f79133a435ebcb20000370d56046fe01201dd80Elliott Hughesvoid Monitor::NotifyAll(Thread* self) {
5595f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  DCHECK(self != NULL);
560d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  MutexLock mu(self, monitor_lock_);
5615f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  // Make sure that we hold the lock.
5625f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  if (owner_ != self) {
5636d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers    ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
5645f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    return;
5655f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
5665f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  // Signal all threads in the wait set.
5675f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  while (wait_set_ != NULL) {
5685f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    Thread* thread = wait_set_;
569dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    wait_set_ = thread->GetWaitNext();
570dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    thread->SetWaitNext(nullptr);
5715f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    thread->Notify();
5725f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
5735f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
5745f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
575590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartierbool Monitor::Deflate(Thread* self, mirror::Object* obj) {
576590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier  DCHECK(obj != nullptr);
5774d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  // Don't need volatile since we only deflate with mutators suspended.
5784d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  LockWord lw(obj->GetLockWord(false));
579590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier  // If the lock isn't an inflated monitor, then we don't need to deflate anything.
580590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier  if (lw.GetState() == LockWord::kFatLocked) {
581590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    Monitor* monitor = lw.FatLockMonitor();
582440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier    DCHECK(monitor != nullptr);
583590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    MutexLock mu(self, monitor->monitor_lock_);
584440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier    // Can't deflate if we have anybody waiting on the CV.
585440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier    if (monitor->num_waiters_ > 0) {
586440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier      return false;
587440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier    }
588590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    Thread* owner = monitor->owner_;
589590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    if (owner != nullptr) {
590590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      // Can't deflate if we are locked and have a hash code.
591590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      if (monitor->HasHashCode()) {
592590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier        return false;
593590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      }
594590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      // Can't deflate if our lock count is too high.
595590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      if (monitor->lock_count_ > LockWord::kThinLockMaxCount) {
596590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier        return false;
597590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      }
598590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      // Deflate to a thin lock.
5994d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier      obj->SetLockWord(LockWord::FromThinLockId(owner->GetThreadId(), monitor->lock_count_), false);
6004d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier      VLOG(monitor) << "Deflated " << obj << " to thin lock " << owner->GetTid() << " / "
6014d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier          << monitor->lock_count_;
602590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    } else if (monitor->HasHashCode()) {
6034d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier      obj->SetLockWord(LockWord::FromHashCode(monitor->GetHashCode()), false);
604440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier      VLOG(monitor) << "Deflated " << obj << " to hash monitor " << monitor->GetHashCode();
605590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    } else {
606590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      // No lock and no hash, just put an empty lock word inside the object.
6074d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier      obj->SetLockWord(LockWord(), false);
608440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier      VLOG(monitor) << "Deflated" << obj << " to empty lock word";
609590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    }
610590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    // The monitor is deflated, mark the object as nullptr so that we know to delete it during the
611590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    // next GC.
612590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    monitor->obj_ = nullptr;
613590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier  }
614590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier  return true;
615590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier}
616590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier
6175f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes/*
618d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers * Changes the shape of a monitor from thin to fat, preserving the internal lock state. The calling
619d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers * thread must own the lock or the owner must be suspended. There's a race with other threads
620d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers * inflating the lock and so the caller should read the monitor following the call.
6215f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes */
622ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartiervoid Monitor::Inflate(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code) {
6235f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  DCHECK(self != NULL);
6245f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  DCHECK(obj != NULL);
6255f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  // Allocate and acquire a new monitor.
626ef7d42fca18c16fbaf103822ad16f23246e2905dIan Rogers  UniquePtr<Monitor> m(new Monitor(self, owner, obj, hash_code));
627d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  if (m->Install(self)) {
628d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    VLOG(monitor) << "monitor: thread " << owner->GetThreadId()
629d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers                    << " created monitor " << m.get() << " for object " << obj;
630d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    Runtime::Current()->GetMonitorList()->Add(m.release());
6314d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier    CHECK_EQ(obj->GetLockWord(true).GetState(), LockWord::kFatLocked);
632ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier  }
633ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier}
634ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier
635eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartiervoid Monitor::InflateThinLocked(Thread* self, Handle<mirror::Object>& obj, LockWord lock_word,
636ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier                                uint32_t hash_code) {
637ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier  DCHECK_EQ(lock_word.GetState(), LockWord::kThinLocked);
638ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier  uint32_t owner_thread_id = lock_word.ThinLockOwner();
639ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier  if (owner_thread_id == self->GetThreadId()) {
640ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    // We own the monitor, we can easily inflate it.
641eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier    Inflate(self, self, obj.Get(), hash_code);
642ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier  } else {
643ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    ThreadList* thread_list = Runtime::Current()->GetThreadList();
644ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    // Suspend the owner, inflate. First change to blocked and give up mutator_lock_.
645ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    ScopedThreadStateChange tsc(self, kBlocked);
646eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier    self->SetMonitorEnterObject(obj.Get());
6474d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier    if (lock_word == obj->GetLockWord(true)) {  // If lock word hasn't changed.
648ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier      bool timed_out;
6495f51d4b80058236759fea1d932470a57f348c199Mathieu Chartier      Thread* owner = thread_list->SuspendThreadByThreadId(owner_thread_id, false, &timed_out);
650ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier      if (owner != nullptr) {
651ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier        // We succeeded in suspending the thread, check the lock's status didn't change.
6524d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier        lock_word = obj->GetLockWord(true);
653ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier        if (lock_word.GetState() == LockWord::kThinLocked &&
654ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier            lock_word.ThinLockOwner() == owner_thread_id) {
655ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier          // Go ahead and inflate the lock.
656eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier          Inflate(self, owner, obj.Get(), hash_code);
657ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier        }
658ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier        thread_list->Resume(owner, false);
659ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier      }
660ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    }
661dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    self->SetMonitorEnterObject(nullptr);
662d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  }
6635f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
6645f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
665719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers// Fool annotalysis into thinking that the lock on obj is acquired.
666719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogersstatic mirror::Object* FakeLock(mirror::Object* obj)
667719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers    EXCLUSIVE_LOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
668719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers  return obj;
669719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers}
670719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers
671719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers// Fool annotalysis into thinking that the lock on obj is release.
672719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogersstatic mirror::Object* FakeUnlock(mirror::Object* obj)
673719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers    UNLOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
674719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers  return obj;
675719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers}
676719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers
677e7e8a5fea2d852cccc840fa046151a16627f26cdMathieu Chartiermirror::Object* Monitor::MonitorEnter(Thread* self, mirror::Object* obj) {
6784681c809ba35d50fab92c592ce8d2c7f8b2731f7Elliott Hughes  DCHECK(self != NULL);
6794681c809ba35d50fab92c592ce8d2c7f8b2731f7Elliott Hughes  DCHECK(obj != NULL);
680719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers  obj = FakeLock(obj);
681d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  uint32_t thread_id = self->GetThreadId();
682d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  size_t contention_count = 0;
683eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier  StackHandleScope<1> hs(self);
684eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier  Handle<mirror::Object> h_obj(hs.NewHandle(obj));
685d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  while (true) {
686eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier    LockWord lock_word = h_obj->GetLockWord(true);
687d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    switch (lock_word.GetState()) {
688d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      case LockWord::kUnlocked: {
689d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0));
690eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier        if (h_obj->CasLockWord(lock_word, thin_locked)) {
691b122a4bbed34ab22b4c1541ee25e5cf22f12a926Ian Rogers          QuasiAtomic::MembarLoadLoad();
692eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier          return h_obj.Get();  // Success!
693d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        }
694d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        continue;  // Go again.
6955f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      }
696d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      case LockWord::kThinLocked: {
697d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        uint32_t owner_thread_id = lock_word.ThinLockOwner();
698d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        if (owner_thread_id == thread_id) {
699d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          // We own the lock, increase the recursion count.
700d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          uint32_t new_count = lock_word.ThinLockCount() + 1;
701d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
702d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers            LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count));
703eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier            h_obj->SetLockWord(thin_locked, true);
704eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier            return h_obj.Get();  // Success!
705d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          } else {
706d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers            // We'd overflow the recursion count, so inflate the monitor.
707eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier            InflateThinLocked(self, h_obj, lock_word, 0);
708d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          }
709d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        } else {
710d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          // Contention.
711d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          contention_count++;
712ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier          Runtime* runtime = Runtime::Current();
713ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier          if (contention_count <= runtime->GetMaxSpinsBeforeThinkLockInflation()) {
714d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers            NanoSleep(1000);  // Sleep for 1us and re-attempt.
7155f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes          } else {
716d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers            contention_count = 0;
717eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier            InflateThinLocked(self, h_obj, lock_word, 0);
7185f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes          }
7195f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes        }
720d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        continue;  // Start from the beginning.
721d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      }
722d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      case LockWord::kFatLocked: {
723d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        Monitor* mon = lock_word.FatLockMonitor();
724d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        mon->Lock(self);
725eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier        return h_obj.Get();  // Success!
7265f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      }
727719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers      case LockWord::kHashCode:
728ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier        // Inflate with the existing hashcode.
729eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier        Inflate(self, nullptr, h_obj.Get(), lock_word.GetHashCode());
730719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers        continue;  // Start from the beginning.
731590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      default: {
732590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier        LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
733eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier        return h_obj.Get();
734590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      }
7355f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    }
7365f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
7375f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
7385f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
7392dd0e2cea360bc9206eb88ecc40d259e796c239dIan Rogersbool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
7405f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  DCHECK(self != NULL);
7415f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  DCHECK(obj != NULL);
742719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers  obj = FakeUnlock(obj);
7434d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  LockWord lock_word = obj->GetLockWord(true);
744eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier  StackHandleScope<1> hs(self);
745eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier  Handle<mirror::Object> h_obj(hs.NewHandle(obj));
746d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  switch (lock_word.GetState()) {
747ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    case LockWord::kHashCode:
748ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier      // Fall-through.
749d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kUnlocked:
750eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier      FailedUnlock(h_obj.Get(), self, nullptr, nullptr);
751d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return false;  // Failure.
752d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kThinLocked: {
753d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      uint32_t thread_id = self->GetThreadId();
754d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      uint32_t owner_thread_id = lock_word.ThinLockOwner();
755d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      if (owner_thread_id != thread_id) {
756d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        // TODO: there's a race here with the owner dying while we unlock.
757d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        Thread* owner =
758d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers            Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
759eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier        FailedUnlock(h_obj.Get(), self, owner, nullptr);
760d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        return false;  // Failure.
7615f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      } else {
762d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        // We own the lock, decrease the recursion count.
763d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        if (lock_word.ThinLockCount() != 0) {
764d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          uint32_t new_count = lock_word.ThinLockCount() - 1;
765d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count));
766eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier          h_obj->SetLockWord(thin_locked, true);
767d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        } else {
768eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier          h_obj->SetLockWord(LockWord(), true);
769d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        }
770d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        return true;  // Success!
7715f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      }
7725f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    }
773d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kFatLocked: {
774d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      Monitor* mon = lock_word.FatLockMonitor();
775d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return mon->Unlock(self);
7765f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    }
777590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    default: {
778590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
779d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return false;
780590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    }
7815f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
7825f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
7835f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
7845f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes/*
7855f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * Object.wait().  Also called for class init.
7865f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes */
7872dd0e2cea360bc9206eb88ecc40d259e796c239dIan Rogersvoid Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
7884cd121ef0cb35fced70c7d9de378277be7a727d9Elliott Hughes                   bool interruptShouldThrow, ThreadState why) {
7894d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  DCHECK(self != nullptr);
7904d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  DCHECK(obj != nullptr);
7914d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  LockWord lock_word = obj->GetLockWord(true);
792d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  switch (lock_word.GetState()) {
793ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    case LockWord::kHashCode:
794ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier      // Fall-through.
795d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kUnlocked:
7966d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers      ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
797d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return;  // Failure.
798d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kThinLocked: {
799d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      uint32_t thread_id = self->GetThreadId();
800d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      uint32_t owner_thread_id = lock_word.ThinLockOwner();
801d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      if (owner_thread_id != thread_id) {
802d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
803d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        return;  // Failure.
804d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      } else {
805d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        // We own the lock, inflate to enqueue ourself on the Monitor.
8064e6a31eb97f22f4480827474b30b9e64f396eaceMathieu Chartier        Inflate(self, self, obj, 0);
8074d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier        lock_word = obj->GetLockWord(true);
808d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      }
809d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      break;
8105f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    }
811d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kFatLocked:
812d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      break;  // Already set for a wait.
813590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    default: {
814590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
815590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      return;
816590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    }
8175f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
818d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  Monitor* mon = lock_word.FatLockMonitor();
819d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  mon->Wait(self, ms, ns, interruptShouldThrow, why);
8205f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
8215f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
82213c479e7e9b62115fe0409e5273c1e976a1c09f9Ian Rogersvoid Monitor::DoNotify(Thread* self, mirror::Object* obj, bool notify_all) {
8234d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  DCHECK(self != nullptr);
8244d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  DCHECK(obj != nullptr);
8254d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  LockWord lock_word = obj->GetLockWord(true);
826d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  switch (lock_word.GetState()) {
827ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    case LockWord::kHashCode:
828ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier      // Fall-through.
829d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kUnlocked:
8306d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers      ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
831d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return;  // Failure.
832d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kThinLocked: {
833d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      uint32_t thread_id = self->GetThreadId();
834d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      uint32_t owner_thread_id = lock_word.ThinLockOwner();
835d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      if (owner_thread_id != thread_id) {
836d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
837d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        return;  // Failure.
838d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      } else {
839d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        // We own the lock but there's no Monitor and therefore no waiters.
840d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        return;  // Success.
841d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      }
842d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    }
843d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kFatLocked: {
844d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      Monitor* mon = lock_word.FatLockMonitor();
845d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      if (notify_all) {
846d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        mon->NotifyAll(self);
847d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      } else {
848d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        mon->Notify(self);
849d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      }
850d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return;  // Success.
8515f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    }
852590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    default: {
853590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
854590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      return;
855590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    }
8565f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
8575f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
8585f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
859d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogersuint32_t Monitor::GetLockOwnerThreadId(mirror::Object* obj) {
8604d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  DCHECK(obj != nullptr);
8614d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  LockWord lock_word = obj->GetLockWord(true);
862d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  switch (lock_word.GetState()) {
863ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    case LockWord::kHashCode:
864ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier      // Fall-through.
865d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kUnlocked:
866d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return ThreadList::kInvalidThreadId;
867d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kThinLocked:
868d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return lock_word.ThinLockOwner();
869d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kFatLocked: {
870d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      Monitor* mon = lock_word.FatLockMonitor();
871d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return mon->GetOwnerThreadId();
8725f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    }
873590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    default: {
874d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      LOG(FATAL) << "Unreachable";
875d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return ThreadList::kInvalidThreadId;
876590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    }
8775f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
8785f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
8795f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
8808e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughesvoid Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
881d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers  // Determine the wait message and object we're waiting or blocked upon.
882d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers  mirror::Object* pretty_object = nullptr;
883d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers  const char* wait_message = nullptr;
884d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  uint32_t lock_owner = ThreadList::kInvalidThreadId;
885d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers  ThreadState state = thread->GetState();
886b4e94fd380a84c755264e8668a16052442c7ec32Elliott Hughes  if (state == kWaiting || state == kTimedWaiting || state == kSleeping) {
887d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    wait_message = (state == kSleeping) ? "  - sleeping on " : "  - waiting on ";
888d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    Thread* self = Thread::Current();
889d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    MutexLock mu(self, *thread->GetWaitMutex());
890d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    Monitor* monitor = thread->GetWaitMonitor();
891d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    if (monitor != nullptr) {
892d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers      pretty_object = monitor->obj_;
8938e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes    }
89434e069606d6f1698cd3c33b39e72b79ae27e1c7bElliott Hughes  } else if (state == kBlocked) {
895d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    wait_message = "  - waiting to lock ";
896d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    pretty_object = thread->GetMonitorEnterObject();
897d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    if (pretty_object != nullptr) {
898d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers      lock_owner = pretty_object->GetLockOwnerThreadId();
8998e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes    }
9008e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  }
9018e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
902d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers  if (wait_message != nullptr) {
903d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    if (pretty_object == nullptr) {
904d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers      os << wait_message << "an unknown object";
905d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    } else {
9064d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier      if ((pretty_object->GetLockWord(true).GetState() == LockWord::kThinLocked) &&
907d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers          Locks::mutator_lock_->IsExclusiveHeld(Thread::Current())) {
908d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers        // Getting the identity hashcode here would result in lock inflation and suspension of the
909d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers        // current thread, which isn't safe if this is the only runnable thread.
910d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers        os << wait_message << StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)",
911d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers                                           reinterpret_cast<intptr_t>(pretty_object),
912d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers                                           PrettyTypeOf(pretty_object).c_str());
913d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers      } else {
914d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers        // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
915d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers        os << wait_message << StringPrintf("<0x%08x> (a %s)", pretty_object->IdentityHashCode(),
916d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers                                           PrettyTypeOf(pretty_object).c_str());
917d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers      }
918d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    }
919d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    // - waiting to lock <0x613f83d8> (a java.lang.Object) held by thread 5
920d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    if (lock_owner != ThreadList::kInvalidThreadId) {
921d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers      os << " held by thread " << lock_owner;
922d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    }
923d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    os << "\n";
9248e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  }
9258e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes}
9268e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
9272dd0e2cea360bc9206eb88ecc40d259e796c239dIan Rogersmirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
928f9501700f51586cb6ba7cc0ffcb5a920bd64adf1Elliott Hughes  // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
929f9501700f51586cb6ba7cc0ffcb5a920bd64adf1Elliott Hughes  // definition of contended that includes a monitor a thread is trying to enter...
930dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers  mirror::Object* result = thread->GetMonitorEnterObject();
931d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  if (result == NULL) {
932d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    // ...but also a monitor that the thread is waiting on.
933dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    MutexLock mu(Thread::Current(), *thread->GetWaitMutex());
934dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    Monitor* monitor = thread->GetWaitMonitor();
935f9501700f51586cb6ba7cc0ffcb5a920bd64adf1Elliott Hughes    if (monitor != NULL) {
936d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      result = monitor->GetObject();
937f9501700f51586cb6ba7cc0ffcb5a920bd64adf1Elliott Hughes    }
938f9501700f51586cb6ba7cc0ffcb5a920bd64adf1Elliott Hughes  }
939d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  return result;
940f9501700f51586cb6ba7cc0ffcb5a920bd64adf1Elliott Hughes}
941f9501700f51586cb6ba7cc0ffcb5a920bd64adf1Elliott Hughes
9422dd0e2cea360bc9206eb88ecc40d259e796c239dIan Rogersvoid Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
9432dd0e2cea360bc9206eb88ecc40d259e796c239dIan Rogers                         void* callback_context) {
944ea46f950e7a51585db293cd7f047de190a482414Brian Carlstrom  mirror::ArtMethod* m = stack_visitor->GetMethod();
94508fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  CHECK(m != NULL);
94608fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes
94708fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  // Native methods are an easy special case.
94808fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
94908fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  if (m->IsNative()) {
95008fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes    if (m->IsSynchronized()) {
951eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier      mirror::Object* jni_this = stack_visitor->GetCurrentHandleScope()->GetReference(0);
9524993bbc8eda377804e585efd918f8ab9d9eab7d4Elliott Hughes      callback(jni_this, callback_context);
95308fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes    }
95408fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes    return;
95508fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  }
95608fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes
95761f916cc4757610ce308bfdea9a00cf29afd2b02jeffhao  // Proxy methods should not be synchronized.
95861f916cc4757610ce308bfdea9a00cf29afd2b02jeffhao  if (m->IsProxyMethod()) {
95961f916cc4757610ce308bfdea9a00cf29afd2b02jeffhao    CHECK(!m->IsSynchronized());
96061f916cc4757610ce308bfdea9a00cf29afd2b02jeffhao    return;
96161f916cc4757610ce308bfdea9a00cf29afd2b02jeffhao  }
96261f916cc4757610ce308bfdea9a00cf29afd2b02jeffhao
96308fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  // <clinit> is another special case. The runtime holds the class lock while calling <clinit>.
96408fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  MethodHelper mh(m);
96508fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  if (mh.IsClassInitializer()) {
9664993bbc8eda377804e585efd918f8ab9d9eab7d4Elliott Hughes    callback(m->GetDeclaringClass(), callback_context);
96708fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes    // Fall through because there might be synchronization in the user code too.
96808fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  }
96908fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes
97008fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  // Is there any reason to believe there's any synchronization in this method?
97108fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  const DexFile::CodeItem* code_item = mh.GetCodeItem();
972caf7654a0e6c76c7489970b1a246fccf220f9982Elliott Hughes  CHECK(code_item != NULL) << PrettyMethod(m);
97308fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  if (code_item->tries_size_ == 0) {
9747934ac288acfb2552bb0b06ec1f61e5820d924a4Brian Carlstrom    return;  // No "tries" implies no synchronization, so no held locks to report.
97508fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  }
97608fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes
97780537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes  // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
97880537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes  // the locks held in this stack frame.
97980537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes  std::vector<uint32_t> monitor_enter_dex_pcs;
98080537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes  verifier::MethodVerifier::FindLocksAtDexPc(m, stack_visitor->GetDexPc(), monitor_enter_dex_pcs);
98180537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes  if (monitor_enter_dex_pcs.empty()) {
98280537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes    return;
98380537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes  }
98408fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes
98580537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes  for (size_t i = 0; i < monitor_enter_dex_pcs.size(); ++i) {
98680537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes    // The verifier works in terms of the dex pcs of the monitor-enter instructions.
98780537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes    // We want the registers used by those instructions (so we can read the values out of them).
98880537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes    uint32_t dex_pc = monitor_enter_dex_pcs[i];
98980537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes    uint16_t monitor_enter_instruction = code_item->insns_[dex_pc];
99008fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes
99180537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes    // Quick sanity check.
99280537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes    if ((monitor_enter_instruction & 0xff) != Instruction::MONITOR_ENTER) {
99380537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes      LOG(FATAL) << "expected monitor-enter @" << dex_pc << "; was "
99480537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes                 << reinterpret_cast<void*>(monitor_enter_instruction);
99508fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes    }
99680537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes
99780537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes    uint16_t monitor_register = ((monitor_enter_instruction >> 8) & 0xff);
9982dd0e2cea360bc9206eb88ecc40d259e796c239dIan Rogers    mirror::Object* o = reinterpret_cast<mirror::Object*>(stack_visitor->GetVReg(m, monitor_register,
9992dd0e2cea360bc9206eb88ecc40d259e796c239dIan Rogers                                                                                 kReferenceVReg));
10004993bbc8eda377804e585efd918f8ab9d9eab7d4Elliott Hughes    callback(o, callback_context);
100108fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  }
100208fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes}
100308fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes
1004d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogersbool Monitor::IsValidLockWord(LockWord lock_word) {
1005d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  switch (lock_word.GetState()) {
1006d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kUnlocked:
1007d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      // Nothing to check.
1008d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return true;
1009d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kThinLocked:
1010d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      // Basic sanity check of owner.
1011d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
1012d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kFatLocked: {
1013d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      // Check the  monitor appears in the monitor list.
1014d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      Monitor* mon = lock_word.FatLockMonitor();
1015d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      MonitorList* list = Runtime::Current()->GetMonitorList();
1016d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      MutexLock mu(Thread::Current(), list->monitor_list_lock_);
1017d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      for (Monitor* list_mon : list->list_) {
1018d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        if (mon == list_mon) {
1019d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          return true;  // Found our monitor.
1020d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        }
10217dfb28c066159e6cde8181720f0c451a700ef966Ian Rogers      }
1022d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return false;  // Fail - unowned monitor in an object.
10237dfb28c066159e6cde8181720f0c451a700ef966Ian Rogers    }
1024ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    case LockWord::kHashCode:
1025ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier      return true;
1026d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    default:
1027d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      LOG(FATAL) << "Unreachable";
1028d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return false;
10297dfb28c066159e6cde8181720f0c451a700ef966Ian Rogers  }
10307dfb28c066159e6cde8181720f0c451a700ef966Ian Rogers}
10317dfb28c066159e6cde8181720f0c451a700ef966Ian Rogers
1032ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartierbool Monitor::IsLocked() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1033ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier  MutexLock mu(Thread::Current(), monitor_lock_);
1034ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier  return owner_ != nullptr;
1035ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier}
1036ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier
1037ef7d42fca18c16fbaf103822ad16f23246e2905dIan Rogersvoid Monitor::TranslateLocation(mirror::ArtMethod* method, uint32_t dex_pc,
1038d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers                                const char** source_file, uint32_t* line_number) const {
103933dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao  // If method is null, location is unknown
104033dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao  if (method == NULL) {
1041d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    *source_file = "";
1042d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    *line_number = 0;
104333dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao    return;
104433dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao  }
10456d4d9fcb4f01e287ee29e81cd1c941ee5d11d379Ian Rogers  MethodHelper mh(method);
1046d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  *source_file = mh.GetDeclaringClassSourceFile();
1047d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  if (*source_file == NULL) {
1048d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    *source_file = "";
1049d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  }
1050d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  *line_number = mh.GetLineNumFromDexPC(dex_pc);
1051d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers}
1052d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers
1053d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogersuint32_t Monitor::GetOwnerThreadId() {
1054d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  MutexLock mu(Thread::Current(), monitor_lock_);
1055d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  Thread* owner = owner_;
1056d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  if (owner != NULL) {
1057d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    return owner->GetThreadId();
1058d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  } else {
1059d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    return ThreadList::kInvalidThreadId;
106012c51e3e5a8b5655351539618f1cf2331f52d1abElliott Hughes  }
106133dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao}
106233dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao
1063c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu ChartierMonitorList::MonitorList()
1064440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier    : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock", kMonitorListLock),
1065c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier      monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
1066c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes}
1067c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes
1068c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott HughesMonitorList::~MonitorList() {
106950b35e2fd1a68cd1240e4a9d9f363e11764957d1Ian Rogers  MutexLock mu(Thread::Current(), monitor_list_lock_);
1070c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes  STLDeleteElements(&list_);
1071c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes}
1072c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes
1073c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartiervoid MonitorList::DisallowNewMonitors() {
107450b35e2fd1a68cd1240e4a9d9f363e11764957d1Ian Rogers  MutexLock mu(Thread::Current(), monitor_list_lock_);
1075c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier  allow_new_monitors_ = false;
1076c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier}
1077c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier
1078c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartiervoid MonitorList::AllowNewMonitors() {
1079c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier  Thread* self = Thread::Current();
1080c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier  MutexLock mu(self, monitor_list_lock_);
1081c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier  allow_new_monitors_ = true;
1082c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier  monitor_add_condition_.Broadcast(self);
1083c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier}
1084c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier
1085c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartiervoid MonitorList::Add(Monitor* m) {
1086c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier  Thread* self = Thread::Current();
1087c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier  MutexLock mu(self, monitor_list_lock_);
1088c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier  while (UNLIKELY(!allow_new_monitors_)) {
1089c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier    monitor_add_condition_.WaitHoldingLocks(self);
1090c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier  }
1091c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes  list_.push_front(m);
1092c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes}
1093c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes
109483c8ee000d525017ead8753fce6bc1020249b96aMathieu Chartiervoid MonitorList::SweepMonitorList(IsMarkedCallback* callback, void* arg) {
109550b35e2fd1a68cd1240e4a9d9f363e11764957d1Ian Rogers  MutexLock mu(Thread::Current(), monitor_list_lock_);
109602e25119b15a6f619f17db99f5d05124a5807ff3Mathieu Chartier  for (auto it = list_.begin(); it != list_.end(); ) {
1097c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes    Monitor* m = *it;
10986aa3df965395566ed6a4fec4af37c2b7577992e9Mathieu Chartier    mirror::Object* obj = m->GetObject();
1099590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    // The object of a monitor can be null if we have deflated it.
110083c8ee000d525017ead8753fce6bc1020249b96aMathieu Chartier    mirror::Object* new_obj = obj != nullptr ? callback(obj, arg) : nullptr;
11016aa3df965395566ed6a4fec4af37c2b7577992e9Mathieu Chartier    if (new_obj == nullptr) {
11026aa3df965395566ed6a4fec4af37c2b7577992e9Mathieu Chartier      VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
11036aa3df965395566ed6a4fec4af37c2b7577992e9Mathieu Chartier                    << m->GetObject();
1104c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes      delete m;
1105c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes      it = list_.erase(it);
1106c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes    } else {
11076aa3df965395566ed6a4fec4af37c2b7577992e9Mathieu Chartier      m->SetObject(new_obj);
1108c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes      ++it;
1109c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes    }
1110c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes  }
1111c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes}
1112c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes
1113440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartierstatic mirror::Object* MonitorDeflateCallback(mirror::Object* object, void* arg)
1114440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1115440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier  if (Monitor::Deflate(reinterpret_cast<Thread*>(arg), object)) {
11164d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier    DCHECK_NE(object->GetLockWord(true).GetState(), LockWord::kFatLocked);
1117440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier    // If we deflated, return nullptr so that the monitor gets removed from the array.
1118440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier    return nullptr;
1119440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier  }
1120440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier  return object;  // Monitor was not deflated.
1121440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier}
1122440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier
1123440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartiervoid MonitorList::DeflateMonitors() {
1124440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier  Thread* self = Thread::Current();
1125440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier  Locks::mutator_lock_->AssertExclusiveHeld(self);
1126440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier  SweepMonitorList(MonitorDeflateCallback, reinterpret_cast<Thread*>(self));
1127440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier}
1128440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier
1129d9c4fc94fa618617f94e1de9af5f034549100753Ian RogersMonitorInfo::MonitorInfo(mirror::Object* obj) : owner_(NULL), entry_count_(0) {
11304d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  DCHECK(obj != nullptr);
11314d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  LockWord lock_word = obj->GetLockWord(true);
1132d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  switch (lock_word.GetState()) {
1133d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kUnlocked:
1134ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier      // Fall-through.
1135590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    case LockWord::kForwardingAddress:
1136590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      // Fall-through.
1137ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    case LockWord::kHashCode:
1138d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      break;
1139d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kThinLocked:
1140d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
1141d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      entry_count_ = 1 + lock_word.ThinLockCount();
1142d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      // Thin locks have no waiters.
1143d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      break;
1144d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kFatLocked: {
1145d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      Monitor* mon = lock_word.FatLockMonitor();
1146d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      owner_ = mon->owner_;
1147d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      entry_count_ = 1 + mon->lock_count_;
1148dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers      for (Thread* waiter = mon->wait_set_; waiter != NULL; waiter = waiter->GetWaitNext()) {
1149d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        waiters_.push_back(waiter);
1150d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      }
1151d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      break;
1152f327e07b37e349b1ec5eaad6dc294a9b7a081d20Elliott Hughes    }
1153f327e07b37e349b1ec5eaad6dc294a9b7a081d20Elliott Hughes  }
1154f327e07b37e349b1ec5eaad6dc294a9b7a081d20Elliott Hughes}
1155f327e07b37e349b1ec5eaad6dc294a9b7a081d20Elliott Hughes
11565f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}  // namespace art
1157