monitor.cc revision 277ccbd200ea43590dfc06a93ae184a765327ad0
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"
3100f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers#include "scoped_thread_state_change.h"
325f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes#include "thread.h"
338e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes#include "thread_list.h"
3408fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes#include "verifier/method_verifier.h"
35044288fb8f69e154862763a6b3bfea2bac1b397eElliott Hughes#include "well_known_classes.h"
365f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
375f79133a435ebcb20000370d56046fe01201dd80Elliott Hughesnamespace art {
385f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
395f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes/*
40d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers * Every Object has a monitor associated with it, but not every Object is actually locked.  Even
41d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers * the ones that are locked do not need a full-fledged monitor until a) there is actual contention
42d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers * or b) wait() is called on the Object.
435f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes *
44d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers * For Android, we have implemented a scheme similar to the one described in Bacon et al.'s
45d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers * "Thin locks: featherweight synchronization for Java" (ACM 1998).  Things are even easier for us,
46d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers * though, because we have a full 32 bits to work with.
475f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes *
48d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers * The two states of an Object's lock are referred to as "thin" and "fat".  A lock may transition
49d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers * from the "thin" state to the "fat" state and this transition is referred to as inflation. Once
50d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers * a lock has been inflated it remains in the "fat" state indefinitely.
515f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes *
52d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers * The lock value itself is stored in mirror::Object::monitor_ and the representation is described
53d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers * in the LockWord value type.
5454e7df1896a4066cbb9fe6f72249829f0b8c49c6Elliott Hughes *
555f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * Monitors provide:
565f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes *  - mutually exclusive access to resources
575f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes *  - a way for multiple threads to wait for notification
585f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes *
595f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * In effect, they fill the role of both mutexes and condition variables.
605f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes *
61d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers * Only one thread can own the monitor at any time.  There may be several threads waiting on it
62d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers * (the wait call unlocks it).  One or more waiting threads may be getting interrupted or notified
63d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers * at any given time.
645f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes */
6554e7df1896a4066cbb9fe6f72249829f0b8c49c6Elliott Hughes
66fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughesbool (*Monitor::is_sensitive_thread_hook_)() = NULL;
67fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughesuint32_t Monitor::lock_profiling_threshold_ = 0;
6832d6e1e5654433d7eadede89e1c770b2c839aee9Elliott Hughes
69fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughesbool Monitor::IsSensitiveThread() {
70fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes  if (is_sensitive_thread_hook_ != NULL) {
71fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes    return (*is_sensitive_thread_hook_)();
72fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes  }
73fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes  return false;
74fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes}
75fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes
764dd9b4d95eec9db5338fb9bf132f9bb8facf6cf4Elliott Hughesvoid Monitor::Init(uint32_t lock_profiling_threshold, bool (*is_sensitive_thread_hook)()) {
77fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes  lock_profiling_threshold_ = lock_profiling_threshold;
78fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes  is_sensitive_thread_hook_ = is_sensitive_thread_hook;
7932d6e1e5654433d7eadede89e1c770b2c839aee9Elliott Hughes}
8032d6e1e5654433d7eadede89e1c770b2c839aee9Elliott Hughes
81ef7d42fca18c16fbaf103822ad16f23246e2905dIan RogersMonitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code)
8200f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    : monitor_lock_("a monitor lock", kMonitorLock),
83d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      monitor_contenders_("monitor contenders", monitor_lock_),
8446bc778f1feed02b20d25e3d03470c93ca2c0506Mathieu Chartier      num_waiters_(0),
8500f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      owner_(owner),
865f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      lock_count_(0),
8794f7b49578b6aaa80de8ffed230648d601393905Hiroshi Yamauchi      obj_(GcRoot<mirror::Object>(obj)),
885f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      wait_set_(NULL),
89ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier      hash_code_(hash_code),
9033dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao      locking_method_(NULL),
91ef7d42fca18c16fbaf103822ad16f23246e2905dIan Rogers      locking_dex_pc_(0),
9274240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe      monitor_id_(MonitorPool::ComputeMonitorId(this, self)) {
9374240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe#ifdef __LP64__
9474240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe  DCHECK(false) << "Should not be reached in 64b";
9574240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe  next_free_ = nullptr;
9674240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe#endif
9774240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe  // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
9874240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe  // with the owner unlocking the thin-lock.
9974240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe  CHECK(owner == nullptr || owner == self || owner->IsSuspended());
10074240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe  // The identity hash code is set for the life time of the monitor.
10174240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe}
10274240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe
10374240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas GampeMonitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code,
10474240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe                 MonitorId id)
10574240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe    : monitor_lock_("a monitor lock", kMonitorLock),
10674240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe      monitor_contenders_("monitor contenders", monitor_lock_),
10774240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe      num_waiters_(0),
10874240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe      owner_(owner),
10974240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe      lock_count_(0),
11094f7b49578b6aaa80de8ffed230648d601393905Hiroshi Yamauchi      obj_(GcRoot<mirror::Object>(obj)),
11174240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe      wait_set_(NULL),
11274240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe      hash_code_(hash_code),
11374240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe      locking_method_(NULL),
11474240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe      locking_dex_pc_(0),
11574240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe      monitor_id_(id) {
11674240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe#ifdef __LP64__
11774240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe  next_free_ = nullptr;
11874240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe#endif
119d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
120d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  // with the owner unlocking the thin-lock.
121ef7d42fca18c16fbaf103822ad16f23246e2905dIan Rogers  CHECK(owner == nullptr || owner == self || owner->IsSuspended());
122ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier  // The identity hash code is set for the life time of the monitor.
123d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers}
124d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers
1254e6a31eb97f22f4480827474b30b9e64f396eaceMathieu Chartierint32_t Monitor::GetHashCode() {
1264e6a31eb97f22f4480827474b30b9e64f396eaceMathieu Chartier  while (!HasHashCode()) {
1273e5cf305db800b2989ad57b7cde8fb3cc9fa1b9eIan Rogers    if (hash_code_.CompareExchangeWeakRelaxed(0, mirror::Object::GenerateIdentityHashCode())) {
1284e6a31eb97f22f4480827474b30b9e64f396eaceMathieu Chartier      break;
1294e6a31eb97f22f4480827474b30b9e64f396eaceMathieu Chartier    }
1304e6a31eb97f22f4480827474b30b9e64f396eaceMathieu Chartier  }
1314e6a31eb97f22f4480827474b30b9e64f396eaceMathieu Chartier  DCHECK(HasHashCode());
1323e5cf305db800b2989ad57b7cde8fb3cc9fa1b9eIan Rogers  return hash_code_.LoadRelaxed();
1334e6a31eb97f22f4480827474b30b9e64f396eaceMathieu Chartier}
1344e6a31eb97f22f4480827474b30b9e64f396eaceMathieu Chartier
135d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogersbool Monitor::Install(Thread* self) {
136d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  MutexLock mu(self, monitor_lock_);  // Uncontended mutex acquisition as monitor isn't yet public.
137ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier  CHECK(owner_ == nullptr || owner_ == self || owner_->IsSuspended());
13800f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  // Propagate the lock state.
1394cba0d979a11f955e6ec3c0f1bf61478af7aa810Hiroshi Yamauchi  LockWord lw(GetObject()->GetLockWord(false));
140ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier  switch (lw.GetState()) {
141ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    case LockWord::kThinLocked: {
142ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier      CHECK_EQ(owner_->GetThreadId(), lw.ThinLockOwner());
143ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier      lock_count_ = lw.ThinLockCount();
144ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier      break;
145ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    }
146ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    case LockWord::kHashCode: {
1473e5cf305db800b2989ad57b7cde8fb3cc9fa1b9eIan Rogers      CHECK_EQ(hash_code_.LoadRelaxed(), static_cast<int32_t>(lw.GetHashCode()));
148ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier      break;
149ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    }
150ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    case LockWord::kFatLocked: {
151ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier      // The owner_ is suspended but another thread beat us to install a monitor.
152ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier      return false;
153ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    }
154ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    case LockWord::kUnlocked: {
155ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier      LOG(FATAL) << "Inflating unlocked lock word";
156ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier      break;
157ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    }
158590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    default: {
159590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      LOG(FATAL) << "Invalid monitor state " << lw.GetState();
160590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      return false;
161590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    }
162d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  }
163d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  LockWord fat(this);
164d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  // Publish the updated lock word, which may race with other threads.
165228602f562f1d130d06e60a98752d99c2d467d6aIan Rogers  bool success = GetObject()->CasLockWordWeakSequentiallyConsistent(lw, fat);
16600f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  // Lock profiling.
1679728f91a63016136261231ff5213bde703bd27b6Mathieu Chartier  if (success && owner_ != nullptr && lock_profiling_threshold_ != 0) {
1686ec8ebd178ed39aa09e4c7fad194900114c4121aAndreas Gampe    // Do not abort on dex pc errors. This can easily happen when we want to dump a stack trace on
1696ec8ebd178ed39aa09e4c7fad194900114c4121aAndreas Gampe    // abort.
1706ec8ebd178ed39aa09e4c7fad194900114c4121aAndreas Gampe    locking_method_ = owner_->GetCurrentMethod(&locking_dex_pc_, false);
17100f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  }
172d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  return success;
1735f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
1745f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
1755f79133a435ebcb20000370d56046fe01201dd80Elliott HughesMonitor::~Monitor() {
176590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier  // Deflated monitors have a null object.
1775f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
1785f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
1795f79133a435ebcb20000370d56046fe01201dd80Elliott Hughesvoid Monitor::AppendToWaitSet(Thread* thread) {
1805f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  DCHECK(owner_ == Thread::Current());
1815f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  DCHECK(thread != NULL);
182dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers  DCHECK(thread->GetWaitNext() == nullptr) << thread->GetWaitNext();
1835f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  if (wait_set_ == NULL) {
1845f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    wait_set_ = thread;
1855f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    return;
1865f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
1875f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
1885f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  // push_back.
1895f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  Thread* t = wait_set_;
190dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers  while (t->GetWaitNext() != nullptr) {
191dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    t = t->GetWaitNext();
1925f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
193dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers  t->SetWaitNext(thread);
1945f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
1955f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
1965f79133a435ebcb20000370d56046fe01201dd80Elliott Hughesvoid Monitor::RemoveFromWaitSet(Thread *thread) {
1975f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  DCHECK(owner_ == Thread::Current());
1985f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  DCHECK(thread != NULL);
1995f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  if (wait_set_ == NULL) {
2005f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    return;
2015f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
2025f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  if (wait_set_ == thread) {
203dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    wait_set_ = thread->GetWaitNext();
204dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    thread->SetWaitNext(nullptr);
2055f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    return;
2065f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
2075f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
2085f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  Thread* t = wait_set_;
209dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers  while (t->GetWaitNext() != NULL) {
210dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    if (t->GetWaitNext() == thread) {
211dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers      t->SetWaitNext(thread->GetWaitNext());
212dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers      thread->SetWaitNext(nullptr);
2135f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      return;
2145f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    }
215dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    t = t->GetWaitNext();
2165f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
2175f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
2185f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
2196aa3df965395566ed6a4fec4af37c2b7577992e9Mathieu Chartiervoid Monitor::SetObject(mirror::Object* object) {
22094f7b49578b6aaa80de8ffed230648d601393905Hiroshi Yamauchi  obj_ = GcRoot<mirror::Object>(object);
2216aa3df965395566ed6a4fec4af37c2b7577992e9Mathieu Chartier}
2226aa3df965395566ed6a4fec4af37c2b7577992e9Mathieu Chartier
2235f79133a435ebcb20000370d56046fe01201dd80Elliott Hughesvoid Monitor::Lock(Thread* self) {
224d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  MutexLock mu(self, monitor_lock_);
225d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  while (true) {
226440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier    if (owner_ == nullptr) {  // Unowned.
227d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      owner_ = self;
228d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      CHECK_EQ(lock_count_, 0);
229d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      // When debugging, save the current monitor holder for future
230d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      // acquisition failures to use in sampled logging.
231d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      if (lock_profiling_threshold_ != 0) {
232d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
233fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes      }
234d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return;
235d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    } else if (owner_ == self) {  // Recursive.
236d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      lock_count_++;
237d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return;
238fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes    }
239d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    // Contended.
240d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    const bool log_contention = (lock_profiling_threshold_ != 0);
24165282b253b55bbdb7f0e246d8c78ea34f84d0ff5Xin Guan    uint64_t wait_start_ms = log_contention ? MilliTime() : 0;
242ef7d42fca18c16fbaf103822ad16f23246e2905dIan Rogers    mirror::ArtMethod* owners_method = locking_method_;
243d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    uint32_t owners_dex_pc = locking_dex_pc_;
244440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier    // Do this before releasing the lock so that we don't get deflated.
245440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier    ++num_waiters_;
246d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    monitor_lock_.Unlock(self);  // Let go of locks in order.
247a6e7f0872c42009ecbee82d7fbe452deef9ae65bMathieu Chartier    self->SetMonitorEnterObject(GetObject());
248d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    {
249d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      ScopedThreadStateChange tsc(self, kBlocked);  // Change to blocked and give up mutator_lock_.
250d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      MutexLock mu2(self, monitor_lock_);  // Reacquire monitor_lock_ without mutator_lock_ for Wait.
251d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      if (owner_ != NULL) {  // Did the owner_ give the lock up?
252d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        monitor_contenders_.Wait(self);  // Still contended so wait.
253d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        // Woken from contention.
254d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        if (log_contention) {
255d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          uint64_t wait_ms = MilliTime() - wait_start_ms;
256d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          uint32_t sample_percent;
257d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          if (wait_ms >= lock_profiling_threshold_) {
258d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers            sample_percent = 100;
259d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          } else {
260d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers            sample_percent = 100 * wait_ms / lock_profiling_threshold_;
261d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          }
262d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
263d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers            const char* owners_filename;
264d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers            uint32_t owners_line_number;
265d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers            TranslateLocation(owners_method, owners_dex_pc, &owners_filename, &owners_line_number);
266d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers            LogContentionEvent(self, wait_ms, sample_percent, owners_filename, owners_line_number);
267d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          }
268d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        }
269fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes      }
2705f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    }
271a6e7f0872c42009ecbee82d7fbe452deef9ae65bMathieu Chartier    self->SetMonitorEnterObject(nullptr);
272d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    monitor_lock_.Lock(self);  // Reacquire locks in order.
273440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier    --num_waiters_;
274fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes  }
2755f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
2765f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
2776d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogersstatic void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
2786d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers                                              __attribute__((format(printf, 1, 2)));
2796d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers
28000f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogersstatic void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
281b726dcb581bf72da46527378ccb6889020f0e6e9Ian Rogers    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2826d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers  va_list args;
2836d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers  va_start(args, fmt);
28462d6c772205b8859f0ebf7ad105402ec4c3e2e01Ian Rogers  Thread* self = Thread::Current();
28562d6c772205b8859f0ebf7ad105402ec4c3e2e01Ian Rogers  ThrowLocation throw_location = self->GetCurrentLocationForThrow();
28662d6c772205b8859f0ebf7ad105402ec4c3e2e01Ian Rogers  self->ThrowNewExceptionV(throw_location, "Ljava/lang/IllegalMonitorStateException;", fmt, args);
287d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  if (!Runtime::Current()->IsStarted() || VLOG_IS_ON(monitor)) {
28864277f38032208a0c1081ff9e466c04009b96383Brian Carlstrom    std::ostringstream ss;
28962d6c772205b8859f0ebf7ad105402ec4c3e2e01Ian Rogers    self->Dump(ss);
290d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    LOG(Runtime::Current()->IsStarted() ? INFO : ERROR)
291d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        << self->GetException(NULL)->Dump() << "\n" << ss.str();
29264277f38032208a0c1081ff9e466c04009b96383Brian Carlstrom  }
2936d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers  va_end(args);
2946d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers}
2956d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers
296d423741f91526cada9d081c64ee295ec9863032dElliott Hughesstatic std::string ThreadToString(Thread* thread) {
297d423741f91526cada9d081c64ee295ec9863032dElliott Hughes  if (thread == NULL) {
298d423741f91526cada9d081c64ee295ec9863032dElliott Hughes    return "NULL";
299d423741f91526cada9d081c64ee295ec9863032dElliott Hughes  }
300d423741f91526cada9d081c64ee295ec9863032dElliott Hughes  std::ostringstream oss;
301d423741f91526cada9d081c64ee295ec9863032dElliott Hughes  // TODO: alternatively, we could just return the thread's name.
302d423741f91526cada9d081c64ee295ec9863032dElliott Hughes  oss << *thread;
303d423741f91526cada9d081c64ee295ec9863032dElliott Hughes  return oss.str();
304d423741f91526cada9d081c64ee295ec9863032dElliott Hughes}
305d423741f91526cada9d081c64ee295ec9863032dElliott Hughes
3062dd0e2cea360bc9206eb88ecc40d259e796c239dIan Rogersvoid Monitor::FailedUnlock(mirror::Object* o, Thread* expected_owner, Thread* found_owner,
307ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                           Monitor* monitor) {
308ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  Thread* current_owner = NULL;
309ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  std::string current_owner_string;
310ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  std::string expected_owner_string;
311ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  std::string found_owner_string;
312ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  {
313ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes    // TODO: isn't this too late to prevent threads from disappearing?
314ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes    // Acquire thread list lock so threads won't disappear from under us.
31550b35e2fd1a68cd1240e4a9d9f363e11764957d1Ian Rogers    MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
316ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes    // Re-read owner now that we hold lock.
317d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    current_owner = (monitor != NULL) ? monitor->GetOwner() : NULL;
318ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes    // Get short descriptions of the threads involved.
319ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes    current_owner_string = ThreadToString(current_owner);
320ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes    expected_owner_string = ThreadToString(expected_owner);
321ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes    found_owner_string = ThreadToString(found_owner);
322ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  }
3236d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers  if (current_owner == NULL) {
3246d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers    if (found_owner == NULL) {
3256d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers      ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
3266d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers                                         " on thread '%s'",
327ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                         PrettyTypeOf(o).c_str(),
328ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                         expected_owner_string.c_str());
3296d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers    } else {
3306d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers      // Race: the original read found an owner but now there is none
3316d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers      ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
3326d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers                                         " (where now the monitor appears unowned) on thread '%s'",
333ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                         found_owner_string.c_str(),
334ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                         PrettyTypeOf(o).c_str(),
335ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                         expected_owner_string.c_str());
3366d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers    }
3376d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers  } else {
3386d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers    if (found_owner == NULL) {
3396d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers      // Race: originally there was no owner, there is now
3406d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers      ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
3416d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers                                         " (originally believed to be unowned) on thread '%s'",
342ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                         current_owner_string.c_str(),
343ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                         PrettyTypeOf(o).c_str(),
344ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                         expected_owner_string.c_str());
3456d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers    } else {
3466d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers      if (found_owner != current_owner) {
3476d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers        // Race: originally found and current owner have changed
3486d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers        ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
3496d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers                                           " owned by '%s') on object of type '%s' on thread '%s'",
350ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                           found_owner_string.c_str(),
351ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                           current_owner_string.c_str(),
352ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                           PrettyTypeOf(o).c_str(),
353ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                           expected_owner_string.c_str());
3546d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers      } else {
3556d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers        ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
3566d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers                                           " on thread '%s",
357ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                           current_owner_string.c_str(),
358ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                           PrettyTypeOf(o).c_str(),
359ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                           expected_owner_string.c_str());
3606d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers      }
3616d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers    }
3626d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers  }
3635f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
3645f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
365d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogersbool Monitor::Unlock(Thread* self) {
3665f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  DCHECK(self != NULL);
367d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  MutexLock mu(self, monitor_lock_);
3686d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers  Thread* owner = owner_;
3696d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers  if (owner == self) {
3705f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    // We own the monitor, so nobody else can be in here.
3715f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    if (lock_count_ == 0) {
3725f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      owner_ = NULL;
37333dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao      locking_method_ = NULL;
3740399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers      locking_dex_pc_ = 0;
375d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      // Wake a contender.
376d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      monitor_contenders_.Signal(self);
3775f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    } else {
3785f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      --lock_count_;
3795f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    }
3805f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  } else {
3815f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    // We don't own this, so we're not allowed to unlock it.
3825f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    // The JNI spec says that we should throw IllegalMonitorStateException
3835f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    // in this case.
3844cba0d979a11f955e6ec3c0f1bf61478af7aa810Hiroshi Yamauchi    FailedUnlock(GetObject(), self, owner, this);
3855f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    return false;
3865f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
3875f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  return true;
3885f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
3895f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
3904cd121ef0cb35fced70c7d9de378277be7a727d9Elliott Hughesvoid Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
3914cd121ef0cb35fced70c7d9de378277be7a727d9Elliott Hughes                   bool interruptShouldThrow, ThreadState why) {
3925f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  DCHECK(self != NULL);
3934cd121ef0cb35fced70c7d9de378277be7a727d9Elliott Hughes  DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
3945f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
395d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  monitor_lock_.Lock(self);
396d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers
3975f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  // Make sure that we hold the lock.
3985f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  if (owner_ != self) {
399d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    monitor_lock_.Unlock(self);
4001af6a1fa35ff7dc0a5c653f19dbc8a91c914aa42Elena Sayapina    ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
4015f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    return;
4025f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
4034cd121ef0cb35fced70c7d9de378277be7a727d9Elliott Hughes
404df42c4815c30b9df15aacb88070c1e94f41d0226Elliott Hughes  // We need to turn a zero-length timed wait into a regular wait because
405df42c4815c30b9df15aacb88070c1e94f41d0226Elliott Hughes  // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
406df42c4815c30b9df15aacb88070c1e94f41d0226Elliott Hughes  if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
407df42c4815c30b9df15aacb88070c1e94f41d0226Elliott Hughes    why = kWaiting;
408df42c4815c30b9df15aacb88070c1e94f41d0226Elliott Hughes  }
409df42c4815c30b9df15aacb88070c1e94f41d0226Elliott Hughes
4105f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  // Enforce the timeout range.
4115f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  if (ms < 0 || ns < 0 || ns > 999999) {
4121af6a1fa35ff7dc0a5c653f19dbc8a91c914aa42Elena Sayapina    monitor_lock_.Unlock(self);
41362d6c772205b8859f0ebf7ad105402ec4c3e2e01Ian Rogers    ThrowLocation throw_location = self->GetCurrentLocationForThrow();
41462d6c772205b8859f0ebf7ad105402ec4c3e2e01Ian Rogers    self->ThrowNewExceptionF(throw_location, "Ljava/lang/IllegalArgumentException;",
415ef7d42fca18c16fbaf103822ad16f23246e2905dIan Rogers                             "timeout arguments out of range: ms=%" PRId64 " ns=%d", ms, ns);
4165f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    return;
4175f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
4185f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
4195f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  /*
4205f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   * Add ourselves to the set of threads waiting on this monitor, and
4215f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   * release our hold.  We need to let it go even if we're a few levels
4225f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   * deep in a recursive lock, and we need to restore that later.
4235f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   *
4245f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   * We append to the wait set ahead of clearing the count and owner
4255f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   * fields so the subroutine can check that the calling thread owns
4265f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   * the monitor.  Aside from that, the order of member updates is
4275f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   * not order sensitive as we hold the pthread mutex.
4285f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   */
4295f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  AppendToWaitSet(self);
430440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier  ++num_waiters_;
4310399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  int prev_lock_count = lock_count_;
4325f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  lock_count_ = 0;
4335f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  owner_ = NULL;
434ef7d42fca18c16fbaf103822ad16f23246e2905dIan Rogers  mirror::ArtMethod* saved_method = locking_method_;
43533dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao  locking_method_ = NULL;
4360399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  uintptr_t saved_dex_pc = locking_dex_pc_;
4370399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  locking_dex_pc_ = 0;
4385f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
4395f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  /*
4404cd121ef0cb35fced70c7d9de378277be7a727d9Elliott Hughes   * Update thread state. If the GC wakes up, it'll ignore us, knowing
4415f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   * that we won't touch any references in this state, and we'll check
4425f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   * our suspend mode before we transition out.
4435f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   */
4444cd121ef0cb35fced70c7d9de378277be7a727d9Elliott Hughes  self->TransitionFromRunnableToSuspended(why);
4455f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
446b4e94fd380a84c755264e8668a16052442c7ec32Elliott Hughes  bool was_interrupted = false;
44700f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  {
44800f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
449dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    MutexLock mu(self, *self->GetWaitMutex());
4505f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
45100f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
45200f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    // non-NULL a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
45300f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    // up.
454dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    DCHECK(self->GetWaitMonitor() == nullptr);
455dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    self->SetWaitMonitor(this);
4565f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
45700f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    // Release the monitor lock.
458d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    monitor_contenders_.Signal(self);
459d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    monitor_lock_.Unlock(self);
46000f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers
461b4e94fd380a84c755264e8668a16052442c7ec32Elliott Hughes    // Handle the case where the thread was interrupted before we called wait().
462dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    if (self->IsInterruptedLocked()) {
463b4e94fd380a84c755264e8668a16052442c7ec32Elliott Hughes      was_interrupted = true;
46400f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    } else {
46500f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      // Wait for a notification or a timeout to occur.
4664cd121ef0cb35fced70c7d9de378277be7a727d9Elliott Hughes      if (why == kWaiting) {
467dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers        self->GetWaitConditionVariable()->Wait(self);
46800f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      } else {
4694cd121ef0cb35fced70c7d9de378277be7a727d9Elliott Hughes        DCHECK(why == kTimedWaiting || why == kSleeping) << why;
470dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers        self->GetWaitConditionVariable()->TimedWait(self, ms, ns);
47100f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      }
472dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers      if (self->IsInterruptedLocked()) {
473b4e94fd380a84c755264e8668a16052442c7ec32Elliott Hughes        was_interrupted = true;
47400f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      }
475dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers      self->SetInterruptedLocked(false);
47600f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    }
4775f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
4785f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
47900f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  // Set self->status back to kRunnable, and self-suspend if needed.
48000f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  self->TransitionFromSuspendedToRunnable();
4815f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
482b4e94fd380a84c755264e8668a16052442c7ec32Elliott Hughes  {
483b4e94fd380a84c755264e8668a16052442c7ec32Elliott Hughes    // We reset the thread's wait_monitor_ field after transitioning back to runnable so
484b4e94fd380a84c755264e8668a16052442c7ec32Elliott Hughes    // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
485b4e94fd380a84c755264e8668a16052442c7ec32Elliott Hughes    // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
486b4e94fd380a84c755264e8668a16052442c7ec32Elliott Hughes    // are waiting on "null".)
487dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    MutexLock mu(self, *self->GetWaitMutex());
488dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    DCHECK(self->GetWaitMonitor() != nullptr);
489dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    self->SetWaitMonitor(nullptr);
490b4e94fd380a84c755264e8668a16052442c7ec32Elliott Hughes  }
491b4e94fd380a84c755264e8668a16052442c7ec32Elliott Hughes
492d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  // Re-acquire the monitor and lock.
49300f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  Lock(self);
494d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  monitor_lock_.Lock(self);
495dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers  self->GetWaitMutex()->AssertNotHeld(self);
4965f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
4975f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  /*
4985f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   * We remove our thread from wait set after restoring the count
4995f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   * and owner fields so the subroutine can check that the calling
5005f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   * thread owns the monitor. Aside from that, the order of member
5015f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   * updates is not order sensitive as we hold the pthread mutex.
5025f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   */
5035f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  owner_ = self;
5040399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  lock_count_ = prev_lock_count;
5050399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  locking_method_ = saved_method;
5060399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  locking_dex_pc_ = saved_dex_pc;
507440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier  --num_waiters_;
5085f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  RemoveFromWaitSet(self);
5095f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
5101af6a1fa35ff7dc0a5c653f19dbc8a91c914aa42Elena Sayapina  monitor_lock_.Unlock(self);
5111af6a1fa35ff7dc0a5c653f19dbc8a91c914aa42Elena Sayapina
512b4e94fd380a84c755264e8668a16052442c7ec32Elliott Hughes  if (was_interrupted) {
5135f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    /*
5145f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes     * We were interrupted while waiting, or somebody interrupted an
5155f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes     * un-interruptible thread earlier and we're bailing out immediately.
5165f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes     *
5175f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes     * The doc sayeth: "The interrupted status of the current thread is
5185f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes     * cleared when this exception is thrown."
5195f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes     */
52000f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    {
521dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers      MutexLock mu(self, *self->GetWaitMutex());
522dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers      self->SetInterruptedLocked(false);
52300f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    }
5245f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    if (interruptShouldThrow) {
52562d6c772205b8859f0ebf7ad105402ec4c3e2e01Ian Rogers      ThrowLocation throw_location = self->GetCurrentLocationForThrow();
52662d6c772205b8859f0ebf7ad105402ec4c3e2e01Ian Rogers      self->ThrowNewException(throw_location, "Ljava/lang/InterruptedException;", NULL);
5275f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    }
5285f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
5295f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
5305f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
5315f79133a435ebcb20000370d56046fe01201dd80Elliott Hughesvoid Monitor::Notify(Thread* self) {
5325f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  DCHECK(self != NULL);
533d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  MutexLock mu(self, monitor_lock_);
5345f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  // Make sure that we hold the lock.
5355f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  if (owner_ != self) {
5366d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers    ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
5375f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    return;
5385f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
5395f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  // Signal the first waiting thread in the wait set.
5405f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  while (wait_set_ != NULL) {
5415f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    Thread* thread = wait_set_;
542dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    wait_set_ = thread->GetWaitNext();
543dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    thread->SetWaitNext(nullptr);
5445f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
5455f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    // Check to see if the thread is still waiting.
546277ccbd200ea43590dfc06a93ae184a765327ad0Andreas Gampe    MutexLock wait_mu(self, *thread->GetWaitMutex());
547dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    if (thread->GetWaitMonitor() != nullptr) {
548dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers      thread->GetWaitConditionVariable()->Signal(self);
5495f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      return;
5505f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    }
5515f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
5525f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
5535f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
5545f79133a435ebcb20000370d56046fe01201dd80Elliott Hughesvoid Monitor::NotifyAll(Thread* self) {
5555f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  DCHECK(self != NULL);
556d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  MutexLock mu(self, monitor_lock_);
5575f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  // Make sure that we hold the lock.
5585f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  if (owner_ != self) {
5596d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers    ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
5605f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    return;
5615f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
5625f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  // Signal all threads in the wait set.
5635f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  while (wait_set_ != NULL) {
5645f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    Thread* thread = wait_set_;
565dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    wait_set_ = thread->GetWaitNext();
566dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    thread->SetWaitNext(nullptr);
5675f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    thread->Notify();
5685f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
5695f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
5705f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
571590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartierbool Monitor::Deflate(Thread* self, mirror::Object* obj) {
572590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier  DCHECK(obj != nullptr);
5734d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  // Don't need volatile since we only deflate with mutators suspended.
5744d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  LockWord lw(obj->GetLockWord(false));
575590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier  // If the lock isn't an inflated monitor, then we don't need to deflate anything.
576590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier  if (lw.GetState() == LockWord::kFatLocked) {
577590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    Monitor* monitor = lw.FatLockMonitor();
578440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier    DCHECK(monitor != nullptr);
579590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    MutexLock mu(self, monitor->monitor_lock_);
580440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier    // Can't deflate if we have anybody waiting on the CV.
581440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier    if (monitor->num_waiters_ > 0) {
582440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier      return false;
583440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier    }
584590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    Thread* owner = monitor->owner_;
585590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    if (owner != nullptr) {
586590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      // Can't deflate if we are locked and have a hash code.
587590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      if (monitor->HasHashCode()) {
588590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier        return false;
589590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      }
590590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      // Can't deflate if our lock count is too high.
591590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      if (monitor->lock_count_ > LockWord::kThinLockMaxCount) {
592590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier        return false;
593590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      }
594590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      // Deflate to a thin lock.
5954d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier      obj->SetLockWord(LockWord::FromThinLockId(owner->GetThreadId(), monitor->lock_count_), false);
5964d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier      VLOG(monitor) << "Deflated " << obj << " to thin lock " << owner->GetTid() << " / "
5974d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier          << monitor->lock_count_;
598590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    } else if (monitor->HasHashCode()) {
5994d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier      obj->SetLockWord(LockWord::FromHashCode(monitor->GetHashCode()), false);
600440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier      VLOG(monitor) << "Deflated " << obj << " to hash monitor " << monitor->GetHashCode();
601590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    } else {
602590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      // No lock and no hash, just put an empty lock word inside the object.
6034d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier      obj->SetLockWord(LockWord(), false);
604440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier      VLOG(monitor) << "Deflated" << obj << " to empty lock word";
605590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    }
606590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    // The monitor is deflated, mark the object as nullptr so that we know to delete it during the
607590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    // next GC.
60894f7b49578b6aaa80de8ffed230648d601393905Hiroshi Yamauchi    monitor->obj_ = GcRoot<mirror::Object>(nullptr);
609590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier  }
610590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier  return true;
611590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier}
612590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier
613ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartiervoid Monitor::Inflate(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code) {
61474240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe  DCHECK(self != nullptr);
61574240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe  DCHECK(obj != nullptr);
6165f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  // Allocate and acquire a new monitor.
61774240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe  Monitor* m = MonitorPool::CreateMonitor(self, owner, obj, hash_code);
61874240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe  DCHECK(m != nullptr);
619d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  if (m->Install(self)) {
62086ab7912423f63541073af5c487b509e9b2b5420Haifeng Li    if (owner != nullptr) {
62186ab7912423f63541073af5c487b509e9b2b5420Haifeng Li      VLOG(monitor) << "monitor: thread" << owner->GetThreadId()
62274240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe          << " created monitor " << m << " for object " << obj;
62386ab7912423f63541073af5c487b509e9b2b5420Haifeng Li    } else {
62486ab7912423f63541073af5c487b509e9b2b5420Haifeng Li      VLOG(monitor) << "monitor: Inflate with hashcode " << hash_code
62574240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe          << " created monitor " << m << " for object " << obj;
62686ab7912423f63541073af5c487b509e9b2b5420Haifeng Li    }
62774240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe    Runtime::Current()->GetMonitorList()->Add(m);
6284d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier    CHECK_EQ(obj->GetLockWord(true).GetState(), LockWord::kFatLocked);
62974240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe  } else {
63074240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe    MonitorPool::ReleaseMonitor(self, m);
631ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier  }
632ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier}
633ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier
6340cd81352a7c06e381951cea1b104fd73516f4341Mathieu Chartiervoid Monitor::InflateThinLocked(Thread* self, Handle<mirror::Object> obj, LockWord lock_word,
635ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier                                uint32_t hash_code) {
636ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier  DCHECK_EQ(lock_word.GetState(), LockWord::kThinLocked);
637ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier  uint32_t owner_thread_id = lock_word.ThinLockOwner();
638ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier  if (owner_thread_id == self->GetThreadId()) {
639ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    // We own the monitor, we can easily inflate it.
640eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier    Inflate(self, self, obj.Get(), hash_code);
641ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier  } else {
642ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    ThreadList* thread_list = Runtime::Current()->GetThreadList();
643ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    // Suspend the owner, inflate. First change to blocked and give up mutator_lock_.
644eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier    self->SetMonitorEnterObject(obj.Get());
645a1ee14fc66a3c99bb7d5744ace881ec93c46f59dMathieu Chartier    bool timed_out;
646a1ee14fc66a3c99bb7d5744ace881ec93c46f59dMathieu Chartier    Thread* owner;
647a1ee14fc66a3c99bb7d5744ace881ec93c46f59dMathieu Chartier    {
648a1ee14fc66a3c99bb7d5744ace881ec93c46f59dMathieu Chartier      ScopedThreadStateChange tsc(self, kBlocked);
649f3d874c60ee3ada19ce26a5c4e532312b6f3a9e9Ian Rogers      // Take suspend thread lock to avoid races with threads trying to suspend this one.
650f3d874c60ee3ada19ce26a5c4e532312b6f3a9e9Ian Rogers      MutexLock mu(self, *Locks::thread_list_suspend_thread_lock_);
651a1ee14fc66a3c99bb7d5744ace881ec93c46f59dMathieu Chartier      owner = thread_list->SuspendThreadByThreadId(owner_thread_id, false, &timed_out);
652a1ee14fc66a3c99bb7d5744ace881ec93c46f59dMathieu Chartier    }
653a1ee14fc66a3c99bb7d5744ace881ec93c46f59dMathieu Chartier    if (owner != nullptr) {
654a1ee14fc66a3c99bb7d5744ace881ec93c46f59dMathieu Chartier      // We succeeded in suspending the thread, check the lock's status didn't change.
655a1ee14fc66a3c99bb7d5744ace881ec93c46f59dMathieu Chartier      lock_word = obj->GetLockWord(true);
656a1ee14fc66a3c99bb7d5744ace881ec93c46f59dMathieu Chartier      if (lock_word.GetState() == LockWord::kThinLocked &&
657a1ee14fc66a3c99bb7d5744ace881ec93c46f59dMathieu Chartier          lock_word.ThinLockOwner() == owner_thread_id) {
658a1ee14fc66a3c99bb7d5744ace881ec93c46f59dMathieu Chartier        // Go ahead and inflate the lock.
659a1ee14fc66a3c99bb7d5744ace881ec93c46f59dMathieu Chartier        Inflate(self, owner, obj.Get(), hash_code);
660ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier      }
661a1ee14fc66a3c99bb7d5744ace881ec93c46f59dMathieu Chartier      thread_list->Resume(owner, false);
662ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    }
663dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    self->SetMonitorEnterObject(nullptr);
664d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  }
6655f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
6665f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
667719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers// Fool annotalysis into thinking that the lock on obj is acquired.
668719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogersstatic mirror::Object* FakeLock(mirror::Object* obj)
669719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers    EXCLUSIVE_LOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
670719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers  return obj;
671719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers}
672719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers
673719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers// Fool annotalysis into thinking that the lock on obj is release.
674719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogersstatic mirror::Object* FakeUnlock(mirror::Object* obj)
675719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers    UNLOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
676719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers  return obj;
677719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers}
678719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers
679e7e8a5fea2d852cccc840fa046151a16627f26cdMathieu Chartiermirror::Object* Monitor::MonitorEnter(Thread* self, mirror::Object* obj) {
6804681c809ba35d50fab92c592ce8d2c7f8b2731f7Elliott Hughes  DCHECK(self != NULL);
6814681c809ba35d50fab92c592ce8d2c7f8b2731f7Elliott Hughes  DCHECK(obj != NULL);
682719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers  obj = FakeLock(obj);
683d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  uint32_t thread_id = self->GetThreadId();
684d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  size_t contention_count = 0;
685eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier  StackHandleScope<1> hs(self);
686eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier  Handle<mirror::Object> h_obj(hs.NewHandle(obj));
687d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  while (true) {
688eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier    LockWord lock_word = h_obj->GetLockWord(true);
689d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    switch (lock_word.GetState()) {
690d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      case LockWord::kUnlocked: {
691d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0));
692228602f562f1d130d06e60a98752d99c2d467d6aIan Rogers        if (h_obj->CasLockWordWeakSequentiallyConsistent(lock_word, thin_locked)) {
6933035961cb41865b80b927546be0c708b6389cec6Hans Boehm          // CasLockWord enforces more than the acquire ordering we need here.
694eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier          return h_obj.Get();  // Success!
695d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        }
696d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        continue;  // Go again.
6975f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      }
698d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      case LockWord::kThinLocked: {
699d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        uint32_t owner_thread_id = lock_word.ThinLockOwner();
700d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        if (owner_thread_id == thread_id) {
701d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          // We own the lock, increase the recursion count.
702d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          uint32_t new_count = lock_word.ThinLockCount() + 1;
703d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
704d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers            LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count));
705eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier            h_obj->SetLockWord(thin_locked, true);
706eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier            return h_obj.Get();  // Success!
707d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          } else {
708d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers            // We'd overflow the recursion count, so inflate the monitor.
709eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier            InflateThinLocked(self, h_obj, lock_word, 0);
710d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          }
711d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        } else {
712d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          // Contention.
713d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          contention_count++;
714ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier          Runtime* runtime = Runtime::Current();
715ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier          if (contention_count <= runtime->GetMaxSpinsBeforeThinkLockInflation()) {
716b363f666883860d40823d5528df3c98c897f74f4Mathieu Chartier            // TODO: Consider switching the thread state to kBlocked when we are yielding.
717251755cd511463260e60be98bf138b6aa1c14bf3Mathieu Chartier            // Use sched_yield instead of NanoSleep since NanoSleep can wait much longer than the
718251755cd511463260e60be98bf138b6aa1c14bf3Mathieu Chartier            // parameter you pass in. This can cause thread suspension to take excessively long
719b363f666883860d40823d5528df3c98c897f74f4Mathieu Chartier            // and make long pauses. See b/16307460.
720251755cd511463260e60be98bf138b6aa1c14bf3Mathieu Chartier            sched_yield();
7215f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes          } else {
722d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers            contention_count = 0;
723eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier            InflateThinLocked(self, h_obj, lock_word, 0);
7245f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes          }
7255f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes        }
726d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        continue;  // Start from the beginning.
727d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      }
728d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      case LockWord::kFatLocked: {
729d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        Monitor* mon = lock_word.FatLockMonitor();
730d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        mon->Lock(self);
731eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier        return h_obj.Get();  // Success!
7325f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      }
733719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers      case LockWord::kHashCode:
734ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier        // Inflate with the existing hashcode.
735eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier        Inflate(self, nullptr, h_obj.Get(), lock_word.GetHashCode());
736719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers        continue;  // Start from the beginning.
737590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      default: {
738590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier        LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
739eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier        return h_obj.Get();
740590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      }
7415f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    }
7425f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
7435f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
7445f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
7452dd0e2cea360bc9206eb88ecc40d259e796c239dIan Rogersbool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
7465f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  DCHECK(self != NULL);
7475f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  DCHECK(obj != NULL);
748719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers  obj = FakeUnlock(obj);
7494d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  LockWord lock_word = obj->GetLockWord(true);
750eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier  StackHandleScope<1> hs(self);
751eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier  Handle<mirror::Object> h_obj(hs.NewHandle(obj));
752d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  switch (lock_word.GetState()) {
753ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    case LockWord::kHashCode:
754ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier      // Fall-through.
755d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kUnlocked:
756eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier      FailedUnlock(h_obj.Get(), self, nullptr, nullptr);
757d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return false;  // Failure.
758d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kThinLocked: {
759d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      uint32_t thread_id = self->GetThreadId();
760d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      uint32_t owner_thread_id = lock_word.ThinLockOwner();
761d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      if (owner_thread_id != thread_id) {
762d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        // TODO: there's a race here with the owner dying while we unlock.
763d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        Thread* owner =
764d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers            Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
765eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier        FailedUnlock(h_obj.Get(), self, owner, nullptr);
766d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        return false;  // Failure.
7675f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      } else {
768d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        // We own the lock, decrease the recursion count.
769d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        if (lock_word.ThinLockCount() != 0) {
770d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          uint32_t new_count = lock_word.ThinLockCount() - 1;
771d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count));
772eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier          h_obj->SetLockWord(thin_locked, true);
773d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        } else {
774eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier          h_obj->SetLockWord(LockWord(), true);
775d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        }
776d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        return true;  // Success!
7775f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      }
7785f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    }
779d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kFatLocked: {
780d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      Monitor* mon = lock_word.FatLockMonitor();
781d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return mon->Unlock(self);
7825f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    }
783590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    default: {
784590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
785d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return false;
786590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    }
7875f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
7885f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
7895f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
7902dd0e2cea360bc9206eb88ecc40d259e796c239dIan Rogersvoid Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
7914cd121ef0cb35fced70c7d9de378277be7a727d9Elliott Hughes                   bool interruptShouldThrow, ThreadState why) {
7924d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  DCHECK(self != nullptr);
7934d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  DCHECK(obj != nullptr);
7944d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  LockWord lock_word = obj->GetLockWord(true);
79543c69cc4cea794cd4d89d9d0680b1e25c6d02accIan Rogers  while (lock_word.GetState() != LockWord::kFatLocked) {
79643c69cc4cea794cd4d89d9d0680b1e25c6d02accIan Rogers    switch (lock_word.GetState()) {
79743c69cc4cea794cd4d89d9d0680b1e25c6d02accIan Rogers      case LockWord::kHashCode:
79843c69cc4cea794cd4d89d9d0680b1e25c6d02accIan Rogers        // Fall-through.
79943c69cc4cea794cd4d89d9d0680b1e25c6d02accIan Rogers      case LockWord::kUnlocked:
800d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
801d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        return;  // Failure.
80243c69cc4cea794cd4d89d9d0680b1e25c6d02accIan Rogers      case LockWord::kThinLocked: {
80343c69cc4cea794cd4d89d9d0680b1e25c6d02accIan Rogers        uint32_t thread_id = self->GetThreadId();
80443c69cc4cea794cd4d89d9d0680b1e25c6d02accIan Rogers        uint32_t owner_thread_id = lock_word.ThinLockOwner();
80543c69cc4cea794cd4d89d9d0680b1e25c6d02accIan Rogers        if (owner_thread_id != thread_id) {
80643c69cc4cea794cd4d89d9d0680b1e25c6d02accIan Rogers          ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
80743c69cc4cea794cd4d89d9d0680b1e25c6d02accIan Rogers          return;  // Failure.
80843c69cc4cea794cd4d89d9d0680b1e25c6d02accIan Rogers        } else {
80943c69cc4cea794cd4d89d9d0680b1e25c6d02accIan Rogers          // We own the lock, inflate to enqueue ourself on the Monitor. May fail spuriously so
81043c69cc4cea794cd4d89d9d0680b1e25c6d02accIan Rogers          // re-load.
81143c69cc4cea794cd4d89d9d0680b1e25c6d02accIan Rogers          Inflate(self, self, obj, 0);
81243c69cc4cea794cd4d89d9d0680b1e25c6d02accIan Rogers          lock_word = obj->GetLockWord(true);
81343c69cc4cea794cd4d89d9d0680b1e25c6d02accIan Rogers        }
81443c69cc4cea794cd4d89d9d0680b1e25c6d02accIan Rogers        break;
81543c69cc4cea794cd4d89d9d0680b1e25c6d02accIan Rogers      }
81643c69cc4cea794cd4d89d9d0680b1e25c6d02accIan Rogers      case LockWord::kFatLocked:  // Unreachable given the loop condition above. Fall-through.
81743c69cc4cea794cd4d89d9d0680b1e25c6d02accIan Rogers      default: {
81843c69cc4cea794cd4d89d9d0680b1e25c6d02accIan Rogers        LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
81943c69cc4cea794cd4d89d9d0680b1e25c6d02accIan Rogers        return;
820d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      }
821590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    }
8225f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
823d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  Monitor* mon = lock_word.FatLockMonitor();
824d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  mon->Wait(self, ms, ns, interruptShouldThrow, why);
8255f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
8265f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
82713c479e7e9b62115fe0409e5273c1e976a1c09f9Ian Rogersvoid Monitor::DoNotify(Thread* self, mirror::Object* obj, bool notify_all) {
8284d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  DCHECK(self != nullptr);
8294d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  DCHECK(obj != nullptr);
8304d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  LockWord lock_word = obj->GetLockWord(true);
831d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  switch (lock_word.GetState()) {
832ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    case LockWord::kHashCode:
833ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier      // Fall-through.
834d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kUnlocked:
8356d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers      ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
836d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return;  // Failure.
837d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kThinLocked: {
838d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      uint32_t thread_id = self->GetThreadId();
839d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      uint32_t owner_thread_id = lock_word.ThinLockOwner();
840d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      if (owner_thread_id != thread_id) {
841d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
842d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        return;  // Failure.
843d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      } else {
844d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        // We own the lock but there's no Monitor and therefore no waiters.
845d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        return;  // Success.
846d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      }
847d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    }
848d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kFatLocked: {
849d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      Monitor* mon = lock_word.FatLockMonitor();
850d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      if (notify_all) {
851d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        mon->NotifyAll(self);
852d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      } else {
853d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        mon->Notify(self);
854d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      }
855d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return;  // Success.
8565f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    }
857590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    default: {
858590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
859590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      return;
860590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    }
8615f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
8625f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
8635f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
864d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogersuint32_t Monitor::GetLockOwnerThreadId(mirror::Object* obj) {
8654d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  DCHECK(obj != nullptr);
8664d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  LockWord lock_word = obj->GetLockWord(true);
867d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  switch (lock_word.GetState()) {
868ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    case LockWord::kHashCode:
869ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier      // Fall-through.
870d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kUnlocked:
871d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return ThreadList::kInvalidThreadId;
872d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kThinLocked:
873d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return lock_word.ThinLockOwner();
874d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kFatLocked: {
875d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      Monitor* mon = lock_word.FatLockMonitor();
876d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return mon->GetOwnerThreadId();
8775f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    }
878590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    default: {
879d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      LOG(FATAL) << "Unreachable";
8802c4257be8191c5eefde744e8965fcefc80a0a97dIan Rogers      UNREACHABLE();
881590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    }
8825f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
8835f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
8845f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
8858e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughesvoid Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
886d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers  // Determine the wait message and object we're waiting or blocked upon.
887d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers  mirror::Object* pretty_object = nullptr;
888d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers  const char* wait_message = nullptr;
889d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  uint32_t lock_owner = ThreadList::kInvalidThreadId;
890d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers  ThreadState state = thread->GetState();
891b4e94fd380a84c755264e8668a16052442c7ec32Elliott Hughes  if (state == kWaiting || state == kTimedWaiting || state == kSleeping) {
892d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    wait_message = (state == kSleeping) ? "  - sleeping on " : "  - waiting on ";
893d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    Thread* self = Thread::Current();
894d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    MutexLock mu(self, *thread->GetWaitMutex());
895d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    Monitor* monitor = thread->GetWaitMonitor();
896d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    if (monitor != nullptr) {
8974cba0d979a11f955e6ec3c0f1bf61478af7aa810Hiroshi Yamauchi      pretty_object = monitor->GetObject();
8988e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes    }
89934e069606d6f1698cd3c33b39e72b79ae27e1c7bElliott Hughes  } else if (state == kBlocked) {
900d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    wait_message = "  - waiting to lock ";
901d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    pretty_object = thread->GetMonitorEnterObject();
902d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    if (pretty_object != nullptr) {
903d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers      lock_owner = pretty_object->GetLockOwnerThreadId();
9048e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes    }
9058e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  }
9068e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
907d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers  if (wait_message != nullptr) {
908d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    if (pretty_object == nullptr) {
909d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers      os << wait_message << "an unknown object";
910d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    } else {
9114d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier      if ((pretty_object->GetLockWord(true).GetState() == LockWord::kThinLocked) &&
912d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers          Locks::mutator_lock_->IsExclusiveHeld(Thread::Current())) {
913d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers        // Getting the identity hashcode here would result in lock inflation and suspension of the
914d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers        // current thread, which isn't safe if this is the only runnable thread.
915d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers        os << wait_message << StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)",
916d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers                                           reinterpret_cast<intptr_t>(pretty_object),
917d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers                                           PrettyTypeOf(pretty_object).c_str());
918d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers      } else {
919d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers        // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
920d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers        os << wait_message << StringPrintf("<0x%08x> (a %s)", pretty_object->IdentityHashCode(),
921d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers                                           PrettyTypeOf(pretty_object).c_str());
922d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers      }
923d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    }
924d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    // - waiting to lock <0x613f83d8> (a java.lang.Object) held by thread 5
925d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    if (lock_owner != ThreadList::kInvalidThreadId) {
926d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers      os << " held by thread " << lock_owner;
927d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    }
928d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    os << "\n";
9298e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  }
9308e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes}
9318e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
9322dd0e2cea360bc9206eb88ecc40d259e796c239dIan Rogersmirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
933f9501700f51586cb6ba7cc0ffcb5a920bd64adf1Elliott Hughes  // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
934f9501700f51586cb6ba7cc0ffcb5a920bd64adf1Elliott Hughes  // definition of contended that includes a monitor a thread is trying to enter...
935dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers  mirror::Object* result = thread->GetMonitorEnterObject();
936d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  if (result == NULL) {
937d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    // ...but also a monitor that the thread is waiting on.
938dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    MutexLock mu(Thread::Current(), *thread->GetWaitMutex());
939dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    Monitor* monitor = thread->GetWaitMonitor();
940f9501700f51586cb6ba7cc0ffcb5a920bd64adf1Elliott Hughes    if (monitor != NULL) {
941d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      result = monitor->GetObject();
942f9501700f51586cb6ba7cc0ffcb5a920bd64adf1Elliott Hughes    }
943f9501700f51586cb6ba7cc0ffcb5a920bd64adf1Elliott Hughes  }
944d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  return result;
945f9501700f51586cb6ba7cc0ffcb5a920bd64adf1Elliott Hughes}
946f9501700f51586cb6ba7cc0ffcb5a920bd64adf1Elliott Hughes
9472dd0e2cea360bc9206eb88ecc40d259e796c239dIan Rogersvoid Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
948956a5228276693a7317ae6b41bfe7a7f0f3cbe6bAndreas Gampe                         void* callback_context, bool abort_on_failure) {
949ea46f950e7a51585db293cd7f047de190a482414Brian Carlstrom  mirror::ArtMethod* m = stack_visitor->GetMethod();
95008fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  CHECK(m != NULL);
95108fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes
95208fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  // Native methods are an easy special case.
95308fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
95408fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  if (m->IsNative()) {
95508fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes    if (m->IsSynchronized()) {
956eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier      mirror::Object* jni_this = stack_visitor->GetCurrentHandleScope()->GetReference(0);
9574993bbc8eda377804e585efd918f8ab9d9eab7d4Elliott Hughes      callback(jni_this, callback_context);
95808fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes    }
95908fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes    return;
96008fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  }
96108fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes
96261f916cc4757610ce308bfdea9a00cf29afd2b02jeffhao  // Proxy methods should not be synchronized.
96361f916cc4757610ce308bfdea9a00cf29afd2b02jeffhao  if (m->IsProxyMethod()) {
96461f916cc4757610ce308bfdea9a00cf29afd2b02jeffhao    CHECK(!m->IsSynchronized());
96561f916cc4757610ce308bfdea9a00cf29afd2b02jeffhao    return;
96661f916cc4757610ce308bfdea9a00cf29afd2b02jeffhao  }
96761f916cc4757610ce308bfdea9a00cf29afd2b02jeffhao
96808fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  // Is there any reason to believe there's any synchronization in this method?
969bfd9a4378eacaf2dc2bbe05ad48c5164fc93c9feMathieu Chartier  const DexFile::CodeItem* code_item = m->GetCodeItem();
970caf7654a0e6c76c7489970b1a246fccf220f9982Elliott Hughes  CHECK(code_item != NULL) << PrettyMethod(m);
97108fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  if (code_item->tries_size_ == 0) {
9727934ac288acfb2552bb0b06ec1f61e5820d924a4Brian Carlstrom    return;  // No "tries" implies no synchronization, so no held locks to report.
97308fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  }
97408fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes
975956a5228276693a7317ae6b41bfe7a7f0f3cbe6bAndreas Gampe  // Get the dex pc. If abort_on_failure is false, GetDexPc will not abort in the case it cannot
976956a5228276693a7317ae6b41bfe7a7f0f3cbe6bAndreas Gampe  // find the dex pc, and instead return kDexNoIndex. Then bail out, as it indicates we have an
977956a5228276693a7317ae6b41bfe7a7f0f3cbe6bAndreas Gampe  // inconsistent stack anyways.
978956a5228276693a7317ae6b41bfe7a7f0f3cbe6bAndreas Gampe  uint32_t dex_pc = stack_visitor->GetDexPc(abort_on_failure);
979956a5228276693a7317ae6b41bfe7a7f0f3cbe6bAndreas Gampe  if (!abort_on_failure && dex_pc == DexFile::kDexNoIndex) {
980956a5228276693a7317ae6b41bfe7a7f0f3cbe6bAndreas Gampe    LOG(ERROR) << "Could not find dex_pc for " << PrettyMethod(m);
981956a5228276693a7317ae6b41bfe7a7f0f3cbe6bAndreas Gampe    return;
982956a5228276693a7317ae6b41bfe7a7f0f3cbe6bAndreas Gampe  }
983956a5228276693a7317ae6b41bfe7a7f0f3cbe6bAndreas Gampe
98480537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes  // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
98580537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes  // the locks held in this stack frame.
98680537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes  std::vector<uint32_t> monitor_enter_dex_pcs;
987956a5228276693a7317ae6b41bfe7a7f0f3cbe6bAndreas Gampe  verifier::MethodVerifier::FindLocksAtDexPc(m, dex_pc, &monitor_enter_dex_pcs);
98880537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes  if (monitor_enter_dex_pcs.empty()) {
98980537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes    return;
99080537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes  }
99108fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes
99280537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes  for (size_t i = 0; i < monitor_enter_dex_pcs.size(); ++i) {
99380537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes    // The verifier works in terms of the dex pcs of the monitor-enter instructions.
99480537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes    // We want the registers used by those instructions (so we can read the values out of them).
995277ccbd200ea43590dfc06a93ae184a765327ad0Andreas Gampe    uint32_t monitor_dex_pc = monitor_enter_dex_pcs[i];
996277ccbd200ea43590dfc06a93ae184a765327ad0Andreas Gampe    uint16_t monitor_enter_instruction = code_item->insns_[monitor_dex_pc];
99708fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes
99880537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes    // Quick sanity check.
99980537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes    if ((monitor_enter_instruction & 0xff) != Instruction::MONITOR_ENTER) {
1000277ccbd200ea43590dfc06a93ae184a765327ad0Andreas Gampe      LOG(FATAL) << "expected monitor-enter @" << monitor_dex_pc << "; was "
100180537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes                 << reinterpret_cast<void*>(monitor_enter_instruction);
100208fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes    }
100380537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes
100480537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes    uint16_t monitor_register = ((monitor_enter_instruction >> 8) & 0xff);
10052dd0e2cea360bc9206eb88ecc40d259e796c239dIan Rogers    mirror::Object* o = reinterpret_cast<mirror::Object*>(stack_visitor->GetVReg(m, monitor_register,
10062dd0e2cea360bc9206eb88ecc40d259e796c239dIan Rogers                                                                                 kReferenceVReg));
10074993bbc8eda377804e585efd918f8ab9d9eab7d4Elliott Hughes    callback(o, callback_context);
100808fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  }
100908fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes}
101008fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes
1011d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogersbool Monitor::IsValidLockWord(LockWord lock_word) {
1012d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  switch (lock_word.GetState()) {
1013d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kUnlocked:
1014d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      // Nothing to check.
1015d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return true;
1016d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kThinLocked:
1017d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      // Basic sanity check of owner.
1018d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
1019d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kFatLocked: {
1020d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      // Check the  monitor appears in the monitor list.
1021d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      Monitor* mon = lock_word.FatLockMonitor();
1022d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      MonitorList* list = Runtime::Current()->GetMonitorList();
1023d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      MutexLock mu(Thread::Current(), list->monitor_list_lock_);
1024d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      for (Monitor* list_mon : list->list_) {
1025d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        if (mon == list_mon) {
1026d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          return true;  // Found our monitor.
1027d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        }
10287dfb28c066159e6cde8181720f0c451a700ef966Ian Rogers      }
1029d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return false;  // Fail - unowned monitor in an object.
10307dfb28c066159e6cde8181720f0c451a700ef966Ian Rogers    }
1031ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    case LockWord::kHashCode:
1032ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier      return true;
1033d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    default:
1034d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      LOG(FATAL) << "Unreachable";
10352c4257be8191c5eefde744e8965fcefc80a0a97dIan Rogers      UNREACHABLE();
10367dfb28c066159e6cde8181720f0c451a700ef966Ian Rogers  }
10377dfb28c066159e6cde8181720f0c451a700ef966Ian Rogers}
10387dfb28c066159e6cde8181720f0c451a700ef966Ian Rogers
1039ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartierbool Monitor::IsLocked() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1040ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier  MutexLock mu(Thread::Current(), monitor_lock_);
1041ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier  return owner_ != nullptr;
1042ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier}
1043ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier
1044ef7d42fca18c16fbaf103822ad16f23246e2905dIan Rogersvoid Monitor::TranslateLocation(mirror::ArtMethod* method, uint32_t dex_pc,
1045d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers                                const char** source_file, uint32_t* line_number) const {
104633dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao  // If method is null, location is unknown
104733dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao  if (method == NULL) {
1048d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    *source_file = "";
1049d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    *line_number = 0;
105033dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao    return;
105133dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao  }
1052bfd9a4378eacaf2dc2bbe05ad48c5164fc93c9feMathieu Chartier  *source_file = method->GetDeclaringClassSourceFile();
1053d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  if (*source_file == NULL) {
1054d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    *source_file = "";
1055d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  }
1056bfd9a4378eacaf2dc2bbe05ad48c5164fc93c9feMathieu Chartier  *line_number = method->GetLineNumFromDexPC(dex_pc);
1057d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers}
1058d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers
1059d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogersuint32_t Monitor::GetOwnerThreadId() {
1060d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  MutexLock mu(Thread::Current(), monitor_lock_);
1061d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  Thread* owner = owner_;
1062d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  if (owner != NULL) {
1063d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    return owner->GetThreadId();
1064d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  } else {
1065d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    return ThreadList::kInvalidThreadId;
106612c51e3e5a8b5655351539618f1cf2331f52d1abElliott Hughes  }
106733dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao}
106833dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao
1069c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu ChartierMonitorList::MonitorList()
1070440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier    : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock", kMonitorListLock),
1071c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier      monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
1072c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes}
1073c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes
1074c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott HughesMonitorList::~MonitorList() {
107574240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe  Thread* self = Thread::Current();
107674240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe  MutexLock mu(self, monitor_list_lock_);
107774240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe  // Release all monitors to the pool.
107874240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe  // TODO: Is it an invariant that *all* open monitors are in the list? Then we could
107974240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe  // clear faster in the pool.
108074240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe  MonitorPool::ReleaseMonitors(self, &list_);
1081c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes}
1082c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes
1083c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartiervoid MonitorList::DisallowNewMonitors() {
108450b35e2fd1a68cd1240e4a9d9f363e11764957d1Ian Rogers  MutexLock mu(Thread::Current(), monitor_list_lock_);
1085c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier  allow_new_monitors_ = false;
1086c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier}
1087c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier
1088c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartiervoid MonitorList::AllowNewMonitors() {
1089c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier  Thread* self = Thread::Current();
1090c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier  MutexLock mu(self, monitor_list_lock_);
1091c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier  allow_new_monitors_ = true;
1092c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier  monitor_add_condition_.Broadcast(self);
1093c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier}
1094c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier
1095c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartiervoid MonitorList::Add(Monitor* m) {
1096c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier  Thread* self = Thread::Current();
1097c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier  MutexLock mu(self, monitor_list_lock_);
1098c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier  while (UNLIKELY(!allow_new_monitors_)) {
1099c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier    monitor_add_condition_.WaitHoldingLocks(self);
1100c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier  }
1101c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes  list_.push_front(m);
1102c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes}
1103c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes
110483c8ee000d525017ead8753fce6bc1020249b96aMathieu Chartiervoid MonitorList::SweepMonitorList(IsMarkedCallback* callback, void* arg) {
110574240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe  Thread* self = Thread::Current();
110674240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe  MutexLock mu(self, monitor_list_lock_);
110702e25119b15a6f619f17db99f5d05124a5807ff3Mathieu Chartier  for (auto it = list_.begin(); it != list_.end(); ) {
1108c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes    Monitor* m = *it;
11094cba0d979a11f955e6ec3c0f1bf61478af7aa810Hiroshi Yamauchi    // Disable the read barrier in GetObject() as this is called by GC.
11104cba0d979a11f955e6ec3c0f1bf61478af7aa810Hiroshi Yamauchi    mirror::Object* obj = m->GetObject<kWithoutReadBarrier>();
1111590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    // The object of a monitor can be null if we have deflated it.
111283c8ee000d525017ead8753fce6bc1020249b96aMathieu Chartier    mirror::Object* new_obj = obj != nullptr ? callback(obj, arg) : nullptr;
11136aa3df965395566ed6a4fec4af37c2b7577992e9Mathieu Chartier    if (new_obj == nullptr) {
11146aa3df965395566ed6a4fec4af37c2b7577992e9Mathieu Chartier      VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
11154cba0d979a11f955e6ec3c0f1bf61478af7aa810Hiroshi Yamauchi                    << obj;
111674240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe      MonitorPool::ReleaseMonitor(self, m);
1117c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes      it = list_.erase(it);
1118c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes    } else {
11196aa3df965395566ed6a4fec4af37c2b7577992e9Mathieu Chartier      m->SetObject(new_obj);
1120c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes      ++it;
1121c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes    }
1122c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes  }
1123c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes}
1124c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes
112548ab687d1f864fec93c2682de6fdc44ab784e2f8Mathieu Chartierstruct MonitorDeflateArgs {
112648ab687d1f864fec93c2682de6fdc44ab784e2f8Mathieu Chartier  MonitorDeflateArgs() : self(Thread::Current()), deflate_count(0) {}
112748ab687d1f864fec93c2682de6fdc44ab784e2f8Mathieu Chartier  Thread* const self;
112848ab687d1f864fec93c2682de6fdc44ab784e2f8Mathieu Chartier  size_t deflate_count;
112948ab687d1f864fec93c2682de6fdc44ab784e2f8Mathieu Chartier};
113048ab687d1f864fec93c2682de6fdc44ab784e2f8Mathieu Chartier
1131440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartierstatic mirror::Object* MonitorDeflateCallback(mirror::Object* object, void* arg)
1132440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
113348ab687d1f864fec93c2682de6fdc44ab784e2f8Mathieu Chartier  MonitorDeflateArgs* args = reinterpret_cast<MonitorDeflateArgs*>(arg);
113448ab687d1f864fec93c2682de6fdc44ab784e2f8Mathieu Chartier  if (Monitor::Deflate(args->self, object)) {
11354d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier    DCHECK_NE(object->GetLockWord(true).GetState(), LockWord::kFatLocked);
113648ab687d1f864fec93c2682de6fdc44ab784e2f8Mathieu Chartier    ++args->deflate_count;
1137440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier    // If we deflated, return nullptr so that the monitor gets removed from the array.
1138440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier    return nullptr;
1139440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier  }
1140440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier  return object;  // Monitor was not deflated.
1141440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier}
1142440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier
114348ab687d1f864fec93c2682de6fdc44ab784e2f8Mathieu Chartiersize_t MonitorList::DeflateMonitors() {
114448ab687d1f864fec93c2682de6fdc44ab784e2f8Mathieu Chartier  MonitorDeflateArgs args;
114548ab687d1f864fec93c2682de6fdc44ab784e2f8Mathieu Chartier  Locks::mutator_lock_->AssertExclusiveHeld(args.self);
114648ab687d1f864fec93c2682de6fdc44ab784e2f8Mathieu Chartier  SweepMonitorList(MonitorDeflateCallback, &args);
114748ab687d1f864fec93c2682de6fdc44ab784e2f8Mathieu Chartier  return args.deflate_count;
1148440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier}
1149440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier
1150d9c4fc94fa618617f94e1de9af5f034549100753Ian RogersMonitorInfo::MonitorInfo(mirror::Object* obj) : owner_(NULL), entry_count_(0) {
11514d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  DCHECK(obj != nullptr);
11524d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  LockWord lock_word = obj->GetLockWord(true);
1153d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  switch (lock_word.GetState()) {
1154d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kUnlocked:
1155ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier      // Fall-through.
1156590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    case LockWord::kForwardingAddress:
1157590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      // Fall-through.
1158ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    case LockWord::kHashCode:
1159d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      break;
1160d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kThinLocked:
1161d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
1162d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      entry_count_ = 1 + lock_word.ThinLockCount();
1163d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      // Thin locks have no waiters.
1164d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      break;
1165d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kFatLocked: {
1166d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      Monitor* mon = lock_word.FatLockMonitor();
1167d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      owner_ = mon->owner_;
1168d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      entry_count_ = 1 + mon->lock_count_;
1169dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers      for (Thread* waiter = mon->wait_set_; waiter != NULL; waiter = waiter->GetWaitNext()) {
1170d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        waiters_.push_back(waiter);
1171d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      }
1172d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      break;
1173f327e07b37e349b1ec5eaad6dc294a9b7a081d20Elliott Hughes    }
1174f327e07b37e349b1ec5eaad6dc294a9b7a081d20Elliott Hughes  }
1175f327e07b37e349b1ec5eaad6dc294a9b7a081d20Elliott Hughes}
1176f327e07b37e349b1ec5eaad6dc294a9b7a081d20Elliott Hughes
11775f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}  // namespace art
1178