monitor.cc revision 760172c3ccd6e75f6f1a89d8006934e8ffb1303e
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 Hughes/*
1805f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * Links a thread into a monitor's wait set.  The monitor lock must be
1815f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * held by the caller of this routine.
1825f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes */
1835f79133a435ebcb20000370d56046fe01201dd80Elliott Hughesvoid Monitor::AppendToWaitSet(Thread* thread) {
1845f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  DCHECK(owner_ == Thread::Current());
1855f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  DCHECK(thread != NULL);
186dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers  DCHECK(thread->GetWaitNext() == nullptr) << thread->GetWaitNext();
1875f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  if (wait_set_ == NULL) {
1885f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    wait_set_ = thread;
1895f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    return;
1905f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
1915f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
1925f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  // push_back.
1935f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  Thread* t = wait_set_;
194dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers  while (t->GetWaitNext() != nullptr) {
195dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    t = t->GetWaitNext();
1965f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
197dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers  t->SetWaitNext(thread);
1985f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
1995f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
2005f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes/*
2015f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * Unlinks a thread from a monitor's wait set.  The monitor lock must
2025f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * be held by the caller of this routine.
2035f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes */
2045f79133a435ebcb20000370d56046fe01201dd80Elliott Hughesvoid Monitor::RemoveFromWaitSet(Thread *thread) {
2055f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  DCHECK(owner_ == Thread::Current());
2065f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  DCHECK(thread != NULL);
2075f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  if (wait_set_ == NULL) {
2085f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    return;
2095f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
2105f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  if (wait_set_ == thread) {
211dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    wait_set_ = thread->GetWaitNext();
212dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    thread->SetWaitNext(nullptr);
2135f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    return;
2145f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
2155f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
2165f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  Thread* t = wait_set_;
217dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers  while (t->GetWaitNext() != NULL) {
218dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    if (t->GetWaitNext() == thread) {
219dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers      t->SetWaitNext(thread->GetWaitNext());
220dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers      thread->SetWaitNext(nullptr);
2215f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      return;
2225f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    }
223dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    t = t->GetWaitNext();
2245f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
2255f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
2265f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
2276aa3df965395566ed6a4fec4af37c2b7577992e9Mathieu Chartiervoid Monitor::SetObject(mirror::Object* object) {
22894f7b49578b6aaa80de8ffed230648d601393905Hiroshi Yamauchi  obj_ = GcRoot<mirror::Object>(object);
2296aa3df965395566ed6a4fec4af37c2b7577992e9Mathieu Chartier}
2306aa3df965395566ed6a4fec4af37c2b7577992e9Mathieu Chartier
2315f79133a435ebcb20000370d56046fe01201dd80Elliott Hughesvoid Monitor::Lock(Thread* self) {
232d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  MutexLock mu(self, monitor_lock_);
233d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  while (true) {
234440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier    if (owner_ == nullptr) {  // Unowned.
235d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      owner_ = self;
236d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      CHECK_EQ(lock_count_, 0);
237d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      // When debugging, save the current monitor holder for future
238d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      // acquisition failures to use in sampled logging.
239d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      if (lock_profiling_threshold_ != 0) {
240d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
241fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes      }
242d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return;
243d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    } else if (owner_ == self) {  // Recursive.
244d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      lock_count_++;
245d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return;
246fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes    }
247d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    // Contended.
248d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    const bool log_contention = (lock_profiling_threshold_ != 0);
249d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    uint64_t wait_start_ms = log_contention ? 0 : MilliTime();
250ef7d42fca18c16fbaf103822ad16f23246e2905dIan Rogers    mirror::ArtMethod* owners_method = locking_method_;
251d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    uint32_t owners_dex_pc = locking_dex_pc_;
252440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier    // Do this before releasing the lock so that we don't get deflated.
253440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier    ++num_waiters_;
254d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    monitor_lock_.Unlock(self);  // Let go of locks in order.
255a6e7f0872c42009ecbee82d7fbe452deef9ae65bMathieu Chartier    self->SetMonitorEnterObject(GetObject());
256d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    {
257d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      ScopedThreadStateChange tsc(self, kBlocked);  // Change to blocked and give up mutator_lock_.
258d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      MutexLock mu2(self, monitor_lock_);  // Reacquire monitor_lock_ without mutator_lock_ for Wait.
259d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      if (owner_ != NULL) {  // Did the owner_ give the lock up?
260d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        monitor_contenders_.Wait(self);  // Still contended so wait.
261d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        // Woken from contention.
262d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        if (log_contention) {
263d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          uint64_t wait_ms = MilliTime() - wait_start_ms;
264d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          uint32_t sample_percent;
265d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          if (wait_ms >= lock_profiling_threshold_) {
266d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers            sample_percent = 100;
267d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          } else {
268d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers            sample_percent = 100 * wait_ms / lock_profiling_threshold_;
269d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          }
270d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
271d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers            const char* owners_filename;
272d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers            uint32_t owners_line_number;
273d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers            TranslateLocation(owners_method, owners_dex_pc, &owners_filename, &owners_line_number);
274d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers            LogContentionEvent(self, wait_ms, sample_percent, owners_filename, owners_line_number);
275d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          }
276d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        }
277fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes      }
2785f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    }
279a6e7f0872c42009ecbee82d7fbe452deef9ae65bMathieu Chartier    self->SetMonitorEnterObject(nullptr);
280d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    monitor_lock_.Lock(self);  // Reacquire locks in order.
281440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier    --num_waiters_;
282fc86162ce2a3467acb690e18cc8bd9b3daafc606Elliott Hughes  }
2835f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
2845f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
2856d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogersstatic void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
2866d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers                                              __attribute__((format(printf, 1, 2)));
2876d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers
28800f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogersstatic void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
289b726dcb581bf72da46527378ccb6889020f0e6e9Ian Rogers    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2906d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers  va_list args;
2916d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers  va_start(args, fmt);
29262d6c772205b8859f0ebf7ad105402ec4c3e2e01Ian Rogers  Thread* self = Thread::Current();
29362d6c772205b8859f0ebf7ad105402ec4c3e2e01Ian Rogers  ThrowLocation throw_location = self->GetCurrentLocationForThrow();
29462d6c772205b8859f0ebf7ad105402ec4c3e2e01Ian Rogers  self->ThrowNewExceptionV(throw_location, "Ljava/lang/IllegalMonitorStateException;", fmt, args);
295d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  if (!Runtime::Current()->IsStarted() || VLOG_IS_ON(monitor)) {
29664277f38032208a0c1081ff9e466c04009b96383Brian Carlstrom    std::ostringstream ss;
29762d6c772205b8859f0ebf7ad105402ec4c3e2e01Ian Rogers    self->Dump(ss);
298d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    LOG(Runtime::Current()->IsStarted() ? INFO : ERROR)
299d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        << self->GetException(NULL)->Dump() << "\n" << ss.str();
30064277f38032208a0c1081ff9e466c04009b96383Brian Carlstrom  }
3016d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers  va_end(args);
3026d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers}
3036d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers
304d423741f91526cada9d081c64ee295ec9863032dElliott Hughesstatic std::string ThreadToString(Thread* thread) {
305d423741f91526cada9d081c64ee295ec9863032dElliott Hughes  if (thread == NULL) {
306d423741f91526cada9d081c64ee295ec9863032dElliott Hughes    return "NULL";
307d423741f91526cada9d081c64ee295ec9863032dElliott Hughes  }
308d423741f91526cada9d081c64ee295ec9863032dElliott Hughes  std::ostringstream oss;
309d423741f91526cada9d081c64ee295ec9863032dElliott Hughes  // TODO: alternatively, we could just return the thread's name.
310d423741f91526cada9d081c64ee295ec9863032dElliott Hughes  oss << *thread;
311d423741f91526cada9d081c64ee295ec9863032dElliott Hughes  return oss.str();
312d423741f91526cada9d081c64ee295ec9863032dElliott Hughes}
313d423741f91526cada9d081c64ee295ec9863032dElliott Hughes
3142dd0e2cea360bc9206eb88ecc40d259e796c239dIan Rogersvoid Monitor::FailedUnlock(mirror::Object* o, Thread* expected_owner, Thread* found_owner,
315ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                           Monitor* monitor) {
316ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  Thread* current_owner = NULL;
317ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  std::string current_owner_string;
318ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  std::string expected_owner_string;
319ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  std::string found_owner_string;
320ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  {
321ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes    // TODO: isn't this too late to prevent threads from disappearing?
322ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes    // Acquire thread list lock so threads won't disappear from under us.
32350b35e2fd1a68cd1240e4a9d9f363e11764957d1Ian Rogers    MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
324ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes    // Re-read owner now that we hold lock.
325d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    current_owner = (monitor != NULL) ? monitor->GetOwner() : NULL;
326ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes    // Get short descriptions of the threads involved.
327ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes    current_owner_string = ThreadToString(current_owner);
328ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes    expected_owner_string = ThreadToString(expected_owner);
329ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes    found_owner_string = ThreadToString(found_owner);
330ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes  }
3316d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers  if (current_owner == NULL) {
3326d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers    if (found_owner == NULL) {
3336d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers      ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
3346d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers                                         " on thread '%s'",
335ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                         PrettyTypeOf(o).c_str(),
336ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                         expected_owner_string.c_str());
3376d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers    } else {
3386d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers      // Race: the original read found an owner but now there is none
3396d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers      ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
3406d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers                                         " (where now the monitor appears unowned) on thread '%s'",
341ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                         found_owner_string.c_str(),
342ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                         PrettyTypeOf(o).c_str(),
343ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                         expected_owner_string.c_str());
3446d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers    }
3456d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers  } else {
3466d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers    if (found_owner == NULL) {
3476d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers      // Race: originally there was no owner, there is now
3486d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers      ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
3496d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers                                         " (originally believed to be unowned) on thread '%s'",
350ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                         current_owner_string.c_str(),
351ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                         PrettyTypeOf(o).c_str(),
352ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                         expected_owner_string.c_str());
3536d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers    } else {
3546d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers      if (found_owner != current_owner) {
3556d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers        // Race: originally found and current owner have changed
3566d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers        ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
3576d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers                                           " owned by '%s') on object of type '%s' on thread '%s'",
358ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                           found_owner_string.c_str(),
359ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                           current_owner_string.c_str(),
360ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                           PrettyTypeOf(o).c_str(),
361ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                           expected_owner_string.c_str());
3626d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers      } else {
3636d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers        ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
3646d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers                                           " on thread '%s",
365ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                           current_owner_string.c_str(),
366ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                           PrettyTypeOf(o).c_str(),
367ffb465f23d9549dd591e6aa62e9250523cb00233Elliott Hughes                                           expected_owner_string.c_str());
3686d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers      }
3696d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers    }
3706d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers  }
3715f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
3725f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
373d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogersbool Monitor::Unlock(Thread* self) {
3745f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  DCHECK(self != NULL);
375d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  MutexLock mu(self, monitor_lock_);
3766d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers  Thread* owner = owner_;
3776d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers  if (owner == self) {
3785f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    // We own the monitor, so nobody else can be in here.
3795f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    if (lock_count_ == 0) {
3805f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      owner_ = NULL;
38133dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao      locking_method_ = NULL;
3820399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers      locking_dex_pc_ = 0;
383d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      // Wake a contender.
384d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      monitor_contenders_.Signal(self);
3855f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    } else {
3865f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      --lock_count_;
3875f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    }
3885f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  } else {
3895f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    // We don't own this, so we're not allowed to unlock it.
3905f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    // The JNI spec says that we should throw IllegalMonitorStateException
3915f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    // in this case.
3924cba0d979a11f955e6ec3c0f1bf61478af7aa810Hiroshi Yamauchi    FailedUnlock(GetObject(), self, owner, this);
3935f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    return false;
3945f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
3955f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  return true;
3965f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
3975f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
3985f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes/*
3995f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * Wait on a monitor until timeout, interrupt, or notification.  Used for
4005f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * Object.wait() and (somewhat indirectly) Thread.sleep() and Thread.join().
4015f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes *
4025f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * If another thread calls Thread.interrupt(), we throw InterruptedException
4035f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * and return immediately if one of the following are true:
4045f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes *  - blocked in wait(), wait(long), or wait(long, int) methods of Object
4055f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes *  - blocked in join(), join(long), or join(long, int) methods of Thread
4065f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes *  - blocked in sleep(long), or sleep(long, int) methods of Thread
4075f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * Otherwise, we set the "interrupted" flag.
4085f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes *
4095f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * Checks to make sure that "ns" is in the range 0-999999
4105f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * (i.e. fractions of a millisecond) and throws the appropriate
4115f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * exception if it isn't.
4125f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes *
4135f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * The spec allows "spurious wakeups", and recommends that all code using
4145f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * Object.wait() do so in a loop.  This appears to derive from concerns
4155f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * about pthread_cond_wait() on multiprocessor systems.  Some commentary
4165f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * on the web casts doubt on whether these can/should occur.
4175f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes *
4185f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * Since we're allowed to wake up "early", we clamp extremely long durations
4195f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * to return at the end of the 32-bit time epoch.
4205f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes */
4214cd121ef0cb35fced70c7d9de378277be7a727d9Elliott Hughesvoid Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
4224cd121ef0cb35fced70c7d9de378277be7a727d9Elliott Hughes                   bool interruptShouldThrow, ThreadState why) {
4235f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  DCHECK(self != NULL);
4244cd121ef0cb35fced70c7d9de378277be7a727d9Elliott Hughes  DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
4255f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
426d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  monitor_lock_.Lock(self);
427d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers
4285f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  // Make sure that we hold the lock.
4295f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  if (owner_ != self) {
430d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    monitor_lock_.Unlock(self);
4311af6a1fa35ff7dc0a5c653f19dbc8a91c914aa42Elena Sayapina    ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
4325f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    return;
4335f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
4344cd121ef0cb35fced70c7d9de378277be7a727d9Elliott Hughes
435df42c4815c30b9df15aacb88070c1e94f41d0226Elliott Hughes  // We need to turn a zero-length timed wait into a regular wait because
436df42c4815c30b9df15aacb88070c1e94f41d0226Elliott Hughes  // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
437df42c4815c30b9df15aacb88070c1e94f41d0226Elliott Hughes  if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
438df42c4815c30b9df15aacb88070c1e94f41d0226Elliott Hughes    why = kWaiting;
439df42c4815c30b9df15aacb88070c1e94f41d0226Elliott Hughes  }
440df42c4815c30b9df15aacb88070c1e94f41d0226Elliott Hughes
4415f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  // Enforce the timeout range.
4425f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  if (ms < 0 || ns < 0 || ns > 999999) {
4431af6a1fa35ff7dc0a5c653f19dbc8a91c914aa42Elena Sayapina    monitor_lock_.Unlock(self);
44462d6c772205b8859f0ebf7ad105402ec4c3e2e01Ian Rogers    ThrowLocation throw_location = self->GetCurrentLocationForThrow();
44562d6c772205b8859f0ebf7ad105402ec4c3e2e01Ian Rogers    self->ThrowNewExceptionF(throw_location, "Ljava/lang/IllegalArgumentException;",
446ef7d42fca18c16fbaf103822ad16f23246e2905dIan Rogers                             "timeout arguments out of range: ms=%" PRId64 " ns=%d", ms, ns);
4475f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    return;
4485f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
4495f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
4505f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  /*
4515f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   * Add ourselves to the set of threads waiting on this monitor, and
4525f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   * release our hold.  We need to let it go even if we're a few levels
4535f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   * deep in a recursive lock, and we need to restore that later.
4545f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   *
4555f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   * We append to the wait set ahead of clearing the count and owner
4565f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   * fields so the subroutine can check that the calling thread owns
4575f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   * the monitor.  Aside from that, the order of member updates is
4585f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   * not order sensitive as we hold the pthread mutex.
4595f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   */
4605f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  AppendToWaitSet(self);
461440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier  ++num_waiters_;
4620399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  int prev_lock_count = lock_count_;
4635f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  lock_count_ = 0;
4645f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  owner_ = NULL;
465ef7d42fca18c16fbaf103822ad16f23246e2905dIan Rogers  mirror::ArtMethod* saved_method = locking_method_;
46633dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao  locking_method_ = NULL;
4670399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  uintptr_t saved_dex_pc = locking_dex_pc_;
4680399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  locking_dex_pc_ = 0;
4695f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
4705f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  /*
4714cd121ef0cb35fced70c7d9de378277be7a727d9Elliott Hughes   * Update thread state. If the GC wakes up, it'll ignore us, knowing
4725f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   * that we won't touch any references in this state, and we'll check
4735f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   * our suspend mode before we transition out.
4745f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   */
4754cd121ef0cb35fced70c7d9de378277be7a727d9Elliott Hughes  self->TransitionFromRunnableToSuspended(why);
4765f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
477b4e94fd380a84c755264e8668a16052442c7ec32Elliott Hughes  bool was_interrupted = false;
47800f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  {
47900f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
480dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    MutexLock mu(self, *self->GetWaitMutex());
4815f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
48200f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
48300f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    // non-NULL a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
48400f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    // up.
485dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    DCHECK(self->GetWaitMonitor() == nullptr);
486dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    self->SetWaitMonitor(this);
4875f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
48800f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    // Release the monitor lock.
489d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    monitor_contenders_.Signal(self);
490d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    monitor_lock_.Unlock(self);
49100f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers
492b4e94fd380a84c755264e8668a16052442c7ec32Elliott Hughes    // Handle the case where the thread was interrupted before we called wait().
493dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    if (self->IsInterruptedLocked()) {
494b4e94fd380a84c755264e8668a16052442c7ec32Elliott Hughes      was_interrupted = true;
49500f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    } else {
49600f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      // Wait for a notification or a timeout to occur.
4974cd121ef0cb35fced70c7d9de378277be7a727d9Elliott Hughes      if (why == kWaiting) {
498dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers        self->GetWaitConditionVariable()->Wait(self);
49900f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      } else {
5004cd121ef0cb35fced70c7d9de378277be7a727d9Elliott Hughes        DCHECK(why == kTimedWaiting || why == kSleeping) << why;
501dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers        self->GetWaitConditionVariable()->TimedWait(self, ms, ns);
50200f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      }
503dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers      if (self->IsInterruptedLocked()) {
504b4e94fd380a84c755264e8668a16052442c7ec32Elliott Hughes        was_interrupted = true;
50500f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers      }
506dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers      self->SetInterruptedLocked(false);
50700f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    }
5085f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
5095f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
51000f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  // Set self->status back to kRunnable, and self-suspend if needed.
51100f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  self->TransitionFromSuspendedToRunnable();
5125f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
513b4e94fd380a84c755264e8668a16052442c7ec32Elliott Hughes  {
514b4e94fd380a84c755264e8668a16052442c7ec32Elliott Hughes    // We reset the thread's wait_monitor_ field after transitioning back to runnable so
515b4e94fd380a84c755264e8668a16052442c7ec32Elliott Hughes    // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
516b4e94fd380a84c755264e8668a16052442c7ec32Elliott Hughes    // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
517b4e94fd380a84c755264e8668a16052442c7ec32Elliott Hughes    // are waiting on "null".)
518dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    MutexLock mu(self, *self->GetWaitMutex());
519dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    DCHECK(self->GetWaitMonitor() != nullptr);
520dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    self->SetWaitMonitor(nullptr);
521b4e94fd380a84c755264e8668a16052442c7ec32Elliott Hughes  }
522b4e94fd380a84c755264e8668a16052442c7ec32Elliott Hughes
523d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  // Re-acquire the monitor and lock.
52400f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers  Lock(self);
525d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  monitor_lock_.Lock(self);
526dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers  self->GetWaitMutex()->AssertNotHeld(self);
5275f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
5285f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  /*
5295f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   * We remove our thread from wait set after restoring the count
5305f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   * and owner fields so the subroutine can check that the calling
5315f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   * thread owns the monitor. Aside from that, the order of member
5325f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   * updates is not order sensitive as we hold the pthread mutex.
5335f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes   */
5345f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  owner_ = self;
5350399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  lock_count_ = prev_lock_count;
5360399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  locking_method_ = saved_method;
5370399dde18753aa9bd2bd0d7cf60beef154d164a4Ian Rogers  locking_dex_pc_ = saved_dex_pc;
538440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier  --num_waiters_;
5395f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  RemoveFromWaitSet(self);
5405f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
5411af6a1fa35ff7dc0a5c653f19dbc8a91c914aa42Elena Sayapina  monitor_lock_.Unlock(self);
5421af6a1fa35ff7dc0a5c653f19dbc8a91c914aa42Elena Sayapina
543b4e94fd380a84c755264e8668a16052442c7ec32Elliott Hughes  if (was_interrupted) {
5445f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    /*
5455f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes     * We were interrupted while waiting, or somebody interrupted an
5465f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes     * un-interruptible thread earlier and we're bailing out immediately.
5475f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes     *
5485f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes     * The doc sayeth: "The interrupted status of the current thread is
5495f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes     * cleared when this exception is thrown."
5505f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes     */
55100f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    {
552dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers      MutexLock mu(self, *self->GetWaitMutex());
553dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers      self->SetInterruptedLocked(false);
55400f7d0eaa6bd93d33bf0c1429bf4ba0b3f28abacIan Rogers    }
5555f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    if (interruptShouldThrow) {
55662d6c772205b8859f0ebf7ad105402ec4c3e2e01Ian Rogers      ThrowLocation throw_location = self->GetCurrentLocationForThrow();
55762d6c772205b8859f0ebf7ad105402ec4c3e2e01Ian Rogers      self->ThrowNewException(throw_location, "Ljava/lang/InterruptedException;", NULL);
5585f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    }
5595f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
5605f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
5615f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
5625f79133a435ebcb20000370d56046fe01201dd80Elliott Hughesvoid Monitor::Notify(Thread* self) {
5635f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  DCHECK(self != NULL);
564d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  MutexLock mu(self, monitor_lock_);
5655f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  // Make sure that we hold the lock.
5665f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  if (owner_ != self) {
5676d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers    ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
5685f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    return;
5695f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
5705f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  // Signal the first waiting thread in the wait set.
5715f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  while (wait_set_ != NULL) {
5725f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    Thread* thread = wait_set_;
573dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    wait_set_ = thread->GetWaitNext();
574dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    thread->SetWaitNext(nullptr);
5755f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
5765f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    // Check to see if the thread is still waiting.
577dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    MutexLock mu(self, *thread->GetWaitMutex());
578dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    if (thread->GetWaitMonitor() != nullptr) {
579dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers      thread->GetWaitConditionVariable()->Signal(self);
5805f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      return;
5815f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    }
5825f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
5835f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
5845f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
5855f79133a435ebcb20000370d56046fe01201dd80Elliott Hughesvoid Monitor::NotifyAll(Thread* self) {
5865f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  DCHECK(self != NULL);
587d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  MutexLock mu(self, monitor_lock_);
5885f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  // Make sure that we hold the lock.
5895f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  if (owner_ != self) {
5906d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers    ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
5915f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    return;
5925f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
5935f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  // Signal all threads in the wait set.
5945f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  while (wait_set_ != NULL) {
5955f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    Thread* thread = wait_set_;
596dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    wait_set_ = thread->GetWaitNext();
597dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    thread->SetWaitNext(nullptr);
5985f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    thread->Notify();
5995f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
6005f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
6015f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
602590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartierbool Monitor::Deflate(Thread* self, mirror::Object* obj) {
603590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier  DCHECK(obj != nullptr);
6044d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  // Don't need volatile since we only deflate with mutators suspended.
6054d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  LockWord lw(obj->GetLockWord(false));
606590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier  // If the lock isn't an inflated monitor, then we don't need to deflate anything.
607590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier  if (lw.GetState() == LockWord::kFatLocked) {
608590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    Monitor* monitor = lw.FatLockMonitor();
609440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier    DCHECK(monitor != nullptr);
610590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    MutexLock mu(self, monitor->monitor_lock_);
611440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier    // Can't deflate if we have anybody waiting on the CV.
612440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier    if (monitor->num_waiters_ > 0) {
613440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier      return false;
614440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier    }
615590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    Thread* owner = monitor->owner_;
616590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    if (owner != nullptr) {
617590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      // Can't deflate if we are locked and have a hash code.
618590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      if (monitor->HasHashCode()) {
619590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier        return false;
620590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      }
621590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      // Can't deflate if our lock count is too high.
622590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      if (monitor->lock_count_ > LockWord::kThinLockMaxCount) {
623590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier        return false;
624590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      }
625590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      // Deflate to a thin lock.
6264d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier      obj->SetLockWord(LockWord::FromThinLockId(owner->GetThreadId(), monitor->lock_count_), false);
6274d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier      VLOG(monitor) << "Deflated " << obj << " to thin lock " << owner->GetTid() << " / "
6284d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier          << monitor->lock_count_;
629590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    } else if (monitor->HasHashCode()) {
6304d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier      obj->SetLockWord(LockWord::FromHashCode(monitor->GetHashCode()), false);
631440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier      VLOG(monitor) << "Deflated " << obj << " to hash monitor " << monitor->GetHashCode();
632590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    } else {
633590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      // No lock and no hash, just put an empty lock word inside the object.
6344d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier      obj->SetLockWord(LockWord(), false);
635440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier      VLOG(monitor) << "Deflated" << obj << " to empty lock word";
636590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    }
637590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    // The monitor is deflated, mark the object as nullptr so that we know to delete it during the
638590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    // next GC.
63994f7b49578b6aaa80de8ffed230648d601393905Hiroshi Yamauchi    monitor->obj_ = GcRoot<mirror::Object>(nullptr);
640590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier  }
641590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier  return true;
642590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier}
643590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier
644ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartiervoid Monitor::Inflate(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code) {
64574240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe  DCHECK(self != nullptr);
64674240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe  DCHECK(obj != nullptr);
6475f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  // Allocate and acquire a new monitor.
64874240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe  Monitor* m = MonitorPool::CreateMonitor(self, owner, obj, hash_code);
64974240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe  DCHECK(m != nullptr);
650d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  if (m->Install(self)) {
65186ab7912423f63541073af5c487b509e9b2b5420Haifeng Li    if (owner != nullptr) {
65286ab7912423f63541073af5c487b509e9b2b5420Haifeng Li      VLOG(monitor) << "monitor: thread" << owner->GetThreadId()
65374240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe          << " created monitor " << m << " for object " << obj;
65486ab7912423f63541073af5c487b509e9b2b5420Haifeng Li    } else {
65586ab7912423f63541073af5c487b509e9b2b5420Haifeng Li      VLOG(monitor) << "monitor: Inflate with hashcode " << hash_code
65674240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe          << " created monitor " << m << " for object " << obj;
65786ab7912423f63541073af5c487b509e9b2b5420Haifeng Li    }
65874240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe    Runtime::Current()->GetMonitorList()->Add(m);
6594d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier    CHECK_EQ(obj->GetLockWord(true).GetState(), LockWord::kFatLocked);
66074240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe  } else {
66174240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe    MonitorPool::ReleaseMonitor(self, m);
662ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier  }
663ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier}
664ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier
6650cd81352a7c06e381951cea1b104fd73516f4341Mathieu Chartiervoid Monitor::InflateThinLocked(Thread* self, Handle<mirror::Object> obj, LockWord lock_word,
666ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier                                uint32_t hash_code) {
667ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier  DCHECK_EQ(lock_word.GetState(), LockWord::kThinLocked);
668ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier  uint32_t owner_thread_id = lock_word.ThinLockOwner();
669ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier  if (owner_thread_id == self->GetThreadId()) {
670ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    // We own the monitor, we can easily inflate it.
671eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier    Inflate(self, self, obj.Get(), hash_code);
672ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier  } else {
673ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    ThreadList* thread_list = Runtime::Current()->GetThreadList();
674ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    // Suspend the owner, inflate. First change to blocked and give up mutator_lock_.
675eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier    self->SetMonitorEnterObject(obj.Get());
676a1ee14fc66a3c99bb7d5744ace881ec93c46f59dMathieu Chartier    bool timed_out;
677a1ee14fc66a3c99bb7d5744ace881ec93c46f59dMathieu Chartier    Thread* owner;
678a1ee14fc66a3c99bb7d5744ace881ec93c46f59dMathieu Chartier    {
679a1ee14fc66a3c99bb7d5744ace881ec93c46f59dMathieu Chartier      ScopedThreadStateChange tsc(self, kBlocked);
680f3d874c60ee3ada19ce26a5c4e532312b6f3a9e9Ian Rogers      // Take suspend thread lock to avoid races with threads trying to suspend this one.
681f3d874c60ee3ada19ce26a5c4e532312b6f3a9e9Ian Rogers      MutexLock mu(self, *Locks::thread_list_suspend_thread_lock_);
682a1ee14fc66a3c99bb7d5744ace881ec93c46f59dMathieu Chartier      owner = thread_list->SuspendThreadByThreadId(owner_thread_id, false, &timed_out);
683a1ee14fc66a3c99bb7d5744ace881ec93c46f59dMathieu Chartier    }
684a1ee14fc66a3c99bb7d5744ace881ec93c46f59dMathieu Chartier    if (owner != nullptr) {
685a1ee14fc66a3c99bb7d5744ace881ec93c46f59dMathieu Chartier      // We succeeded in suspending the thread, check the lock's status didn't change.
686a1ee14fc66a3c99bb7d5744ace881ec93c46f59dMathieu Chartier      lock_word = obj->GetLockWord(true);
687a1ee14fc66a3c99bb7d5744ace881ec93c46f59dMathieu Chartier      if (lock_word.GetState() == LockWord::kThinLocked &&
688a1ee14fc66a3c99bb7d5744ace881ec93c46f59dMathieu Chartier          lock_word.ThinLockOwner() == owner_thread_id) {
689a1ee14fc66a3c99bb7d5744ace881ec93c46f59dMathieu Chartier        // Go ahead and inflate the lock.
690a1ee14fc66a3c99bb7d5744ace881ec93c46f59dMathieu Chartier        Inflate(self, owner, obj.Get(), hash_code);
691ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier      }
692a1ee14fc66a3c99bb7d5744ace881ec93c46f59dMathieu Chartier      thread_list->Resume(owner, false);
693ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    }
694dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    self->SetMonitorEnterObject(nullptr);
695d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  }
6965f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
6975f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
698719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers// Fool annotalysis into thinking that the lock on obj is acquired.
699719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogersstatic mirror::Object* FakeLock(mirror::Object* obj)
700719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers    EXCLUSIVE_LOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
701719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers  return obj;
702719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers}
703719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers
704719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers// Fool annotalysis into thinking that the lock on obj is release.
705719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogersstatic mirror::Object* FakeUnlock(mirror::Object* obj)
706719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers    UNLOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
707719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers  return obj;
708719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers}
709719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers
710e7e8a5fea2d852cccc840fa046151a16627f26cdMathieu Chartiermirror::Object* Monitor::MonitorEnter(Thread* self, mirror::Object* obj) {
7114681c809ba35d50fab92c592ce8d2c7f8b2731f7Elliott Hughes  DCHECK(self != NULL);
7124681c809ba35d50fab92c592ce8d2c7f8b2731f7Elliott Hughes  DCHECK(obj != NULL);
713719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers  obj = FakeLock(obj);
714d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  uint32_t thread_id = self->GetThreadId();
715d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  size_t contention_count = 0;
716eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier  StackHandleScope<1> hs(self);
717eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier  Handle<mirror::Object> h_obj(hs.NewHandle(obj));
718d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  while (true) {
719eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier    LockWord lock_word = h_obj->GetLockWord(true);
720d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    switch (lock_word.GetState()) {
721d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      case LockWord::kUnlocked: {
722d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0));
723228602f562f1d130d06e60a98752d99c2d467d6aIan Rogers        if (h_obj->CasLockWordWeakSequentiallyConsistent(lock_word, thin_locked)) {
7243035961cb41865b80b927546be0c708b6389cec6Hans Boehm          // CasLockWord enforces more than the acquire ordering we need here.
725eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier          return h_obj.Get();  // Success!
726d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        }
727d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        continue;  // Go again.
7285f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      }
729d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      case LockWord::kThinLocked: {
730d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        uint32_t owner_thread_id = lock_word.ThinLockOwner();
731d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        if (owner_thread_id == thread_id) {
732d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          // We own the lock, increase the recursion count.
733d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          uint32_t new_count = lock_word.ThinLockCount() + 1;
734d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
735d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers            LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count));
736eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier            h_obj->SetLockWord(thin_locked, true);
737eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier            return h_obj.Get();  // Success!
738d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          } else {
739d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers            // We'd overflow the recursion count, so inflate the monitor.
740eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier            InflateThinLocked(self, h_obj, lock_word, 0);
741d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          }
742d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        } else {
743d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          // Contention.
744d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          contention_count++;
745ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier          Runtime* runtime = Runtime::Current();
746ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier          if (contention_count <= runtime->GetMaxSpinsBeforeThinkLockInflation()) {
747b363f666883860d40823d5528df3c98c897f74f4Mathieu Chartier            // TODO: Consider switching the thread state to kBlocked when we are yielding.
748251755cd511463260e60be98bf138b6aa1c14bf3Mathieu Chartier            // Use sched_yield instead of NanoSleep since NanoSleep can wait much longer than the
749251755cd511463260e60be98bf138b6aa1c14bf3Mathieu Chartier            // parameter you pass in. This can cause thread suspension to take excessively long
750b363f666883860d40823d5528df3c98c897f74f4Mathieu Chartier            // and make long pauses. See b/16307460.
751251755cd511463260e60be98bf138b6aa1c14bf3Mathieu Chartier            sched_yield();
7525f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes          } else {
753d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers            contention_count = 0;
754eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier            InflateThinLocked(self, h_obj, lock_word, 0);
7555f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes          }
7565f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes        }
757d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        continue;  // Start from the beginning.
758d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      }
759d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      case LockWord::kFatLocked: {
760d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        Monitor* mon = lock_word.FatLockMonitor();
761d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        mon->Lock(self);
762eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier        return h_obj.Get();  // Success!
7635f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      }
764719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers      case LockWord::kHashCode:
765ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier        // Inflate with the existing hashcode.
766eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier        Inflate(self, nullptr, h_obj.Get(), lock_word.GetHashCode());
767719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers        continue;  // Start from the beginning.
768590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      default: {
769590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier        LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
770eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier        return h_obj.Get();
771590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      }
7725f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    }
7735f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
7745f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
7755f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
7762dd0e2cea360bc9206eb88ecc40d259e796c239dIan Rogersbool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
7775f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  DCHECK(self != NULL);
7785f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  DCHECK(obj != NULL);
779719d1a33f6569864f529e5a3fff59e7bca97aad0Ian Rogers  obj = FakeUnlock(obj);
7804d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  LockWord lock_word = obj->GetLockWord(true);
781eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier  StackHandleScope<1> hs(self);
782eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier  Handle<mirror::Object> h_obj(hs.NewHandle(obj));
783d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  switch (lock_word.GetState()) {
784ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    case LockWord::kHashCode:
785ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier      // Fall-through.
786d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kUnlocked:
787eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier      FailedUnlock(h_obj.Get(), self, nullptr, nullptr);
788d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return false;  // Failure.
789d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kThinLocked: {
790d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      uint32_t thread_id = self->GetThreadId();
791d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      uint32_t owner_thread_id = lock_word.ThinLockOwner();
792d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      if (owner_thread_id != thread_id) {
793d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        // TODO: there's a race here with the owner dying while we unlock.
794d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        Thread* owner =
795d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers            Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
796eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier        FailedUnlock(h_obj.Get(), self, owner, nullptr);
797d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        return false;  // Failure.
7985f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      } else {
799d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        // We own the lock, decrease the recursion count.
800d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        if (lock_word.ThinLockCount() != 0) {
801d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          uint32_t new_count = lock_word.ThinLockCount() - 1;
802d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count));
803eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier          h_obj->SetLockWord(thin_locked, true);
804d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        } else {
805eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier          h_obj->SetLockWord(LockWord(), true);
806d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        }
807d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        return true;  // Success!
8085f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes      }
8095f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    }
810d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kFatLocked: {
811d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      Monitor* mon = lock_word.FatLockMonitor();
812d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return mon->Unlock(self);
8135f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    }
814590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    default: {
815590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
816d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return false;
817590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    }
8185f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
8195f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
8205f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
8215f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes/*
8225f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes * Object.wait().  Also called for class init.
8235f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes */
8242dd0e2cea360bc9206eb88ecc40d259e796c239dIan Rogersvoid Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
8254cd121ef0cb35fced70c7d9de378277be7a727d9Elliott Hughes                   bool interruptShouldThrow, ThreadState why) {
8264d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  DCHECK(self != nullptr);
8274d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  DCHECK(obj != nullptr);
8284d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  LockWord lock_word = obj->GetLockWord(true);
8296f22fc166ed6c11cad229bff442c064e704de101Ian Rogers  while (lock_word.GetState() != LockWord::kFatLocked) {
8306f22fc166ed6c11cad229bff442c064e704de101Ian Rogers    switch (lock_word.GetState()) {
8316f22fc166ed6c11cad229bff442c064e704de101Ian Rogers      case LockWord::kHashCode:
8326f22fc166ed6c11cad229bff442c064e704de101Ian Rogers        // Fall-through.
8336f22fc166ed6c11cad229bff442c064e704de101Ian Rogers      case LockWord::kUnlocked:
834d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
835d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        return;  // Failure.
8366f22fc166ed6c11cad229bff442c064e704de101Ian Rogers      case LockWord::kThinLocked: {
8376f22fc166ed6c11cad229bff442c064e704de101Ian Rogers        uint32_t thread_id = self->GetThreadId();
8386f22fc166ed6c11cad229bff442c064e704de101Ian Rogers        uint32_t owner_thread_id = lock_word.ThinLockOwner();
8396f22fc166ed6c11cad229bff442c064e704de101Ian Rogers        if (owner_thread_id != thread_id) {
8406f22fc166ed6c11cad229bff442c064e704de101Ian Rogers          ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
8416f22fc166ed6c11cad229bff442c064e704de101Ian Rogers          return;  // Failure.
8426f22fc166ed6c11cad229bff442c064e704de101Ian Rogers        } else {
8436f22fc166ed6c11cad229bff442c064e704de101Ian Rogers          // We own the lock, inflate to enqueue ourself on the Monitor. May fail spuriously so
8446f22fc166ed6c11cad229bff442c064e704de101Ian Rogers          // re-load.
8456f22fc166ed6c11cad229bff442c064e704de101Ian Rogers          Inflate(self, self, obj, 0);
8466f22fc166ed6c11cad229bff442c064e704de101Ian Rogers          lock_word = obj->GetLockWord(true);
8476f22fc166ed6c11cad229bff442c064e704de101Ian Rogers        }
8486f22fc166ed6c11cad229bff442c064e704de101Ian Rogers        break;
8496f22fc166ed6c11cad229bff442c064e704de101Ian Rogers      }
8506f22fc166ed6c11cad229bff442c064e704de101Ian Rogers      case LockWord::kFatLocked:  // Unreachable given the loop condition above. Fall-through.
8516f22fc166ed6c11cad229bff442c064e704de101Ian Rogers      default: {
8526f22fc166ed6c11cad229bff442c064e704de101Ian Rogers        LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
8536f22fc166ed6c11cad229bff442c064e704de101Ian Rogers        return;
854d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      }
855590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    }
8565f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
857d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  Monitor* mon = lock_word.FatLockMonitor();
858d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  mon->Wait(self, ms, ns, interruptShouldThrow, why);
8595f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
8605f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
86113c479e7e9b62115fe0409e5273c1e976a1c09f9Ian Rogersvoid Monitor::DoNotify(Thread* self, mirror::Object* obj, bool notify_all) {
8624d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  DCHECK(self != nullptr);
8634d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  DCHECK(obj != nullptr);
8644d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  LockWord lock_word = obj->GetLockWord(true);
865d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  switch (lock_word.GetState()) {
866ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    case LockWord::kHashCode:
867ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier      // Fall-through.
868d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kUnlocked:
8696d0b13e931fb73d5e964d14b0a7ecd1f3f5db547Ian Rogers      ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
870d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return;  // Failure.
871d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kThinLocked: {
872d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      uint32_t thread_id = self->GetThreadId();
873d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      uint32_t owner_thread_id = lock_word.ThinLockOwner();
874d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      if (owner_thread_id != thread_id) {
875d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
876d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        return;  // Failure.
877d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      } else {
878d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        // We own the lock but there's no Monitor and therefore no waiters.
879d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        return;  // Success.
880d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      }
881d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    }
882d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kFatLocked: {
883d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      Monitor* mon = lock_word.FatLockMonitor();
884d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      if (notify_all) {
885d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        mon->NotifyAll(self);
886d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      } else {
887d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        mon->Notify(self);
888d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      }
889d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return;  // Success.
8905f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    }
891590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    default: {
892590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
893590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      return;
894590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    }
8955f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
8965f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
8975f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
898d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogersuint32_t Monitor::GetLockOwnerThreadId(mirror::Object* obj) {
8994d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  DCHECK(obj != nullptr);
9004d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  LockWord lock_word = obj->GetLockWord(true);
901d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  switch (lock_word.GetState()) {
902ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    case LockWord::kHashCode:
903ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier      // Fall-through.
904d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kUnlocked:
905d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return ThreadList::kInvalidThreadId;
906d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kThinLocked:
907d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return lock_word.ThinLockOwner();
908d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kFatLocked: {
909d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      Monitor* mon = lock_word.FatLockMonitor();
910d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return mon->GetOwnerThreadId();
9115f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes    }
912590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    default: {
913d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      LOG(FATAL) << "Unreachable";
914d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return ThreadList::kInvalidThreadId;
915590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    }
9165f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes  }
9175f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}
9185f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes
9198e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughesvoid Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
920d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers  // Determine the wait message and object we're waiting or blocked upon.
921d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers  mirror::Object* pretty_object = nullptr;
922d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers  const char* wait_message = nullptr;
923d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  uint32_t lock_owner = ThreadList::kInvalidThreadId;
924d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers  ThreadState state = thread->GetState();
925b4e94fd380a84c755264e8668a16052442c7ec32Elliott Hughes  if (state == kWaiting || state == kTimedWaiting || state == kSleeping) {
926d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    wait_message = (state == kSleeping) ? "  - sleeping on " : "  - waiting on ";
927d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    Thread* self = Thread::Current();
928d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    MutexLock mu(self, *thread->GetWaitMutex());
929d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    Monitor* monitor = thread->GetWaitMonitor();
930d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    if (monitor != nullptr) {
9314cba0d979a11f955e6ec3c0f1bf61478af7aa810Hiroshi Yamauchi      pretty_object = monitor->GetObject();
9328e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes    }
93334e069606d6f1698cd3c33b39e72b79ae27e1c7bElliott Hughes  } else if (state == kBlocked) {
934d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    wait_message = "  - waiting to lock ";
935d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    pretty_object = thread->GetMonitorEnterObject();
936d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    if (pretty_object != nullptr) {
937d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers      lock_owner = pretty_object->GetLockOwnerThreadId();
9388e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes    }
9398e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  }
9408e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
941d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers  if (wait_message != nullptr) {
942d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    if (pretty_object == nullptr) {
943d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers      os << wait_message << "an unknown object";
944d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    } else {
9454d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier      if ((pretty_object->GetLockWord(true).GetState() == LockWord::kThinLocked) &&
946d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers          Locks::mutator_lock_->IsExclusiveHeld(Thread::Current())) {
947d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers        // Getting the identity hashcode here would result in lock inflation and suspension of the
948d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers        // current thread, which isn't safe if this is the only runnable thread.
949d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers        os << wait_message << StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)",
950d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers                                           reinterpret_cast<intptr_t>(pretty_object),
951d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers                                           PrettyTypeOf(pretty_object).c_str());
952d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers      } else {
953d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers        // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
954d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers        os << wait_message << StringPrintf("<0x%08x> (a %s)", pretty_object->IdentityHashCode(),
955d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers                                           PrettyTypeOf(pretty_object).c_str());
956d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers      }
957d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    }
958d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    // - waiting to lock <0x613f83d8> (a java.lang.Object) held by thread 5
959d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    if (lock_owner != ThreadList::kInvalidThreadId) {
960d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers      os << " held by thread " << lock_owner;
961d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    }
962d803bc7ce255be6c16eaf6a8a58a742515e9da9fIan Rogers    os << "\n";
9638e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes  }
9648e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes}
9658e4aac52962d54cb4be2078b9cd95685e067133aElliott Hughes
9662dd0e2cea360bc9206eb88ecc40d259e796c239dIan Rogersmirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
967f9501700f51586cb6ba7cc0ffcb5a920bd64adf1Elliott Hughes  // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
968f9501700f51586cb6ba7cc0ffcb5a920bd64adf1Elliott Hughes  // definition of contended that includes a monitor a thread is trying to enter...
969dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers  mirror::Object* result = thread->GetMonitorEnterObject();
970d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  if (result == NULL) {
971d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    // ...but also a monitor that the thread is waiting on.
972dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    MutexLock mu(Thread::Current(), *thread->GetWaitMutex());
973dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers    Monitor* monitor = thread->GetWaitMonitor();
974f9501700f51586cb6ba7cc0ffcb5a920bd64adf1Elliott Hughes    if (monitor != NULL) {
975d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      result = monitor->GetObject();
976f9501700f51586cb6ba7cc0ffcb5a920bd64adf1Elliott Hughes    }
977f9501700f51586cb6ba7cc0ffcb5a920bd64adf1Elliott Hughes  }
978d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  return result;
979f9501700f51586cb6ba7cc0ffcb5a920bd64adf1Elliott Hughes}
980f9501700f51586cb6ba7cc0ffcb5a920bd64adf1Elliott Hughes
9812dd0e2cea360bc9206eb88ecc40d259e796c239dIan Rogersvoid Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
982760172c3ccd6e75f6f1a89d8006934e8ffb1303eAndreas Gampe                         void* callback_context, bool abort_on_failure) {
983ea46f950e7a51585db293cd7f047de190a482414Brian Carlstrom  mirror::ArtMethod* m = stack_visitor->GetMethod();
98408fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  CHECK(m != NULL);
98508fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes
98608fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  // Native methods are an easy special case.
98708fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
98808fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  if (m->IsNative()) {
98908fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes    if (m->IsSynchronized()) {
990eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier      mirror::Object* jni_this = stack_visitor->GetCurrentHandleScope()->GetReference(0);
9914993bbc8eda377804e585efd918f8ab9d9eab7d4Elliott Hughes      callback(jni_this, callback_context);
99208fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes    }
99308fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes    return;
99408fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  }
99508fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes
99661f916cc4757610ce308bfdea9a00cf29afd2b02jeffhao  // Proxy methods should not be synchronized.
99761f916cc4757610ce308bfdea9a00cf29afd2b02jeffhao  if (m->IsProxyMethod()) {
99861f916cc4757610ce308bfdea9a00cf29afd2b02jeffhao    CHECK(!m->IsSynchronized());
99961f916cc4757610ce308bfdea9a00cf29afd2b02jeffhao    return;
100061f916cc4757610ce308bfdea9a00cf29afd2b02jeffhao  }
100161f916cc4757610ce308bfdea9a00cf29afd2b02jeffhao
100208fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  // <clinit> is another special case. The runtime holds the class lock while calling <clinit>.
1003bfd9a4378eacaf2dc2bbe05ad48c5164fc93c9feMathieu Chartier  if (m->IsClassInitializer()) {
10044993bbc8eda377804e585efd918f8ab9d9eab7d4Elliott Hughes    callback(m->GetDeclaringClass(), callback_context);
100508fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes    // Fall through because there might be synchronization in the user code too.
100608fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  }
100708fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes
100808fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  // Is there any reason to believe there's any synchronization in this method?
1009bfd9a4378eacaf2dc2bbe05ad48c5164fc93c9feMathieu Chartier  const DexFile::CodeItem* code_item = m->GetCodeItem();
1010caf7654a0e6c76c7489970b1a246fccf220f9982Elliott Hughes  CHECK(code_item != NULL) << PrettyMethod(m);
101108fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  if (code_item->tries_size_ == 0) {
10127934ac288acfb2552bb0b06ec1f61e5820d924a4Brian Carlstrom    return;  // No "tries" implies no synchronization, so no held locks to report.
101308fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  }
101408fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes
1015760172c3ccd6e75f6f1a89d8006934e8ffb1303eAndreas Gampe  // Get the dex pc. If abort_on_failure is false, GetDexPc will not abort in the case it cannot
1016760172c3ccd6e75f6f1a89d8006934e8ffb1303eAndreas Gampe  // find the dex pc, and instead return kDexNoIndex. Then bail out, as it indicates we have an
1017760172c3ccd6e75f6f1a89d8006934e8ffb1303eAndreas Gampe  // inconsistent stack anyways.
1018760172c3ccd6e75f6f1a89d8006934e8ffb1303eAndreas Gampe  uint32_t dex_pc = stack_visitor->GetDexPc(abort_on_failure);
1019760172c3ccd6e75f6f1a89d8006934e8ffb1303eAndreas Gampe  if (!abort_on_failure && dex_pc == DexFile::kDexNoIndex) {
1020760172c3ccd6e75f6f1a89d8006934e8ffb1303eAndreas Gampe    LOG(ERROR) << "Could not find dex_pc for " << PrettyMethod(m);
1021760172c3ccd6e75f6f1a89d8006934e8ffb1303eAndreas Gampe    return;
1022760172c3ccd6e75f6f1a89d8006934e8ffb1303eAndreas Gampe  }
1023760172c3ccd6e75f6f1a89d8006934e8ffb1303eAndreas Gampe
102480537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes  // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
102580537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes  // the locks held in this stack frame.
102680537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes  std::vector<uint32_t> monitor_enter_dex_pcs;
1027760172c3ccd6e75f6f1a89d8006934e8ffb1303eAndreas Gampe  verifier::MethodVerifier::FindLocksAtDexPc(m, dex_pc, &monitor_enter_dex_pcs);
102880537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes  if (monitor_enter_dex_pcs.empty()) {
102980537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes    return;
103080537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes  }
103108fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes
103280537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes  for (size_t i = 0; i < monitor_enter_dex_pcs.size(); ++i) {
103380537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes    // The verifier works in terms of the dex pcs of the monitor-enter instructions.
103480537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes    // We want the registers used by those instructions (so we can read the values out of them).
103580537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes    uint32_t dex_pc = monitor_enter_dex_pcs[i];
103680537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes    uint16_t monitor_enter_instruction = code_item->insns_[dex_pc];
103708fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes
103880537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes    // Quick sanity check.
103980537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes    if ((monitor_enter_instruction & 0xff) != Instruction::MONITOR_ENTER) {
104080537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes      LOG(FATAL) << "expected monitor-enter @" << dex_pc << "; was "
104180537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes                 << reinterpret_cast<void*>(monitor_enter_instruction);
104208fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes    }
104380537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes
104480537bb742dff4ccdf6d04b1c0bb7d2179acc8cbElliott Hughes    uint16_t monitor_register = ((monitor_enter_instruction >> 8) & 0xff);
10452dd0e2cea360bc9206eb88ecc40d259e796c239dIan Rogers    mirror::Object* o = reinterpret_cast<mirror::Object*>(stack_visitor->GetVReg(m, monitor_register,
10462dd0e2cea360bc9206eb88ecc40d259e796c239dIan Rogers                                                                                 kReferenceVReg));
10474993bbc8eda377804e585efd918f8ab9d9eab7d4Elliott Hughes    callback(o, callback_context);
104808fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes  }
104908fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes}
105008fc03ae5dded4adc9b45b7014a4b9dfedbe95a6Elliott Hughes
1051d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogersbool Monitor::IsValidLockWord(LockWord lock_word) {
1052d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  switch (lock_word.GetState()) {
1053d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kUnlocked:
1054d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      // Nothing to check.
1055d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return true;
1056d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kThinLocked:
1057d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      // Basic sanity check of owner.
1058d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
1059d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kFatLocked: {
1060d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      // Check the  monitor appears in the monitor list.
1061d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      Monitor* mon = lock_word.FatLockMonitor();
1062d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      MonitorList* list = Runtime::Current()->GetMonitorList();
1063d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      MutexLock mu(Thread::Current(), list->monitor_list_lock_);
1064d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      for (Monitor* list_mon : list->list_) {
1065d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        if (mon == list_mon) {
1066d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers          return true;  // Found our monitor.
1067d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        }
10687dfb28c066159e6cde8181720f0c451a700ef966Ian Rogers      }
1069d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return false;  // Fail - unowned monitor in an object.
10707dfb28c066159e6cde8181720f0c451a700ef966Ian Rogers    }
1071ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    case LockWord::kHashCode:
1072ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier      return true;
1073d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    default:
1074d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      LOG(FATAL) << "Unreachable";
1075d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      return false;
10767dfb28c066159e6cde8181720f0c451a700ef966Ian Rogers  }
10777dfb28c066159e6cde8181720f0c451a700ef966Ian Rogers}
10787dfb28c066159e6cde8181720f0c451a700ef966Ian Rogers
1079ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartierbool Monitor::IsLocked() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1080ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier  MutexLock mu(Thread::Current(), monitor_lock_);
1081ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier  return owner_ != nullptr;
1082ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier}
1083ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier
1084ef7d42fca18c16fbaf103822ad16f23246e2905dIan Rogersvoid Monitor::TranslateLocation(mirror::ArtMethod* method, uint32_t dex_pc,
1085d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers                                const char** source_file, uint32_t* line_number) const {
108633dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao  // If method is null, location is unknown
108733dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao  if (method == NULL) {
1088d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    *source_file = "";
1089d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    *line_number = 0;
109033dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao    return;
109133dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao  }
1092bfd9a4378eacaf2dc2bbe05ad48c5164fc93c9feMathieu Chartier  *source_file = method->GetDeclaringClassSourceFile();
1093d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  if (*source_file == NULL) {
1094d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    *source_file = "";
1095d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  }
1096bfd9a4378eacaf2dc2bbe05ad48c5164fc93c9feMathieu Chartier  *line_number = method->GetLineNumFromDexPC(dex_pc);
1097d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers}
1098d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers
1099d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogersuint32_t Monitor::GetOwnerThreadId() {
1100d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  MutexLock mu(Thread::Current(), monitor_lock_);
1101d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  Thread* owner = owner_;
1102d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  if (owner != NULL) {
1103d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    return owner->GetThreadId();
1104d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  } else {
1105d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    return ThreadList::kInvalidThreadId;
110612c51e3e5a8b5655351539618f1cf2331f52d1abElliott Hughes  }
110733dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao}
110833dc7717cd16592bcc825350bea6305be9eb2ea1jeffhao
1109c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu ChartierMonitorList::MonitorList()
1110440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier    : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock", kMonitorListLock),
1111c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier      monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
1112c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes}
1113c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes
1114c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott HughesMonitorList::~MonitorList() {
111574240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe  Thread* self = Thread::Current();
111674240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe  MutexLock mu(self, monitor_list_lock_);
111774240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe  // Release all monitors to the pool.
111874240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe  // TODO: Is it an invariant that *all* open monitors are in the list? Then we could
111974240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe  // clear faster in the pool.
112074240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe  MonitorPool::ReleaseMonitors(self, &list_);
1121c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes}
1122c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes
1123c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartiervoid MonitorList::DisallowNewMonitors() {
112450b35e2fd1a68cd1240e4a9d9f363e11764957d1Ian Rogers  MutexLock mu(Thread::Current(), monitor_list_lock_);
1125c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier  allow_new_monitors_ = false;
1126c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier}
1127c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier
1128c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartiervoid MonitorList::AllowNewMonitors() {
1129c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier  Thread* self = Thread::Current();
1130c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier  MutexLock mu(self, monitor_list_lock_);
1131c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier  allow_new_monitors_ = true;
1132c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier  monitor_add_condition_.Broadcast(self);
1133c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier}
1134c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier
1135c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartiervoid MonitorList::Add(Monitor* m) {
1136c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier  Thread* self = Thread::Current();
1137c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier  MutexLock mu(self, monitor_list_lock_);
1138c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier  while (UNLIKELY(!allow_new_monitors_)) {
1139c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier    monitor_add_condition_.WaitHoldingLocks(self);
1140c11d9b8870de5f860b13c84003ade7b3f3125a52Mathieu Chartier  }
1141c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes  list_.push_front(m);
1142c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes}
1143c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes
114483c8ee000d525017ead8753fce6bc1020249b96aMathieu Chartiervoid MonitorList::SweepMonitorList(IsMarkedCallback* callback, void* arg) {
114574240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe  Thread* self = Thread::Current();
114674240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe  MutexLock mu(self, monitor_list_lock_);
114702e25119b15a6f619f17db99f5d05124a5807ff3Mathieu Chartier  for (auto it = list_.begin(); it != list_.end(); ) {
1148c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes    Monitor* m = *it;
11494cba0d979a11f955e6ec3c0f1bf61478af7aa810Hiroshi Yamauchi    // Disable the read barrier in GetObject() as this is called by GC.
11504cba0d979a11f955e6ec3c0f1bf61478af7aa810Hiroshi Yamauchi    mirror::Object* obj = m->GetObject<kWithoutReadBarrier>();
1151590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    // The object of a monitor can be null if we have deflated it.
115283c8ee000d525017ead8753fce6bc1020249b96aMathieu Chartier    mirror::Object* new_obj = obj != nullptr ? callback(obj, arg) : nullptr;
11536aa3df965395566ed6a4fec4af37c2b7577992e9Mathieu Chartier    if (new_obj == nullptr) {
11546aa3df965395566ed6a4fec4af37c2b7577992e9Mathieu Chartier      VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
11554cba0d979a11f955e6ec3c0f1bf61478af7aa810Hiroshi Yamauchi                    << obj;
115674240819ae09e29b2753ef38f4eb4be1c2762e2eAndreas Gampe      MonitorPool::ReleaseMonitor(self, m);
1157c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes      it = list_.erase(it);
1158c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes    } else {
11596aa3df965395566ed6a4fec4af37c2b7577992e9Mathieu Chartier      m->SetObject(new_obj);
1160c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes      ++it;
1161c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes    }
1162c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes  }
1163c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes}
1164c33a32bccc4c66ed82ce3a580b16636399385cb4Elliott Hughes
116548ab687d1f864fec93c2682de6fdc44ab784e2f8Mathieu Chartierstruct MonitorDeflateArgs {
116648ab687d1f864fec93c2682de6fdc44ab784e2f8Mathieu Chartier  MonitorDeflateArgs() : self(Thread::Current()), deflate_count(0) {}
116748ab687d1f864fec93c2682de6fdc44ab784e2f8Mathieu Chartier  Thread* const self;
116848ab687d1f864fec93c2682de6fdc44ab784e2f8Mathieu Chartier  size_t deflate_count;
116948ab687d1f864fec93c2682de6fdc44ab784e2f8Mathieu Chartier};
117048ab687d1f864fec93c2682de6fdc44ab784e2f8Mathieu Chartier
1171440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartierstatic mirror::Object* MonitorDeflateCallback(mirror::Object* object, void* arg)
1172440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
117348ab687d1f864fec93c2682de6fdc44ab784e2f8Mathieu Chartier  MonitorDeflateArgs* args = reinterpret_cast<MonitorDeflateArgs*>(arg);
117448ab687d1f864fec93c2682de6fdc44ab784e2f8Mathieu Chartier  if (Monitor::Deflate(args->self, object)) {
11754d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier    DCHECK_NE(object->GetLockWord(true).GetState(), LockWord::kFatLocked);
117648ab687d1f864fec93c2682de6fdc44ab784e2f8Mathieu Chartier    ++args->deflate_count;
1177440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier    // If we deflated, return nullptr so that the monitor gets removed from the array.
1178440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier    return nullptr;
1179440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier  }
1180440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier  return object;  // Monitor was not deflated.
1181440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier}
1182440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier
118348ab687d1f864fec93c2682de6fdc44ab784e2f8Mathieu Chartiersize_t MonitorList::DeflateMonitors() {
118448ab687d1f864fec93c2682de6fdc44ab784e2f8Mathieu Chartier  MonitorDeflateArgs args;
118548ab687d1f864fec93c2682de6fdc44ab784e2f8Mathieu Chartier  Locks::mutator_lock_->AssertExclusiveHeld(args.self);
118648ab687d1f864fec93c2682de6fdc44ab784e2f8Mathieu Chartier  SweepMonitorList(MonitorDeflateCallback, &args);
118748ab687d1f864fec93c2682de6fdc44ab784e2f8Mathieu Chartier  return args.deflate_count;
1188440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier}
1189440e4ceb310349ee8eb569495bc04d3d7fbe71cbMathieu Chartier
1190d9c4fc94fa618617f94e1de9af5f034549100753Ian RogersMonitorInfo::MonitorInfo(mirror::Object* obj) : owner_(NULL), entry_count_(0) {
11914d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  DCHECK(obj != nullptr);
11924d7f61d44a732cfbc8573e5d93364983fd746888Mathieu Chartier  LockWord lock_word = obj->GetLockWord(true);
1193d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers  switch (lock_word.GetState()) {
1194d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kUnlocked:
1195ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier      // Fall-through.
1196590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    case LockWord::kForwardingAddress:
1197590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      // Fall-through.
1198ad2541a59c00c2c69e8973088891a2b5257c9780Mathieu Chartier    case LockWord::kHashCode:
1199d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      break;
1200d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kThinLocked:
1201d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
1202d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      entry_count_ = 1 + lock_word.ThinLockCount();
1203d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      // Thin locks have no waiters.
1204d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      break;
1205d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers    case LockWord::kFatLocked: {
1206d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      Monitor* mon = lock_word.FatLockMonitor();
1207d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      owner_ = mon->owner_;
1208d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      entry_count_ = 1 + mon->lock_count_;
1209dd7624d2b9e599d57762d12031b10b89defc9807Ian Rogers      for (Thread* waiter = mon->wait_set_; waiter != NULL; waiter = waiter->GetWaitNext()) {
1210d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers        waiters_.push_back(waiter);
1211d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      }
1212d9c4fc94fa618617f94e1de9af5f034549100753Ian Rogers      break;
1213f327e07b37e349b1ec5eaad6dc294a9b7a081d20Elliott Hughes    }
1214f327e07b37e349b1ec5eaad6dc294a9b7a081d20Elliott Hughes  }
1215f327e07b37e349b1ec5eaad6dc294a9b7a081d20Elliott Hughes}
1216f327e07b37e349b1ec5eaad6dc294a9b7a081d20Elliott Hughes
12175f79133a435ebcb20000370d56046fe01201dd80Elliott Hughes}  // namespace art
1218