blob: 255a0f23d8e2c0415ff5bc448c040fe22dcb0f69 [file] [log] [blame]
Elliott Hughes5f791332011-09-15 17:45:30 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Elliott Hughes54e7df12011-09-16 11:47:04 -070017#include "monitor.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070018
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -080019#define ATRACE_TAG ATRACE_TAG_DALVIK
20
21#include <cutils/trace.h>
Elliott Hughes08fc03a2012-06-26 17:34:00 -070022#include <vector>
23
Mathieu Chartiere401d142015-04-22 13:56:20 -070024#include "art_method-inl.h"
Elliott Hughes76b61672012-12-12 17:47:30 -080025#include "base/mutex.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080026#include "base/stl_util.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010027#include "base/time_utils.h"
jeffhao33dc7712011-11-09 17:54:24 -080028#include "class_linker.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070029#include "dex_file-inl.h"
Elliott Hughes08fc03a2012-06-26 17:34:00 -070030#include "dex_instruction.h"
Ian Rogersd9c4fc92013-10-01 19:45:43 -070031#include "lock_word-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070032#include "mirror/class-inl.h"
Ian Rogers05f30572013-02-20 12:13:11 -080033#include "mirror/object-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080034#include "mirror/object_array-inl.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070035#include "scoped_thread_state_change.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070036#include "thread.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070037#include "thread_list.h"
Elliott Hughes08fc03a2012-06-26 17:34:00 -070038#include "verifier/method_verifier.h"
Elliott Hughes044288f2012-06-25 14:46:39 -070039#include "well_known_classes.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070040
41namespace art {
42
Mathieu Chartierb9001ab2014-10-03 13:28:46 -070043static constexpr uint64_t kLongWaitMs = 100;
44
Elliott Hughes5f791332011-09-15 17:45:30 -070045/*
Ian Rogersd9c4fc92013-10-01 19:45:43 -070046 * Every Object has a monitor associated with it, but not every Object is actually locked. Even
47 * the ones that are locked do not need a full-fledged monitor until a) there is actual contention
48 * or b) wait() is called on the Object.
Elliott Hughes5f791332011-09-15 17:45:30 -070049 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070050 * For Android, we have implemented a scheme similar to the one described in Bacon et al.'s
51 * "Thin locks: featherweight synchronization for Java" (ACM 1998). Things are even easier for us,
52 * though, because we have a full 32 bits to work with.
Elliott Hughes5f791332011-09-15 17:45:30 -070053 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070054 * The two states of an Object's lock are referred to as "thin" and "fat". A lock may transition
55 * from the "thin" state to the "fat" state and this transition is referred to as inflation. Once
56 * a lock has been inflated it remains in the "fat" state indefinitely.
Elliott Hughes5f791332011-09-15 17:45:30 -070057 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070058 * The lock value itself is stored in mirror::Object::monitor_ and the representation is described
59 * in the LockWord value type.
Elliott Hughes54e7df12011-09-16 11:47:04 -070060 *
Elliott Hughes5f791332011-09-15 17:45:30 -070061 * Monitors provide:
62 * - mutually exclusive access to resources
63 * - a way for multiple threads to wait for notification
64 *
65 * In effect, they fill the role of both mutexes and condition variables.
66 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070067 * Only one thread can own the monitor at any time. There may be several threads waiting on it
68 * (the wait call unlocks it). One or more waiting threads may be getting interrupted or notified
69 * at any given time.
Elliott Hughes5f791332011-09-15 17:45:30 -070070 */
Elliott Hughes54e7df12011-09-16 11:47:04 -070071
Mathieu Chartier2cebb242015-04-21 16:50:40 -070072bool (*Monitor::is_sensitive_thread_hook_)() = nullptr;
Elliott Hughesfc861622011-10-17 17:57:47 -070073uint32_t Monitor::lock_profiling_threshold_ = 0;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070074
Elliott Hughesfc861622011-10-17 17:57:47 -070075bool Monitor::IsSensitiveThread() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070076 if (is_sensitive_thread_hook_ != nullptr) {
Elliott Hughesfc861622011-10-17 17:57:47 -070077 return (*is_sensitive_thread_hook_)();
78 }
79 return false;
80}
81
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -080082void Monitor::Init(uint32_t lock_profiling_threshold, bool (*is_sensitive_thread_hook)()) {
Elliott Hughesfc861622011-10-17 17:57:47 -070083 lock_profiling_threshold_ = lock_profiling_threshold;
84 is_sensitive_thread_hook_ = is_sensitive_thread_hook;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070085}
86
Ian Rogersef7d42f2014-01-06 12:55:46 -080087Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code)
Ian Rogers00f7d0e2012-07-19 15:28:27 -070088 : monitor_lock_("a monitor lock", kMonitorLock),
Ian Rogersd9c4fc92013-10-01 19:45:43 -070089 monitor_contenders_("monitor contenders", monitor_lock_),
Mathieu Chartier46bc7782013-11-12 17:03:02 -080090 num_waiters_(0),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070091 owner_(owner),
Elliott Hughes5f791332011-09-15 17:45:30 -070092 lock_count_(0),
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070093 obj_(GcRoot<mirror::Object>(obj)),
Mathieu Chartier2cebb242015-04-21 16:50:40 -070094 wait_set_(nullptr),
Mathieu Chartierad2541a2013-10-25 10:05:23 -070095 hash_code_(hash_code),
Mathieu Chartier2cebb242015-04-21 16:50:40 -070096 locking_method_(nullptr),
Ian Rogersef7d42f2014-01-06 12:55:46 -080097 locking_dex_pc_(0),
Andreas Gampe74240812014-04-17 10:35:09 -070098 monitor_id_(MonitorPool::ComputeMonitorId(this, self)) {
99#ifdef __LP64__
100 DCHECK(false) << "Should not be reached in 64b";
101 next_free_ = nullptr;
102#endif
103 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
104 // with the owner unlocking the thin-lock.
105 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
106 // The identity hash code is set for the life time of the monitor.
107}
108
109Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code,
110 MonitorId id)
111 : monitor_lock_("a monitor lock", kMonitorLock),
112 monitor_contenders_("monitor contenders", monitor_lock_),
113 num_waiters_(0),
114 owner_(owner),
115 lock_count_(0),
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700116 obj_(GcRoot<mirror::Object>(obj)),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700117 wait_set_(nullptr),
Andreas Gampe74240812014-04-17 10:35:09 -0700118 hash_code_(hash_code),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700119 locking_method_(nullptr),
Andreas Gampe74240812014-04-17 10:35:09 -0700120 locking_dex_pc_(0),
121 monitor_id_(id) {
122#ifdef __LP64__
123 next_free_ = nullptr;
124#endif
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700125 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
126 // with the owner unlocking the thin-lock.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800127 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700128 // The identity hash code is set for the life time of the monitor.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700129}
130
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700131int32_t Monitor::GetHashCode() {
132 while (!HasHashCode()) {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700133 if (hash_code_.CompareExchangeWeakRelaxed(0, mirror::Object::GenerateIdentityHashCode())) {
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700134 break;
135 }
136 }
137 DCHECK(HasHashCode());
Ian Rogers3e5cf302014-05-20 16:40:37 -0700138 return hash_code_.LoadRelaxed();
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700139}
140
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700141bool Monitor::Install(Thread* self) {
142 MutexLock mu(self, monitor_lock_); // Uncontended mutex acquisition as monitor isn't yet public.
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700143 CHECK(owner_ == nullptr || owner_ == self || owner_->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700144 // Propagate the lock state.
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700145 LockWord lw(GetObject()->GetLockWord(false));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700146 switch (lw.GetState()) {
147 case LockWord::kThinLocked: {
148 CHECK_EQ(owner_->GetThreadId(), lw.ThinLockOwner());
149 lock_count_ = lw.ThinLockCount();
150 break;
151 }
152 case LockWord::kHashCode: {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700153 CHECK_EQ(hash_code_.LoadRelaxed(), static_cast<int32_t>(lw.GetHashCode()));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700154 break;
155 }
156 case LockWord::kFatLocked: {
157 // The owner_ is suspended but another thread beat us to install a monitor.
158 return false;
159 }
160 case LockWord::kUnlocked: {
161 LOG(FATAL) << "Inflating unlocked lock word";
162 break;
163 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700164 default: {
165 LOG(FATAL) << "Invalid monitor state " << lw.GetState();
166 return false;
167 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700168 }
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800169 LockWord fat(this, lw.ReadBarrierState());
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700170 // Publish the updated lock word, which may race with other threads.
Ian Rogers228602f2014-07-10 02:07:54 -0700171 bool success = GetObject()->CasLockWordWeakSequentiallyConsistent(lw, fat);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700172 // Lock profiling.
Mathieu Chartier9728f912013-10-30 09:45:13 -0700173 if (success && owner_ != nullptr && lock_profiling_threshold_ != 0) {
Andreas Gampe6ec8ebd2014-07-25 13:36:56 -0700174 // Do not abort on dex pc errors. This can easily happen when we want to dump a stack trace on
175 // abort.
176 locking_method_ = owner_->GetCurrentMethod(&locking_dex_pc_, false);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700177 }
178 return success;
Elliott Hughes5f791332011-09-15 17:45:30 -0700179}
180
181Monitor::~Monitor() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700182 // Deflated monitors have a null object.
Elliott Hughes5f791332011-09-15 17:45:30 -0700183}
184
Elliott Hughes5f791332011-09-15 17:45:30 -0700185void Monitor::AppendToWaitSet(Thread* thread) {
186 DCHECK(owner_ == Thread::Current());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700187 DCHECK(thread != nullptr);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700188 DCHECK(thread->GetWaitNext() == nullptr) << thread->GetWaitNext();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700189 if (wait_set_ == nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700190 wait_set_ = thread;
191 return;
192 }
193
194 // push_back.
195 Thread* t = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700196 while (t->GetWaitNext() != nullptr) {
197 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700198 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700199 t->SetWaitNext(thread);
Elliott Hughes5f791332011-09-15 17:45:30 -0700200}
201
Elliott Hughes5f791332011-09-15 17:45:30 -0700202void Monitor::RemoveFromWaitSet(Thread *thread) {
203 DCHECK(owner_ == Thread::Current());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700204 DCHECK(thread != nullptr);
205 if (wait_set_ == nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700206 return;
207 }
208 if (wait_set_ == thread) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700209 wait_set_ = thread->GetWaitNext();
210 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700211 return;
212 }
213
214 Thread* t = wait_set_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700215 while (t->GetWaitNext() != nullptr) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700216 if (t->GetWaitNext() == thread) {
217 t->SetWaitNext(thread->GetWaitNext());
218 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700219 return;
220 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700221 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700222 }
223}
224
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700225void Monitor::SetObject(mirror::Object* object) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700226 obj_ = GcRoot<mirror::Object>(object);
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700227}
228
Elliott Hughes5f791332011-09-15 17:45:30 -0700229void Monitor::Lock(Thread* self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700230 MutexLock mu(self, monitor_lock_);
231 while (true) {
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700232 if (owner_ == nullptr) { // Unowned.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700233 owner_ = self;
234 CHECK_EQ(lock_count_, 0);
235 // When debugging, save the current monitor holder for future
236 // acquisition failures to use in sampled logging.
237 if (lock_profiling_threshold_ != 0) {
238 locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
239 }
240 return;
241 } else if (owner_ == self) { // Recursive.
242 lock_count_++;
243 return;
244 }
245 // Contended.
246 const bool log_contention = (lock_profiling_threshold_ != 0);
Xin Guanb894a192014-08-22 11:55:37 -0500247 uint64_t wait_start_ms = log_contention ? MilliTime() : 0;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700248 ArtMethod* owners_method = locking_method_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700249 uint32_t owners_dex_pc = locking_dex_pc_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700250 // Do this before releasing the lock so that we don't get deflated.
Mathieu Chartierb9001ab2014-10-03 13:28:46 -0700251 size_t num_waiters = num_waiters_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700252 ++num_waiters_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700253 monitor_lock_.Unlock(self); // Let go of locks in order.
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700254 self->SetMonitorEnterObject(GetObject());
Elliott Hughes5f791332011-09-15 17:45:30 -0700255 {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700256 ScopedThreadStateChange tsc(self, kBlocked); // Change to blocked and give up mutator_lock_.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700257 // Reacquire monitor_lock_ without mutator_lock_ for Wait.
258 MutexLock mu2(self, monitor_lock_);
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800259 if (owner_ != nullptr) { // Did the owner_ give the lock up?
260 if (ATRACE_ENABLED()) {
261 std::string name;
262 owner_->GetThreadName(name);
263 ATRACE_BEGIN(("Contended on monitor with owner " + name).c_str());
264 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700265 monitor_contenders_.Wait(self); // Still contended so wait.
266 // Woken from contention.
267 if (log_contention) {
268 uint64_t wait_ms = MilliTime() - wait_start_ms;
269 uint32_t sample_percent;
270 if (wait_ms >= lock_profiling_threshold_) {
271 sample_percent = 100;
272 } else {
273 sample_percent = 100 * wait_ms / lock_profiling_threshold_;
274 }
275 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
276 const char* owners_filename;
277 uint32_t owners_line_number;
278 TranslateLocation(owners_method, owners_dex_pc, &owners_filename, &owners_line_number);
Mathieu Chartierb9001ab2014-10-03 13:28:46 -0700279 if (wait_ms > kLongWaitMs && owners_method != nullptr) {
280 LOG(WARNING) << "Long monitor contention event with owner method="
281 << PrettyMethod(owners_method) << " from " << owners_filename << ":"
282 << owners_line_number << " waiters=" << num_waiters << " for "
283 << PrettyDuration(MsToNs(wait_ms));
284 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700285 LogContentionEvent(self, wait_ms, sample_percent, owners_filename, owners_line_number);
286 }
287 }
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800288 ATRACE_END();
Elliott Hughesfc861622011-10-17 17:57:47 -0700289 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700290 }
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700291 self->SetMonitorEnterObject(nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700292 monitor_lock_.Lock(self); // Reacquire locks in order.
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700293 --num_waiters_;
Elliott Hughesfc861622011-10-17 17:57:47 -0700294 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700295}
296
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800297static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
298 __attribute__((format(printf, 1, 2)));
299
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700300static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
Mathieu Chartier90443472015-07-16 20:32:27 -0700301 SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800302 va_list args;
303 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800304 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000305 self->ThrowNewExceptionV("Ljava/lang/IllegalMonitorStateException;", fmt, args);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700306 if (!Runtime::Current()->IsStarted() || VLOG_IS_ON(monitor)) {
Brian Carlstrom64277f32012-03-26 23:53:34 -0700307 std::ostringstream ss;
Ian Rogers62d6c772013-02-27 08:32:07 -0800308 self->Dump(ss);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700309 LOG(Runtime::Current()->IsStarted() ? INFO : ERROR)
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000310 << self->GetException()->Dump() << "\n" << ss.str();
Brian Carlstrom64277f32012-03-26 23:53:34 -0700311 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800312 va_end(args);
313}
314
Elliott Hughesd4237412012-02-21 11:24:45 -0800315static std::string ThreadToString(Thread* thread) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700316 if (thread == nullptr) {
317 return "nullptr";
Elliott Hughesd4237412012-02-21 11:24:45 -0800318 }
319 std::ostringstream oss;
320 // TODO: alternatively, we could just return the thread's name.
321 oss << *thread;
322 return oss.str();
323}
324
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800325void Monitor::FailedUnlock(mirror::Object* o, Thread* expected_owner, Thread* found_owner,
Elliott Hughesffb465f2012-03-01 18:46:05 -0800326 Monitor* monitor) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700327 Thread* current_owner = nullptr;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800328 std::string current_owner_string;
329 std::string expected_owner_string;
330 std::string found_owner_string;
331 {
332 // TODO: isn't this too late to prevent threads from disappearing?
333 // Acquire thread list lock so threads won't disappear from under us.
Ian Rogers50b35e22012-10-04 10:09:15 -0700334 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Elliott Hughesffb465f2012-03-01 18:46:05 -0800335 // Re-read owner now that we hold lock.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700336 current_owner = (monitor != nullptr) ? monitor->GetOwner() : nullptr;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800337 // Get short descriptions of the threads involved.
338 current_owner_string = ThreadToString(current_owner);
339 expected_owner_string = ThreadToString(expected_owner);
340 found_owner_string = ThreadToString(found_owner);
341 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700342 if (current_owner == nullptr) {
343 if (found_owner == nullptr) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800344 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
345 " on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800346 PrettyTypeOf(o).c_str(),
347 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800348 } else {
349 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800350 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
351 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800352 found_owner_string.c_str(),
353 PrettyTypeOf(o).c_str(),
354 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800355 }
356 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700357 if (found_owner == nullptr) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800358 // Race: originally there was no owner, there is now
359 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
360 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800361 current_owner_string.c_str(),
362 PrettyTypeOf(o).c_str(),
363 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800364 } else {
365 if (found_owner != current_owner) {
366 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800367 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
368 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800369 found_owner_string.c_str(),
370 current_owner_string.c_str(),
371 PrettyTypeOf(o).c_str(),
372 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800373 } else {
374 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
375 " on thread '%s",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800376 current_owner_string.c_str(),
377 PrettyTypeOf(o).c_str(),
378 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800379 }
380 }
381 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700382}
383
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700384bool Monitor::Unlock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700385 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700386 MutexLock mu(self, monitor_lock_);
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800387 Thread* owner = owner_;
388 if (owner == self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700389 // We own the monitor, so nobody else can be in here.
390 if (lock_count_ == 0) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700391 owner_ = nullptr;
392 locking_method_ = nullptr;
Ian Rogers0399dde2012-06-06 17:09:28 -0700393 locking_dex_pc_ = 0;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700394 // Wake a contender.
395 monitor_contenders_.Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700396 } else {
397 --lock_count_;
398 }
399 } else {
400 // We don't own this, so we're not allowed to unlock it.
401 // The JNI spec says that we should throw IllegalMonitorStateException
402 // in this case.
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700403 FailedUnlock(GetObject(), self, owner, this);
Elliott Hughes5f791332011-09-15 17:45:30 -0700404 return false;
405 }
406 return true;
407}
408
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800409void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
410 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700411 DCHECK(self != nullptr);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800412 DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
Elliott Hughes5f791332011-09-15 17:45:30 -0700413
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700414 monitor_lock_.Lock(self);
415
Elliott Hughes5f791332011-09-15 17:45:30 -0700416 // Make sure that we hold the lock.
417 if (owner_ != self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700418 monitor_lock_.Unlock(self);
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700419 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700420 return;
421 }
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800422
Elliott Hughesdf42c482013-01-09 12:49:02 -0800423 // We need to turn a zero-length timed wait into a regular wait because
424 // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
425 if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
426 why = kWaiting;
427 }
428
Elliott Hughes5f791332011-09-15 17:45:30 -0700429 // Enforce the timeout range.
430 if (ms < 0 || ns < 0 || ns > 999999) {
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700431 monitor_lock_.Unlock(self);
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000432 self->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
Ian Rogersef7d42f2014-01-06 12:55:46 -0800433 "timeout arguments out of range: ms=%" PRId64 " ns=%d", ms, ns);
Elliott Hughes5f791332011-09-15 17:45:30 -0700434 return;
435 }
436
Elliott Hughes5f791332011-09-15 17:45:30 -0700437 /*
438 * Add ourselves to the set of threads waiting on this monitor, and
439 * release our hold. We need to let it go even if we're a few levels
440 * deep in a recursive lock, and we need to restore that later.
441 *
442 * We append to the wait set ahead of clearing the count and owner
443 * fields so the subroutine can check that the calling thread owns
444 * the monitor. Aside from that, the order of member updates is
445 * not order sensitive as we hold the pthread mutex.
446 */
447 AppendToWaitSet(self);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700448 ++num_waiters_;
Ian Rogers0399dde2012-06-06 17:09:28 -0700449 int prev_lock_count = lock_count_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700450 lock_count_ = 0;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700451 owner_ = nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700452 ArtMethod* saved_method = locking_method_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700453 locking_method_ = nullptr;
Ian Rogers0399dde2012-06-06 17:09:28 -0700454 uintptr_t saved_dex_pc = locking_dex_pc_;
455 locking_dex_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700456
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800457 bool was_interrupted = false;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700458 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700459 // Update thread state. If the GC wakes up, it'll ignore us, knowing
460 // that we won't touch any references in this state, and we'll check
461 // our suspend mode before we transition out.
462 ScopedThreadSuspension sts(self, why);
463
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700464 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700465 MutexLock mu(self, *self->GetWaitMutex());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700466
467 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700468 // non-null a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700469 // up.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700470 DCHECK(self->GetWaitMonitor() == nullptr);
471 self->SetWaitMonitor(this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700472
473 // Release the monitor lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700474 monitor_contenders_.Signal(self);
475 monitor_lock_.Unlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700476
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800477 // Handle the case where the thread was interrupted before we called wait().
Ian Rogersdd7624d2014-03-14 17:43:00 -0700478 if (self->IsInterruptedLocked()) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800479 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700480 } else {
481 // Wait for a notification or a timeout to occur.
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800482 if (why == kWaiting) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700483 self->GetWaitConditionVariable()->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700484 } else {
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800485 DCHECK(why == kTimedWaiting || why == kSleeping) << why;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700486 self->GetWaitConditionVariable()->TimedWait(self, ms, ns);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700487 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700488 if (self->IsInterruptedLocked()) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800489 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700490 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700491 self->SetInterruptedLocked(false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700492 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700493 }
494
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800495 {
496 // We reset the thread's wait_monitor_ field after transitioning back to runnable so
497 // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
498 // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
499 // are waiting on "null".)
Ian Rogersdd7624d2014-03-14 17:43:00 -0700500 MutexLock mu(self, *self->GetWaitMutex());
501 DCHECK(self->GetWaitMonitor() != nullptr);
502 self->SetWaitMonitor(nullptr);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800503 }
504
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700505 // Re-acquire the monitor and lock.
Elliott Hughes5f791332011-09-15 17:45:30 -0700506 Lock(self);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700507 monitor_lock_.Lock(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700508 self->GetWaitMutex()->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700509
Elliott Hughes5f791332011-09-15 17:45:30 -0700510 /*
511 * We remove our thread from wait set after restoring the count
512 * and owner fields so the subroutine can check that the calling
513 * thread owns the monitor. Aside from that, the order of member
514 * updates is not order sensitive as we hold the pthread mutex.
515 */
516 owner_ = self;
Ian Rogers0399dde2012-06-06 17:09:28 -0700517 lock_count_ = prev_lock_count;
518 locking_method_ = saved_method;
519 locking_dex_pc_ = saved_dex_pc;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700520 --num_waiters_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700521 RemoveFromWaitSet(self);
522
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700523 monitor_lock_.Unlock(self);
524
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800525 if (was_interrupted) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700526 /*
527 * We were interrupted while waiting, or somebody interrupted an
528 * un-interruptible thread earlier and we're bailing out immediately.
529 *
530 * The doc sayeth: "The interrupted status of the current thread is
531 * cleared when this exception is thrown."
532 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700533 {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700534 MutexLock mu(self, *self->GetWaitMutex());
535 self->SetInterruptedLocked(false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700536 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700537 if (interruptShouldThrow) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700538 self->ThrowNewException("Ljava/lang/InterruptedException;", nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700539 }
540 }
541}
542
543void Monitor::Notify(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700544 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700545 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700546 // Make sure that we hold the lock.
547 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800548 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700549 return;
550 }
551 // Signal the first waiting thread in the wait set.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700552 while (wait_set_ != nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700553 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700554 wait_set_ = thread->GetWaitNext();
555 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700556
557 // Check to see if the thread is still waiting.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800558 MutexLock wait_mu(self, *thread->GetWaitMutex());
Ian Rogersdd7624d2014-03-14 17:43:00 -0700559 if (thread->GetWaitMonitor() != nullptr) {
560 thread->GetWaitConditionVariable()->Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700561 return;
562 }
563 }
564}
565
566void Monitor::NotifyAll(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700567 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700568 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700569 // Make sure that we hold the lock.
570 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800571 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700572 return;
573 }
574 // Signal all threads in the wait set.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700575 while (wait_set_ != nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700576 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700577 wait_set_ = thread->GetWaitNext();
578 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700579 thread->Notify();
580 }
581}
582
Mathieu Chartier590fee92013-09-13 13:46:47 -0700583bool Monitor::Deflate(Thread* self, mirror::Object* obj) {
584 DCHECK(obj != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700585 // Don't need volatile since we only deflate with mutators suspended.
586 LockWord lw(obj->GetLockWord(false));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700587 // If the lock isn't an inflated monitor, then we don't need to deflate anything.
588 if (lw.GetState() == LockWord::kFatLocked) {
589 Monitor* monitor = lw.FatLockMonitor();
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700590 DCHECK(monitor != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700591 MutexLock mu(self, monitor->monitor_lock_);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700592 // Can't deflate if we have anybody waiting on the CV.
593 if (monitor->num_waiters_ > 0) {
594 return false;
595 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700596 Thread* owner = monitor->owner_;
597 if (owner != nullptr) {
598 // Can't deflate if we are locked and have a hash code.
599 if (monitor->HasHashCode()) {
600 return false;
601 }
602 // Can't deflate if our lock count is too high.
603 if (monitor->lock_count_ > LockWord::kThinLockMaxCount) {
604 return false;
605 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700606 // Deflate to a thin lock.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800607 LockWord new_lw = LockWord::FromThinLockId(owner->GetThreadId(), monitor->lock_count_,
608 lw.ReadBarrierState());
609 // Assume no concurrent read barrier state changes as mutators are suspended.
610 obj->SetLockWord(new_lw, false);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700611 VLOG(monitor) << "Deflated " << obj << " to thin lock " << owner->GetTid() << " / "
612 << monitor->lock_count_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700613 } else if (monitor->HasHashCode()) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800614 LockWord new_lw = LockWord::FromHashCode(monitor->GetHashCode(), lw.ReadBarrierState());
615 // Assume no concurrent read barrier state changes as mutators are suspended.
616 obj->SetLockWord(new_lw, false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700617 VLOG(monitor) << "Deflated " << obj << " to hash monitor " << monitor->GetHashCode();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700618 } else {
619 // No lock and no hash, just put an empty lock word inside the object.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800620 LockWord new_lw = LockWord::FromDefault(lw.ReadBarrierState());
621 // Assume no concurrent read barrier state changes as mutators are suspended.
622 obj->SetLockWord(new_lw, false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700623 VLOG(monitor) << "Deflated" << obj << " to empty lock word";
Mathieu Chartier590fee92013-09-13 13:46:47 -0700624 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700625 // The monitor is deflated, mark the object as null so that we know to delete it during the
Mathieu Chartier590fee92013-09-13 13:46:47 -0700626 // next GC.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700627 monitor->obj_ = GcRoot<mirror::Object>(nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700628 }
629 return true;
630}
631
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700632void Monitor::Inflate(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code) {
Andreas Gampe74240812014-04-17 10:35:09 -0700633 DCHECK(self != nullptr);
634 DCHECK(obj != nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700635 // Allocate and acquire a new monitor.
Andreas Gampe74240812014-04-17 10:35:09 -0700636 Monitor* m = MonitorPool::CreateMonitor(self, owner, obj, hash_code);
637 DCHECK(m != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700638 if (m->Install(self)) {
Haifeng Li86ab7912014-05-16 10:47:59 +0800639 if (owner != nullptr) {
640 VLOG(monitor) << "monitor: thread" << owner->GetThreadId()
Andreas Gampe74240812014-04-17 10:35:09 -0700641 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800642 } else {
643 VLOG(monitor) << "monitor: Inflate with hashcode " << hash_code
Andreas Gampe74240812014-04-17 10:35:09 -0700644 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800645 }
Andreas Gampe74240812014-04-17 10:35:09 -0700646 Runtime::Current()->GetMonitorList()->Add(m);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700647 CHECK_EQ(obj->GetLockWord(true).GetState(), LockWord::kFatLocked);
Andreas Gampe74240812014-04-17 10:35:09 -0700648 } else {
649 MonitorPool::ReleaseMonitor(self, m);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700650 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700651}
652
Mathieu Chartier0cd81352014-05-22 16:48:55 -0700653void Monitor::InflateThinLocked(Thread* self, Handle<mirror::Object> obj, LockWord lock_word,
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700654 uint32_t hash_code) {
655 DCHECK_EQ(lock_word.GetState(), LockWord::kThinLocked);
656 uint32_t owner_thread_id = lock_word.ThinLockOwner();
657 if (owner_thread_id == self->GetThreadId()) {
658 // We own the monitor, we can easily inflate it.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700659 Inflate(self, self, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700660 } else {
661 ThreadList* thread_list = Runtime::Current()->GetThreadList();
662 // Suspend the owner, inflate. First change to blocked and give up mutator_lock_.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700663 self->SetMonitorEnterObject(obj.Get());
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700664 bool timed_out;
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700665 Thread* owner;
666 {
667 ScopedThreadSuspension sts(self, kBlocked);
668 owner = thread_list->SuspendThreadByThreadId(owner_thread_id, false, &timed_out);
669 }
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700670 if (owner != nullptr) {
671 // We succeeded in suspending the thread, check the lock's status didn't change.
672 lock_word = obj->GetLockWord(true);
673 if (lock_word.GetState() == LockWord::kThinLocked &&
674 lock_word.ThinLockOwner() == owner_thread_id) {
675 // Go ahead and inflate the lock.
676 Inflate(self, owner, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700677 }
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700678 thread_list->Resume(owner, false);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700679 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700680 self->SetMonitorEnterObject(nullptr);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700681 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700682}
683
Ian Rogers719d1a32014-03-06 12:13:39 -0800684// Fool annotalysis into thinking that the lock on obj is acquired.
685static mirror::Object* FakeLock(mirror::Object* obj)
686 EXCLUSIVE_LOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
687 return obj;
688}
689
690// Fool annotalysis into thinking that the lock on obj is release.
691static mirror::Object* FakeUnlock(mirror::Object* obj)
692 UNLOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
693 return obj;
694}
695
Mathieu Chartiere7e8a5f2014-02-14 16:59:41 -0800696mirror::Object* Monitor::MonitorEnter(Thread* self, mirror::Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700697 DCHECK(self != nullptr);
698 DCHECK(obj != nullptr);
Mathieu Chartier2d096c92015-10-12 16:18:20 -0700699 self->AssertThreadSuspensionIsAllowable();
Ian Rogers719d1a32014-03-06 12:13:39 -0800700 obj = FakeLock(obj);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700701 uint32_t thread_id = self->GetThreadId();
702 size_t contention_count = 0;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700703 StackHandleScope<1> hs(self);
704 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700705 while (true) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700706 LockWord lock_word = h_obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700707 switch (lock_word.GetState()) {
708 case LockWord::kUnlocked: {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800709 LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0, lock_word.ReadBarrierState()));
Ian Rogers228602f2014-07-10 02:07:54 -0700710 if (h_obj->CasLockWordWeakSequentiallyConsistent(lock_word, thin_locked)) {
Hans Boehm30359612014-05-21 17:46:23 -0700711 // CasLockWord enforces more than the acquire ordering we need here.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700712 return h_obj.Get(); // Success!
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700713 }
714 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -0700715 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700716 case LockWord::kThinLocked: {
717 uint32_t owner_thread_id = lock_word.ThinLockOwner();
718 if (owner_thread_id == thread_id) {
719 // We own the lock, increase the recursion count.
720 uint32_t new_count = lock_word.ThinLockCount() + 1;
721 if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800722 LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count,
723 lock_word.ReadBarrierState()));
724 if (!kUseReadBarrier) {
725 h_obj->SetLockWord(thin_locked, true);
726 return h_obj.Get(); // Success!
727 } else {
728 // Use CAS to preserve the read barrier state.
729 if (h_obj->CasLockWordWeakSequentiallyConsistent(lock_word, thin_locked)) {
730 return h_obj.Get(); // Success!
731 }
732 }
733 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -0700734 } else {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700735 // We'd overflow the recursion count, so inflate the monitor.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700736 InflateThinLocked(self, h_obj, lock_word, 0);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700737 }
738 } else {
739 // Contention.
740 contention_count++;
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700741 Runtime* runtime = Runtime::Current();
742 if (contention_count <= runtime->GetMaxSpinsBeforeThinkLockInflation()) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700743 // TODO: Consider switching the thread state to kBlocked when we are yielding.
Mathieu Chartier251755c2014-07-15 18:10:25 -0700744 // Use sched_yield instead of NanoSleep since NanoSleep can wait much longer than the
745 // parameter you pass in. This can cause thread suspension to take excessively long
Mathieu Chartierb363f662014-07-16 13:28:58 -0700746 // and make long pauses. See b/16307460.
Mathieu Chartier251755c2014-07-15 18:10:25 -0700747 sched_yield();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700748 } else {
749 contention_count = 0;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700750 InflateThinLocked(self, h_obj, lock_word, 0);
Elliott Hughes5f791332011-09-15 17:45:30 -0700751 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700752 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700753 continue; // Start from the beginning.
Elliott Hughes5f791332011-09-15 17:45:30 -0700754 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700755 case LockWord::kFatLocked: {
756 Monitor* mon = lock_word.FatLockMonitor();
757 mon->Lock(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700758 return h_obj.Get(); // Success!
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700759 }
Ian Rogers719d1a32014-03-06 12:13:39 -0800760 case LockWord::kHashCode:
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700761 // Inflate with the existing hashcode.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700762 Inflate(self, nullptr, h_obj.Get(), lock_word.GetHashCode());
Ian Rogers719d1a32014-03-06 12:13:39 -0800763 continue; // Start from the beginning.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700764 default: {
765 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700766 return h_obj.Get();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700767 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700768 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700769 }
770}
771
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800772bool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700773 DCHECK(self != nullptr);
774 DCHECK(obj != nullptr);
Mathieu Chartier2d096c92015-10-12 16:18:20 -0700775 self->AssertThreadSuspensionIsAllowable();
Ian Rogers719d1a32014-03-06 12:13:39 -0800776 obj = FakeUnlock(obj);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700777 StackHandleScope<1> hs(self);
778 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800779 while (true) {
780 LockWord lock_word = obj->GetLockWord(true);
781 switch (lock_word.GetState()) {
782 case LockWord::kHashCode:
783 // Fall-through.
784 case LockWord::kUnlocked:
785 FailedUnlock(h_obj.Get(), self, nullptr, nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700786 return false; // Failure.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800787 case LockWord::kThinLocked: {
788 uint32_t thread_id = self->GetThreadId();
789 uint32_t owner_thread_id = lock_word.ThinLockOwner();
790 if (owner_thread_id != thread_id) {
791 // TODO: there's a race here with the owner dying while we unlock.
792 Thread* owner =
793 Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
794 FailedUnlock(h_obj.Get(), self, owner, nullptr);
795 return false; // Failure.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700796 } else {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800797 // We own the lock, decrease the recursion count.
798 LockWord new_lw = LockWord::Default();
799 if (lock_word.ThinLockCount() != 0) {
800 uint32_t new_count = lock_word.ThinLockCount() - 1;
801 new_lw = LockWord::FromThinLockId(thread_id, new_count, lock_word.ReadBarrierState());
802 } else {
803 new_lw = LockWord::FromDefault(lock_word.ReadBarrierState());
804 }
805 if (!kUseReadBarrier) {
806 DCHECK_EQ(new_lw.ReadBarrierState(), 0U);
807 h_obj->SetLockWord(new_lw, true);
808 // Success!
809 return true;
810 } else {
811 // Use CAS to preserve the read barrier state.
812 if (h_obj->CasLockWordWeakSequentiallyConsistent(lock_word, new_lw)) {
813 // Success!
814 return true;
815 }
816 }
817 continue; // Go again.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700818 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700819 }
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800820 case LockWord::kFatLocked: {
821 Monitor* mon = lock_word.FatLockMonitor();
822 return mon->Unlock(self);
823 }
824 default: {
825 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
826 return false;
827 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700828 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700829 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700830}
831
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800832void Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800833 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700834 DCHECK(self != nullptr);
835 DCHECK(obj != nullptr);
836 LockWord lock_word = obj->GetLockWord(true);
Ian Rogers43c69cc2014-08-15 11:09:28 -0700837 while (lock_word.GetState() != LockWord::kFatLocked) {
838 switch (lock_word.GetState()) {
839 case LockWord::kHashCode:
840 // Fall-through.
841 case LockWord::kUnlocked:
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700842 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
843 return; // Failure.
Ian Rogers43c69cc2014-08-15 11:09:28 -0700844 case LockWord::kThinLocked: {
845 uint32_t thread_id = self->GetThreadId();
846 uint32_t owner_thread_id = lock_word.ThinLockOwner();
847 if (owner_thread_id != thread_id) {
848 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
849 return; // Failure.
850 } else {
851 // We own the lock, inflate to enqueue ourself on the Monitor. May fail spuriously so
852 // re-load.
853 Inflate(self, self, obj, 0);
854 lock_word = obj->GetLockWord(true);
855 }
856 break;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700857 }
Ian Rogers43c69cc2014-08-15 11:09:28 -0700858 case LockWord::kFatLocked: // Unreachable given the loop condition above. Fall-through.
859 default: {
860 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
861 return;
862 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700863 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700864 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700865 Monitor* mon = lock_word.FatLockMonitor();
866 mon->Wait(self, ms, ns, interruptShouldThrow, why);
Elliott Hughes5f791332011-09-15 17:45:30 -0700867}
868
Ian Rogers13c479e2013-10-11 07:59:01 -0700869void Monitor::DoNotify(Thread* self, mirror::Object* obj, bool notify_all) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700870 DCHECK(self != nullptr);
871 DCHECK(obj != nullptr);
872 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700873 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700874 case LockWord::kHashCode:
875 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700876 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800877 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700878 return; // Failure.
879 case LockWord::kThinLocked: {
880 uint32_t thread_id = self->GetThreadId();
881 uint32_t owner_thread_id = lock_word.ThinLockOwner();
882 if (owner_thread_id != thread_id) {
883 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
884 return; // Failure.
885 } else {
886 // We own the lock but there's no Monitor and therefore no waiters.
887 return; // Success.
888 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700889 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700890 case LockWord::kFatLocked: {
891 Monitor* mon = lock_word.FatLockMonitor();
892 if (notify_all) {
893 mon->NotifyAll(self);
894 } else {
895 mon->Notify(self);
896 }
897 return; // Success.
898 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700899 default: {
900 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
901 return;
902 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700903 }
904}
905
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700906uint32_t Monitor::GetLockOwnerThreadId(mirror::Object* obj) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700907 DCHECK(obj != nullptr);
908 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700909 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700910 case LockWord::kHashCode:
911 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700912 case LockWord::kUnlocked:
913 return ThreadList::kInvalidThreadId;
914 case LockWord::kThinLocked:
915 return lock_word.ThinLockOwner();
916 case LockWord::kFatLocked: {
917 Monitor* mon = lock_word.FatLockMonitor();
918 return mon->GetOwnerThreadId();
Elliott Hughes5f791332011-09-15 17:45:30 -0700919 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700920 default: {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700921 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -0700922 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700923 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700924 }
925}
926
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700927void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
Ian Rogersd803bc72014-04-01 15:33:03 -0700928 // Determine the wait message and object we're waiting or blocked upon.
929 mirror::Object* pretty_object = nullptr;
930 const char* wait_message = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700931 uint32_t lock_owner = ThreadList::kInvalidThreadId;
Ian Rogersd803bc72014-04-01 15:33:03 -0700932 ThreadState state = thread->GetState();
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800933 if (state == kWaiting || state == kTimedWaiting || state == kSleeping) {
Ian Rogersd803bc72014-04-01 15:33:03 -0700934 wait_message = (state == kSleeping) ? " - sleeping on " : " - waiting on ";
935 Thread* self = Thread::Current();
936 MutexLock mu(self, *thread->GetWaitMutex());
937 Monitor* monitor = thread->GetWaitMonitor();
938 if (monitor != nullptr) {
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700939 pretty_object = monitor->GetObject();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700940 }
Elliott Hughes34e06962012-04-09 13:55:55 -0700941 } else if (state == kBlocked) {
Ian Rogersd803bc72014-04-01 15:33:03 -0700942 wait_message = " - waiting to lock ";
943 pretty_object = thread->GetMonitorEnterObject();
944 if (pretty_object != nullptr) {
945 lock_owner = pretty_object->GetLockOwnerThreadId();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700946 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700947 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700948
Ian Rogersd803bc72014-04-01 15:33:03 -0700949 if (wait_message != nullptr) {
950 if (pretty_object == nullptr) {
951 os << wait_message << "an unknown object";
952 } else {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700953 if ((pretty_object->GetLockWord(true).GetState() == LockWord::kThinLocked) &&
Ian Rogersd803bc72014-04-01 15:33:03 -0700954 Locks::mutator_lock_->IsExclusiveHeld(Thread::Current())) {
955 // Getting the identity hashcode here would result in lock inflation and suspension of the
956 // current thread, which isn't safe if this is the only runnable thread.
957 os << wait_message << StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)",
958 reinterpret_cast<intptr_t>(pretty_object),
959 PrettyTypeOf(pretty_object).c_str());
960 } else {
961 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
Mathieu Chartier49361592015-01-22 16:36:10 -0800962 // Call PrettyTypeOf before IdentityHashCode since IdentityHashCode can cause thread
963 // suspension and move pretty_object.
964 const std::string pretty_type(PrettyTypeOf(pretty_object));
Ian Rogersd803bc72014-04-01 15:33:03 -0700965 os << wait_message << StringPrintf("<0x%08x> (a %s)", pretty_object->IdentityHashCode(),
Mathieu Chartier49361592015-01-22 16:36:10 -0800966 pretty_type.c_str());
Ian Rogersd803bc72014-04-01 15:33:03 -0700967 }
968 }
969 // - waiting to lock <0x613f83d8> (a java.lang.Object) held by thread 5
970 if (lock_owner != ThreadList::kInvalidThreadId) {
971 os << " held by thread " << lock_owner;
972 }
973 os << "\n";
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700974 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700975}
976
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800977mirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800978 // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
979 // definition of contended that includes a monitor a thread is trying to enter...
Ian Rogersdd7624d2014-03-14 17:43:00 -0700980 mirror::Object* result = thread->GetMonitorEnterObject();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700981 if (result == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700982 // ...but also a monitor that the thread is waiting on.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700983 MutexLock mu(Thread::Current(), *thread->GetWaitMutex());
984 Monitor* monitor = thread->GetWaitMonitor();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700985 if (monitor != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700986 result = monitor->GetObject();
Elliott Hughesf9501702013-01-11 11:22:27 -0800987 }
988 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700989 return result;
Elliott Hughesf9501702013-01-11 11:22:27 -0800990}
991
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800992void Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
Andreas Gampe760172c2014-08-16 13:41:10 -0700993 void* callback_context, bool abort_on_failure) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700994 ArtMethod* m = stack_visitor->GetMethod();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700995 CHECK(m != nullptr);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700996
997 // Native methods are an easy special case.
998 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
999 if (m->IsNative()) {
1000 if (m->IsSynchronized()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001001 mirror::Object* jni_this =
1002 stack_visitor->GetCurrentHandleScope(sizeof(void*))->GetReference(0);
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001003 callback(jni_this, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001004 }
1005 return;
1006 }
1007
jeffhao61f916c2012-10-25 17:48:51 -07001008 // Proxy methods should not be synchronized.
1009 if (m->IsProxyMethod()) {
1010 CHECK(!m->IsSynchronized());
1011 return;
1012 }
1013
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001014 // Is there any reason to believe there's any synchronization in this method?
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001015 const DexFile::CodeItem* code_item = m->GetCodeItem();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001016 CHECK(code_item != nullptr) << PrettyMethod(m);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001017 if (code_item->tries_size_ == 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001018 return; // No "tries" implies no synchronization, so no held locks to report.
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001019 }
1020
Andreas Gampe760172c2014-08-16 13:41:10 -07001021 // Get the dex pc. If abort_on_failure is false, GetDexPc will not abort in the case it cannot
1022 // find the dex pc, and instead return kDexNoIndex. Then bail out, as it indicates we have an
1023 // inconsistent stack anyways.
1024 uint32_t dex_pc = stack_visitor->GetDexPc(abort_on_failure);
1025 if (!abort_on_failure && dex_pc == DexFile::kDexNoIndex) {
1026 LOG(ERROR) << "Could not find dex_pc for " << PrettyMethod(m);
1027 return;
1028 }
1029
Elliott Hughes80537bb2013-01-04 16:37:26 -08001030 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
1031 // the locks held in this stack frame.
1032 std::vector<uint32_t> monitor_enter_dex_pcs;
Andreas Gampe760172c2014-08-16 13:41:10 -07001033 verifier::MethodVerifier::FindLocksAtDexPc(m, dex_pc, &monitor_enter_dex_pcs);
Mathieu Chartiere6a8eec2015-01-06 14:17:57 -08001034 for (uint32_t monitor_dex_pc : monitor_enter_dex_pcs) {
Elliott Hughes80537bb2013-01-04 16:37:26 -08001035 // The verifier works in terms of the dex pcs of the monitor-enter instructions.
1036 // We want the registers used by those instructions (so we can read the values out of them).
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001037 uint16_t monitor_enter_instruction = code_item->insns_[monitor_dex_pc];
Elliott Hughes80537bb2013-01-04 16:37:26 -08001038
1039 // Quick sanity check.
1040 if ((monitor_enter_instruction & 0xff) != Instruction::MONITOR_ENTER) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001041 LOG(FATAL) << "expected monitor-enter @" << monitor_dex_pc << "; was "
Elliott Hughes80537bb2013-01-04 16:37:26 -08001042 << reinterpret_cast<void*>(monitor_enter_instruction);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001043 }
1044
Elliott Hughes80537bb2013-01-04 16:37:26 -08001045 uint16_t monitor_register = ((monitor_enter_instruction >> 8) & 0xff);
Nicolas Geoffray15b9d522015-03-12 15:05:13 +00001046 uint32_t value;
1047 bool success = stack_visitor->GetVReg(m, monitor_register, kReferenceVReg, &value);
1048 CHECK(success) << "Failed to read v" << monitor_register << " of kind "
1049 << kReferenceVReg << " in method " << PrettyMethod(m);
1050 mirror::Object* o = reinterpret_cast<mirror::Object*>(value);
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001051 callback(o, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001052 }
1053}
1054
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001055bool Monitor::IsValidLockWord(LockWord lock_word) {
1056 switch (lock_word.GetState()) {
1057 case LockWord::kUnlocked:
1058 // Nothing to check.
1059 return true;
1060 case LockWord::kThinLocked:
1061 // Basic sanity check of owner.
1062 return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
1063 case LockWord::kFatLocked: {
1064 // Check the monitor appears in the monitor list.
1065 Monitor* mon = lock_word.FatLockMonitor();
1066 MonitorList* list = Runtime::Current()->GetMonitorList();
1067 MutexLock mu(Thread::Current(), list->monitor_list_lock_);
1068 for (Monitor* list_mon : list->list_) {
1069 if (mon == list_mon) {
1070 return true; // Found our monitor.
1071 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001072 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001073 return false; // Fail - unowned monitor in an object.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001074 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001075 case LockWord::kHashCode:
1076 return true;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001077 default:
1078 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001079 UNREACHABLE();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001080 }
1081}
1082
Mathieu Chartier90443472015-07-16 20:32:27 -07001083bool Monitor::IsLocked() SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001084 MutexLock mu(Thread::Current(), monitor_lock_);
1085 return owner_ != nullptr;
1086}
1087
Mathieu Chartiere401d142015-04-22 13:56:20 -07001088void Monitor::TranslateLocation(ArtMethod* method, uint32_t dex_pc,
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001089 const char** source_file, uint32_t* line_number) const {
jeffhao33dc7712011-11-09 17:54:24 -08001090 // If method is null, location is unknown
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001091 if (method == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001092 *source_file = "";
1093 *line_number = 0;
jeffhao33dc7712011-11-09 17:54:24 -08001094 return;
1095 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001096 *source_file = method->GetDeclaringClassSourceFile();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001097 if (*source_file == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001098 *source_file = "";
Elliott Hughes12c51e32012-01-17 20:25:05 -08001099 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001100 *line_number = method->GetLineNumFromDexPC(dex_pc);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001101}
1102
1103uint32_t Monitor::GetOwnerThreadId() {
1104 MutexLock mu(Thread::Current(), monitor_lock_);
1105 Thread* owner = owner_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001106 if (owner != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001107 return owner->GetThreadId();
1108 } else {
1109 return ThreadList::kInvalidThreadId;
1110 }
jeffhao33dc7712011-11-09 17:54:24 -08001111}
1112
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001113MonitorList::MonitorList()
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001114 : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock", kMonitorListLock),
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001115 monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001116}
1117
1118MonitorList::~MonitorList() {
Andreas Gampe74240812014-04-17 10:35:09 -07001119 Thread* self = Thread::Current();
1120 MutexLock mu(self, monitor_list_lock_);
1121 // Release all monitors to the pool.
1122 // TODO: Is it an invariant that *all* open monitors are in the list? Then we could
1123 // clear faster in the pool.
1124 MonitorPool::ReleaseMonitors(self, &list_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001125}
1126
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001127void MonitorList::DisallowNewMonitors() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001128 CHECK(!kUseReadBarrier);
Ian Rogers50b35e22012-10-04 10:09:15 -07001129 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001130 allow_new_monitors_ = false;
1131}
1132
1133void MonitorList::AllowNewMonitors() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001134 CHECK(!kUseReadBarrier);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001135 Thread* self = Thread::Current();
1136 MutexLock mu(self, monitor_list_lock_);
1137 allow_new_monitors_ = true;
1138 monitor_add_condition_.Broadcast(self);
1139}
1140
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001141void MonitorList::BroadcastForNewMonitors() {
1142 CHECK(kUseReadBarrier);
1143 Thread* self = Thread::Current();
1144 MutexLock mu(self, monitor_list_lock_);
1145 monitor_add_condition_.Broadcast(self);
1146}
1147
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001148void MonitorList::Add(Monitor* m) {
1149 Thread* self = Thread::Current();
1150 MutexLock mu(self, monitor_list_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001151 while (UNLIKELY((!kUseReadBarrier && !allow_new_monitors_) ||
1152 (kUseReadBarrier && !self->GetWeakRefAccessEnabled()))) {
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001153 monitor_add_condition_.WaitHoldingLocks(self);
1154 }
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001155 list_.push_front(m);
1156}
1157
Mathieu Chartier97509952015-07-13 14:35:43 -07001158void MonitorList::SweepMonitorList(IsMarkedVisitor* visitor) {
Andreas Gampe74240812014-04-17 10:35:09 -07001159 Thread* self = Thread::Current();
1160 MutexLock mu(self, monitor_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001161 for (auto it = list_.begin(); it != list_.end(); ) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001162 Monitor* m = *it;
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001163 // Disable the read barrier in GetObject() as this is called by GC.
1164 mirror::Object* obj = m->GetObject<kWithoutReadBarrier>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001165 // The object of a monitor can be null if we have deflated it.
Mathieu Chartier97509952015-07-13 14:35:43 -07001166 mirror::Object* new_obj = obj != nullptr ? visitor->IsMarked(obj) : nullptr;
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001167 if (new_obj == nullptr) {
1168 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001169 << obj;
Andreas Gampe74240812014-04-17 10:35:09 -07001170 MonitorPool::ReleaseMonitor(self, m);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001171 it = list_.erase(it);
1172 } else {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001173 m->SetObject(new_obj);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001174 ++it;
1175 }
1176 }
1177}
1178
Mathieu Chartier97509952015-07-13 14:35:43 -07001179class MonitorDeflateVisitor : public IsMarkedVisitor {
1180 public:
1181 MonitorDeflateVisitor() : self_(Thread::Current()), deflate_count_(0) {}
1182
1183 virtual mirror::Object* IsMarked(mirror::Object* object) OVERRIDE
Mathieu Chartier90443472015-07-16 20:32:27 -07001184 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001185 if (Monitor::Deflate(self_, object)) {
1186 DCHECK_NE(object->GetLockWord(true).GetState(), LockWord::kFatLocked);
1187 ++deflate_count_;
1188 // If we deflated, return null so that the monitor gets removed from the array.
1189 return nullptr;
1190 }
1191 return object; // Monitor was not deflated.
1192 }
1193
1194 Thread* const self_;
1195 size_t deflate_count_;
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001196};
1197
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001198size_t MonitorList::DeflateMonitors() {
Mathieu Chartier97509952015-07-13 14:35:43 -07001199 MonitorDeflateVisitor visitor;
1200 Locks::mutator_lock_->AssertExclusiveHeld(visitor.self_);
1201 SweepMonitorList(&visitor);
1202 return visitor.deflate_count_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001203}
1204
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001205MonitorInfo::MonitorInfo(mirror::Object* obj) : owner_(nullptr), entry_count_(0) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001206 DCHECK(obj != nullptr);
1207 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001208 switch (lock_word.GetState()) {
1209 case LockWord::kUnlocked:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001210 // Fall-through.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001211 case LockWord::kForwardingAddress:
1212 // Fall-through.
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001213 case LockWord::kHashCode:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001214 break;
1215 case LockWord::kThinLocked:
1216 owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
1217 entry_count_ = 1 + lock_word.ThinLockCount();
1218 // Thin locks have no waiters.
1219 break;
1220 case LockWord::kFatLocked: {
1221 Monitor* mon = lock_word.FatLockMonitor();
1222 owner_ = mon->owner_;
1223 entry_count_ = 1 + mon->lock_count_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001224 for (Thread* waiter = mon->wait_set_; waiter != nullptr; waiter = waiter->GetWaitNext()) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001225 waiters_.push_back(waiter);
1226 }
1227 break;
Elliott Hughesf327e072013-01-09 16:01:26 -08001228 }
1229 }
1230}
1231
Elliott Hughes5f791332011-09-15 17:45:30 -07001232} // namespace art