blob: bb330478951fad8f993c8ed32a332b1df5f2784c [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
Elliott Hughes08fc03a2012-06-26 17:34:00 -070019#include <vector>
20
Andreas Gampe46ee31b2016-12-14 10:11:49 -080021#include "android-base/stringprintf.h"
22
Mathieu Chartiere401d142015-04-22 13:56:20 -070023#include "art_method-inl.h"
Elliott Hughes76b61672012-12-12 17:47:30 -080024#include "base/mutex.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080025#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080026#include "base/systrace.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"
Sebastien Hertz0f7c9332015-11-05 15:57:30 +010030#include "dex_instruction-inl.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"
Mathieu Chartier0795f232016-09-27 18:43:30 -070034#include "scoped_thread_state_change-inl.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070035#include "thread.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070036#include "thread_list.h"
Elliott Hughes08fc03a2012-06-26 17:34:00 -070037#include "verifier/method_verifier.h"
Elliott Hughes044288f2012-06-25 14:46:39 -070038#include "well_known_classes.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070039
40namespace art {
41
Andreas Gampe46ee31b2016-12-14 10:11:49 -080042using android::base::StringPrintf;
43
Mathieu Chartierb9001ab2014-10-03 13:28:46 -070044static constexpr uint64_t kLongWaitMs = 100;
45
Elliott Hughes5f791332011-09-15 17:45:30 -070046/*
Ian Rogersd9c4fc92013-10-01 19:45:43 -070047 * Every Object has a monitor associated with it, but not every Object is actually locked. Even
48 * the ones that are locked do not need a full-fledged monitor until a) there is actual contention
49 * or b) wait() is called on the Object.
Elliott Hughes5f791332011-09-15 17:45:30 -070050 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070051 * For Android, we have implemented a scheme similar to the one described in Bacon et al.'s
52 * "Thin locks: featherweight synchronization for Java" (ACM 1998). Things are even easier for us,
53 * though, because we have a full 32 bits to work with.
Elliott Hughes5f791332011-09-15 17:45:30 -070054 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070055 * The two states of an Object's lock are referred to as "thin" and "fat". A lock may transition
56 * from the "thin" state to the "fat" state and this transition is referred to as inflation. Once
57 * a lock has been inflated it remains in the "fat" state indefinitely.
Elliott Hughes5f791332011-09-15 17:45:30 -070058 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070059 * The lock value itself is stored in mirror::Object::monitor_ and the representation is described
60 * in the LockWord value type.
Elliott Hughes54e7df12011-09-16 11:47:04 -070061 *
Elliott Hughes5f791332011-09-15 17:45:30 -070062 * Monitors provide:
63 * - mutually exclusive access to resources
64 * - a way for multiple threads to wait for notification
65 *
66 * In effect, they fill the role of both mutexes and condition variables.
67 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070068 * Only one thread can own the monitor at any time. There may be several threads waiting on it
69 * (the wait call unlocks it). One or more waiting threads may be getting interrupted or notified
70 * at any given time.
Elliott Hughes5f791332011-09-15 17:45:30 -070071 */
Elliott Hughes54e7df12011-09-16 11:47:04 -070072
Elliott Hughesfc861622011-10-17 17:57:47 -070073uint32_t Monitor::lock_profiling_threshold_ = 0;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070074
Calin Juravleb2771b42016-04-07 17:09:25 +010075void Monitor::Init(uint32_t lock_profiling_threshold) {
Elliott Hughesfc861622011-10-17 17:57:47 -070076 lock_profiling_threshold_ = lock_profiling_threshold;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070077}
78
Ian Rogersef7d42f2014-01-06 12:55:46 -080079Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code)
Ian Rogers00f7d0e2012-07-19 15:28:27 -070080 : monitor_lock_("a monitor lock", kMonitorLock),
Ian Rogersd9c4fc92013-10-01 19:45:43 -070081 monitor_contenders_("monitor contenders", monitor_lock_),
Mathieu Chartier46bc7782013-11-12 17:03:02 -080082 num_waiters_(0),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070083 owner_(owner),
Elliott Hughes5f791332011-09-15 17:45:30 -070084 lock_count_(0),
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070085 obj_(GcRoot<mirror::Object>(obj)),
Mathieu Chartier2cebb242015-04-21 16:50:40 -070086 wait_set_(nullptr),
Mathieu Chartierad2541a2013-10-25 10:05:23 -070087 hash_code_(hash_code),
Mathieu Chartier2cebb242015-04-21 16:50:40 -070088 locking_method_(nullptr),
Ian Rogersef7d42f2014-01-06 12:55:46 -080089 locking_dex_pc_(0),
Andreas Gampe74240812014-04-17 10:35:09 -070090 monitor_id_(MonitorPool::ComputeMonitorId(this, self)) {
91#ifdef __LP64__
92 DCHECK(false) << "Should not be reached in 64b";
93 next_free_ = nullptr;
94#endif
95 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
96 // with the owner unlocking the thin-lock.
97 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
98 // The identity hash code is set for the life time of the monitor.
99}
100
101Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code,
102 MonitorId id)
103 : monitor_lock_("a monitor lock", kMonitorLock),
104 monitor_contenders_("monitor contenders", monitor_lock_),
105 num_waiters_(0),
106 owner_(owner),
107 lock_count_(0),
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700108 obj_(GcRoot<mirror::Object>(obj)),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700109 wait_set_(nullptr),
Andreas Gampe74240812014-04-17 10:35:09 -0700110 hash_code_(hash_code),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700111 locking_method_(nullptr),
Andreas Gampe74240812014-04-17 10:35:09 -0700112 locking_dex_pc_(0),
113 monitor_id_(id) {
114#ifdef __LP64__
115 next_free_ = nullptr;
116#endif
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700117 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
118 // with the owner unlocking the thin-lock.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800119 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700120 // The identity hash code is set for the life time of the monitor.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700121}
122
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700123int32_t Monitor::GetHashCode() {
124 while (!HasHashCode()) {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700125 if (hash_code_.CompareExchangeWeakRelaxed(0, mirror::Object::GenerateIdentityHashCode())) {
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700126 break;
127 }
128 }
129 DCHECK(HasHashCode());
Ian Rogers3e5cf302014-05-20 16:40:37 -0700130 return hash_code_.LoadRelaxed();
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700131}
132
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700133bool Monitor::Install(Thread* self) {
134 MutexLock mu(self, monitor_lock_); // Uncontended mutex acquisition as monitor isn't yet public.
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700135 CHECK(owner_ == nullptr || owner_ == self || owner_->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700136 // Propagate the lock state.
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700137 LockWord lw(GetObject()->GetLockWord(false));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700138 switch (lw.GetState()) {
139 case LockWord::kThinLocked: {
140 CHECK_EQ(owner_->GetThreadId(), lw.ThinLockOwner());
141 lock_count_ = lw.ThinLockCount();
142 break;
143 }
144 case LockWord::kHashCode: {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700145 CHECK_EQ(hash_code_.LoadRelaxed(), static_cast<int32_t>(lw.GetHashCode()));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700146 break;
147 }
148 case LockWord::kFatLocked: {
149 // The owner_ is suspended but another thread beat us to install a monitor.
150 return false;
151 }
152 case LockWord::kUnlocked: {
153 LOG(FATAL) << "Inflating unlocked lock word";
154 break;
155 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700156 default: {
157 LOG(FATAL) << "Invalid monitor state " << lw.GetState();
158 return false;
159 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700160 }
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700161 LockWord fat(this, lw.GCState());
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700162 // Publish the updated lock word, which may race with other threads.
Hans Boehmb3da36c2016-12-15 13:12:59 -0800163 bool success = GetObject()->CasLockWordWeakRelease(lw, fat);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700164 // Lock profiling.
Mathieu Chartier9728f912013-10-30 09:45:13 -0700165 if (success && owner_ != nullptr && lock_profiling_threshold_ != 0) {
Andreas Gampe6ec8ebd2014-07-25 13:36:56 -0700166 // Do not abort on dex pc errors. This can easily happen when we want to dump a stack trace on
167 // abort.
168 locking_method_ = owner_->GetCurrentMethod(&locking_dex_pc_, false);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700169 }
170 return success;
Elliott Hughes5f791332011-09-15 17:45:30 -0700171}
172
173Monitor::~Monitor() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700174 // Deflated monitors have a null object.
Elliott Hughes5f791332011-09-15 17:45:30 -0700175}
176
Elliott Hughes5f791332011-09-15 17:45:30 -0700177void Monitor::AppendToWaitSet(Thread* thread) {
178 DCHECK(owner_ == Thread::Current());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700179 DCHECK(thread != nullptr);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700180 DCHECK(thread->GetWaitNext() == nullptr) << thread->GetWaitNext();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700181 if (wait_set_ == nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700182 wait_set_ = thread;
183 return;
184 }
185
186 // push_back.
187 Thread* t = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700188 while (t->GetWaitNext() != nullptr) {
189 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700190 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700191 t->SetWaitNext(thread);
Elliott Hughes5f791332011-09-15 17:45:30 -0700192}
193
Elliott Hughes5f791332011-09-15 17:45:30 -0700194void Monitor::RemoveFromWaitSet(Thread *thread) {
195 DCHECK(owner_ == Thread::Current());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700196 DCHECK(thread != nullptr);
197 if (wait_set_ == nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700198 return;
199 }
200 if (wait_set_ == thread) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700201 wait_set_ = thread->GetWaitNext();
202 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700203 return;
204 }
205
206 Thread* t = wait_set_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700207 while (t->GetWaitNext() != nullptr) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700208 if (t->GetWaitNext() == thread) {
209 t->SetWaitNext(thread->GetWaitNext());
210 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700211 return;
212 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700213 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700214 }
215}
216
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700217void Monitor::SetObject(mirror::Object* object) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700218 obj_ = GcRoot<mirror::Object>(object);
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700219}
220
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700221// Note: Adapted from CurrentMethodVisitor in thread.cc. We must not resolve here.
222
223struct NthCallerWithDexPcVisitor FINAL : public StackVisitor {
224 explicit NthCallerWithDexPcVisitor(Thread* thread, size_t frame)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700225 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +0100226 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700227 method_(nullptr),
228 dex_pc_(0),
229 current_frame_number_(0),
230 wanted_frame_number_(frame) {}
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700231 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700232 ArtMethod* m = GetMethod();
233 if (m == nullptr || m->IsRuntimeMethod()) {
234 // Runtime method, upcall, or resolution issue. Skip.
235 return true;
236 }
237
238 // Is this the requested frame?
239 if (current_frame_number_ == wanted_frame_number_) {
240 method_ = m;
241 dex_pc_ = GetDexPc(false /* abort_on_error*/);
242 return false;
243 }
244
245 // Look for more.
246 current_frame_number_++;
247 return true;
248 }
249
250 ArtMethod* method_;
251 uint32_t dex_pc_;
252
253 private:
254 size_t current_frame_number_;
255 const size_t wanted_frame_number_;
256};
257
258// This function is inlined and just helps to not have the VLOG and ATRACE check at all the
259// potential tracing points.
260void Monitor::AtraceMonitorLock(Thread* self, mirror::Object* obj, bool is_wait) {
261 if (UNLIKELY(VLOG_IS_ON(systrace_lock_logging) && ATRACE_ENABLED())) {
262 AtraceMonitorLockImpl(self, obj, is_wait);
263 }
264}
265
266void Monitor::AtraceMonitorLockImpl(Thread* self, mirror::Object* obj, bool is_wait) {
267 // Wait() requires a deeper call stack to be useful. Otherwise you'll see "Waiting at
268 // Object.java". Assume that we'll wait a nontrivial amount, so it's OK to do a longer
269 // stack walk than if !is_wait.
270 NthCallerWithDexPcVisitor visitor(self, is_wait ? 1U : 0U);
271 visitor.WalkStack(false);
272 const char* prefix = is_wait ? "Waiting on " : "Locking ";
273
274 const char* filename;
275 int32_t line_number;
276 TranslateLocation(visitor.method_, visitor.dex_pc_, &filename, &line_number);
277
278 // It would be nice to have a stable "ID" for the object here. However, the only stable thing
279 // would be the identity hashcode. But we cannot use IdentityHashcode here: For one, there are
280 // times when it is unsafe to make that call (see stack dumping for an explanation). More
281 // importantly, we would have to give up on thin-locking when adding systrace locks, as the
282 // identity hashcode is stored in the lockword normally (so can't be used with thin-locks).
283 //
284 // Because of thin-locks we also cannot use the monitor id (as there is no monitor). Monitor ids
285 // also do not have to be stable, as the monitor may be deflated.
286 std::string tmp = StringPrintf("%s %d at %s:%d",
287 prefix,
288 (obj == nullptr ? -1 : static_cast<int32_t>(reinterpret_cast<uintptr_t>(obj))),
289 (filename != nullptr ? filename : "null"),
290 line_number);
291 ATRACE_BEGIN(tmp.c_str());
292}
293
294void Monitor::AtraceMonitorUnlock() {
295 if (UNLIKELY(VLOG_IS_ON(systrace_lock_logging))) {
296 ATRACE_END();
297 }
298}
299
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700300std::string Monitor::PrettyContentionInfo(const std::string& owner_name,
301 pid_t owner_tid,
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700302 ArtMethod* owners_method,
303 uint32_t owners_dex_pc,
304 size_t num_waiters) {
Hiroshi Yamauchi71cd68d2017-01-25 18:28:12 -0800305 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700306 const char* owners_filename;
Goran Jakovljevic49c882b2016-04-19 10:27:21 +0200307 int32_t owners_line_number = 0;
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700308 if (owners_method != nullptr) {
309 TranslateLocation(owners_method, owners_dex_pc, &owners_filename, &owners_line_number);
310 }
311 std::ostringstream oss;
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700312 oss << "monitor contention with owner " << owner_name << " (" << owner_tid << ")";
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700313 if (owners_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700314 oss << " at " << owners_method->PrettyMethod();
Mathieu Chartier36891fe2016-04-28 17:21:08 -0700315 oss << "(" << owners_filename << ":" << owners_line_number << ")";
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700316 }
317 oss << " waiters=" << num_waiters;
318 return oss.str();
319}
320
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700321bool Monitor::TryLockLocked(Thread* self) {
322 if (owner_ == nullptr) { // Unowned.
323 owner_ = self;
324 CHECK_EQ(lock_count_, 0);
325 // When debugging, save the current monitor holder for future
326 // acquisition failures to use in sampled logging.
327 if (lock_profiling_threshold_ != 0) {
328 locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
329 }
330 } else if (owner_ == self) { // Recursive.
331 lock_count_++;
332 } else {
333 return false;
334 }
335 AtraceMonitorLock(self, GetObject(), false /* is_wait */);
336 return true;
337}
338
339bool Monitor::TryLock(Thread* self) {
340 MutexLock mu(self, monitor_lock_);
341 return TryLockLocked(self);
342}
343
Elliott Hughes5f791332011-09-15 17:45:30 -0700344void Monitor::Lock(Thread* self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700345 MutexLock mu(self, monitor_lock_);
346 while (true) {
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700347 if (TryLockLocked(self)) {
348 return;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700349 }
350 // Contended.
351 const bool log_contention = (lock_profiling_threshold_ != 0);
Xin Guanb894a192014-08-22 11:55:37 -0500352 uint64_t wait_start_ms = log_contention ? MilliTime() : 0;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700353 ArtMethod* owners_method = locking_method_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700354 uint32_t owners_dex_pc = locking_dex_pc_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700355 // Do this before releasing the lock so that we don't get deflated.
Mathieu Chartierb9001ab2014-10-03 13:28:46 -0700356 size_t num_waiters = num_waiters_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700357 ++num_waiters_;
Andreas Gampe2702d562017-02-06 09:48:00 -0800358
359 // If systrace logging is enabled, first look at the lock owner. Acquiring the monitor's
360 // lock and then re-acquiring the mutator lock can deadlock.
361 bool started_trace = false;
362 if (ATRACE_ENABLED()) {
363 if (owner_ != nullptr) { // Did the owner_ give the lock up?
364 std::ostringstream oss;
365 std::string name;
366 owner_->GetThreadName(name);
367 oss << PrettyContentionInfo(name,
368 owner_->GetTid(),
369 owners_method,
370 owners_dex_pc,
371 num_waiters);
372 // Add info for contending thread.
373 uint32_t pc;
374 ArtMethod* m = self->GetCurrentMethod(&pc);
375 const char* filename;
376 int32_t line_number;
377 TranslateLocation(m, pc, &filename, &line_number);
378 oss << " blocking from "
379 << ArtMethod::PrettyMethod(m) << "(" << (filename != nullptr ? filename : "null")
380 << ":" << line_number << ")";
381 ATRACE_BEGIN(oss.str().c_str());
382 started_trace = true;
383 }
384 }
385
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700386 monitor_lock_.Unlock(self); // Let go of locks in order.
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700387 self->SetMonitorEnterObject(GetObject());
Elliott Hughes5f791332011-09-15 17:45:30 -0700388 {
Hiroshi Yamauchi71cd68d2017-01-25 18:28:12 -0800389 ScopedThreadSuspension tsc(self, kBlocked); // Change to blocked and give up mutator_lock_.
Andreas Gampe2702d562017-02-06 09:48:00 -0800390 uint32_t original_owner_thread_id = 0u;
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700391 {
392 // Reacquire monitor_lock_ without mutator_lock_ for Wait.
393 MutexLock mu2(self, monitor_lock_);
394 if (owner_ != nullptr) { // Did the owner_ give the lock up?
395 original_owner_thread_id = owner_->GetThreadId();
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700396 monitor_contenders_.Wait(self); // Still contended so wait.
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800397 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700398 }
399 if (original_owner_thread_id != 0u) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700400 // Woken from contention.
401 if (log_contention) {
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700402 uint32_t original_owner_tid = 0;
403 std::string original_owner_name;
404 {
405 MutexLock mu2(Thread::Current(), *Locks::thread_list_lock_);
406 // Re-find the owner in case the thread got killed.
407 Thread* original_owner = Runtime::Current()->GetThreadList()->FindThreadByThreadId(
408 original_owner_thread_id);
409 // Do not do any work that requires the mutator lock.
410 if (original_owner != nullptr) {
411 original_owner_tid = original_owner->GetTid();
412 original_owner->GetThreadName(original_owner_name);
413 }
414 }
415
416 if (original_owner_tid != 0u) {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700417 uint64_t wait_ms = MilliTime() - wait_start_ms;
418 uint32_t sample_percent;
419 if (wait_ms >= lock_profiling_threshold_) {
420 sample_percent = 100;
421 } else {
422 sample_percent = 100 * wait_ms / lock_profiling_threshold_;
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700423 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700424 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
Hiroshi Yamauchi71cd68d2017-01-25 18:28:12 -0800425 // Reacquire mutator_lock_ for logging.
426 ScopedObjectAccess soa(self);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700427 if (wait_ms > kLongWaitMs && owners_method != nullptr) {
Mathieu Chartier36891fe2016-04-28 17:21:08 -0700428 uint32_t pc;
429 ArtMethod* m = self->GetCurrentMethod(&pc);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700430 // TODO: We should maybe check that original_owner is still a live thread.
431 LOG(WARNING) << "Long "
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700432 << PrettyContentionInfo(original_owner_name,
433 original_owner_tid,
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700434 owners_method,
435 owners_dex_pc,
436 num_waiters)
David Sehr709b0702016-10-13 09:12:37 -0700437 << " in " << ArtMethod::PrettyMethod(m) << " for "
438 << PrettyDuration(MsToNs(wait_ms));
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700439 }
440 const char* owners_filename;
441 int32_t owners_line_number;
442 TranslateLocation(owners_method,
443 owners_dex_pc,
444 &owners_filename,
445 &owners_line_number);
446 LogContentionEvent(self,
447 wait_ms,
448 sample_percent,
449 owners_filename,
450 owners_line_number);
451 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700452 }
453 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700454 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700455 }
Andreas Gampe2702d562017-02-06 09:48:00 -0800456 if (started_trace) {
457 ATRACE_END();
458 }
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700459 self->SetMonitorEnterObject(nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700460 monitor_lock_.Lock(self); // Reacquire locks in order.
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700461 --num_waiters_;
Elliott Hughesfc861622011-10-17 17:57:47 -0700462 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700463}
464
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800465static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
466 __attribute__((format(printf, 1, 2)));
467
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700468static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700469 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800470 va_list args;
471 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800472 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000473 self->ThrowNewExceptionV("Ljava/lang/IllegalMonitorStateException;", fmt, args);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700474 if (!Runtime::Current()->IsStarted() || VLOG_IS_ON(monitor)) {
Brian Carlstrom64277f32012-03-26 23:53:34 -0700475 std::ostringstream ss;
Ian Rogers62d6c772013-02-27 08:32:07 -0800476 self->Dump(ss);
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700477 LOG(Runtime::Current()->IsStarted() ? ::android::base::INFO : ::android::base::ERROR)
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000478 << self->GetException()->Dump() << "\n" << ss.str();
Brian Carlstrom64277f32012-03-26 23:53:34 -0700479 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800480 va_end(args);
481}
482
Elliott Hughesd4237412012-02-21 11:24:45 -0800483static std::string ThreadToString(Thread* thread) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700484 if (thread == nullptr) {
485 return "nullptr";
Elliott Hughesd4237412012-02-21 11:24:45 -0800486 }
487 std::ostringstream oss;
488 // TODO: alternatively, we could just return the thread's name.
489 oss << *thread;
490 return oss.str();
491}
492
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700493void Monitor::FailedUnlock(mirror::Object* o,
494 uint32_t expected_owner_thread_id,
495 uint32_t found_owner_thread_id,
Elliott Hughesffb465f2012-03-01 18:46:05 -0800496 Monitor* monitor) {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700497 // Acquire thread list lock so threads won't disappear from under us.
Elliott Hughesffb465f2012-03-01 18:46:05 -0800498 std::string current_owner_string;
499 std::string expected_owner_string;
500 std::string found_owner_string;
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700501 uint32_t current_owner_thread_id = 0u;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800502 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700503 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700504 ThreadList* const thread_list = Runtime::Current()->GetThreadList();
505 Thread* expected_owner = thread_list->FindThreadByThreadId(expected_owner_thread_id);
506 Thread* found_owner = thread_list->FindThreadByThreadId(found_owner_thread_id);
507
Elliott Hughesffb465f2012-03-01 18:46:05 -0800508 // Re-read owner now that we hold lock.
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700509 Thread* current_owner = (monitor != nullptr) ? monitor->GetOwner() : nullptr;
510 if (current_owner != nullptr) {
511 current_owner_thread_id = current_owner->GetThreadId();
512 }
Elliott Hughesffb465f2012-03-01 18:46:05 -0800513 // Get short descriptions of the threads involved.
514 current_owner_string = ThreadToString(current_owner);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700515 expected_owner_string = expected_owner != nullptr ? ThreadToString(expected_owner) : "unnamed";
516 found_owner_string = found_owner != nullptr ? ThreadToString(found_owner) : "unnamed";
Elliott Hughesffb465f2012-03-01 18:46:05 -0800517 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700518
519 if (current_owner_thread_id == 0u) {
520 if (found_owner_thread_id == 0u) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800521 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
522 " on thread '%s'",
David Sehr709b0702016-10-13 09:12:37 -0700523 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800524 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800525 } else {
526 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800527 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
528 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800529 found_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700530 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800531 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800532 }
533 } else {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700534 if (found_owner_thread_id == 0u) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800535 // Race: originally there was no owner, there is now
536 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
537 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800538 current_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700539 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800540 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800541 } else {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700542 if (found_owner_thread_id != current_owner_thread_id) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800543 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800544 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
545 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800546 found_owner_string.c_str(),
547 current_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700548 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800549 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800550 } else {
551 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
552 " on thread '%s",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800553 current_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700554 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800555 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800556 }
557 }
558 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700559}
560
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700561bool Monitor::Unlock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700562 DCHECK(self != nullptr);
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700563 uint32_t owner_thread_id = 0u;
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700564 {
565 MutexLock mu(self, monitor_lock_);
566 Thread* owner = owner_;
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700567 if (owner != nullptr) {
568 owner_thread_id = owner->GetThreadId();
569 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700570 if (owner == self) {
571 // We own the monitor, so nobody else can be in here.
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700572 AtraceMonitorUnlock();
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700573 if (lock_count_ == 0) {
574 owner_ = nullptr;
575 locking_method_ = nullptr;
576 locking_dex_pc_ = 0;
577 // Wake a contender.
578 monitor_contenders_.Signal(self);
579 } else {
580 --lock_count_;
581 }
582 return true;
Elliott Hughes5f791332011-09-15 17:45:30 -0700583 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700584 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700585 // We don't own this, so we're not allowed to unlock it.
586 // The JNI spec says that we should throw IllegalMonitorStateException in this case.
587 FailedUnlock(GetObject(), self->GetThreadId(), owner_thread_id, this);
588 return false;
Elliott Hughes5f791332011-09-15 17:45:30 -0700589}
590
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800591void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
592 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700593 DCHECK(self != nullptr);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800594 DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
Elliott Hughes5f791332011-09-15 17:45:30 -0700595
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700596 monitor_lock_.Lock(self);
597
Elliott Hughes5f791332011-09-15 17:45:30 -0700598 // Make sure that we hold the lock.
599 if (owner_ != self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700600 monitor_lock_.Unlock(self);
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700601 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700602 return;
603 }
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800604
Elliott Hughesdf42c482013-01-09 12:49:02 -0800605 // We need to turn a zero-length timed wait into a regular wait because
606 // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
607 if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
608 why = kWaiting;
609 }
610
Elliott Hughes5f791332011-09-15 17:45:30 -0700611 // Enforce the timeout range.
612 if (ms < 0 || ns < 0 || ns > 999999) {
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700613 monitor_lock_.Unlock(self);
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000614 self->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
Ian Rogersef7d42f2014-01-06 12:55:46 -0800615 "timeout arguments out of range: ms=%" PRId64 " ns=%d", ms, ns);
Elliott Hughes5f791332011-09-15 17:45:30 -0700616 return;
617 }
618
Elliott Hughes5f791332011-09-15 17:45:30 -0700619 /*
620 * Add ourselves to the set of threads waiting on this monitor, and
621 * release our hold. We need to let it go even if we're a few levels
622 * deep in a recursive lock, and we need to restore that later.
623 *
624 * We append to the wait set ahead of clearing the count and owner
625 * fields so the subroutine can check that the calling thread owns
626 * the monitor. Aside from that, the order of member updates is
627 * not order sensitive as we hold the pthread mutex.
628 */
629 AppendToWaitSet(self);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700630 ++num_waiters_;
Ian Rogers0399dde2012-06-06 17:09:28 -0700631 int prev_lock_count = lock_count_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700632 lock_count_ = 0;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700633 owner_ = nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700634 ArtMethod* saved_method = locking_method_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700635 locking_method_ = nullptr;
Ian Rogers0399dde2012-06-06 17:09:28 -0700636 uintptr_t saved_dex_pc = locking_dex_pc_;
637 locking_dex_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700638
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700639 AtraceMonitorUnlock(); // For the implict Unlock() just above. This will only end the deepest
640 // nesting, but that is enough for the visualization, and corresponds to
641 // the single Lock() we do afterwards.
642 AtraceMonitorLock(self, GetObject(), true /* is_wait */);
643
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800644 bool was_interrupted = false;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700645 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700646 // Update thread state. If the GC wakes up, it'll ignore us, knowing
647 // that we won't touch any references in this state, and we'll check
648 // our suspend mode before we transition out.
649 ScopedThreadSuspension sts(self, why);
650
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700651 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700652 MutexLock mu(self, *self->GetWaitMutex());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700653
654 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700655 // non-null a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700656 // up.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700657 DCHECK(self->GetWaitMonitor() == nullptr);
658 self->SetWaitMonitor(this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700659
660 // Release the monitor lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700661 monitor_contenders_.Signal(self);
662 monitor_lock_.Unlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700663
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800664 // Handle the case where the thread was interrupted before we called wait().
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000665 if (self->IsInterrupted()) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800666 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700667 } else {
668 // Wait for a notification or a timeout to occur.
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800669 if (why == kWaiting) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700670 self->GetWaitConditionVariable()->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700671 } else {
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800672 DCHECK(why == kTimedWaiting || why == kSleeping) << why;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700673 self->GetWaitConditionVariable()->TimedWait(self, ms, ns);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700674 }
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000675 was_interrupted = self->IsInterrupted();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700676 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700677 }
678
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800679 {
680 // We reset the thread's wait_monitor_ field after transitioning back to runnable so
681 // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
682 // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
683 // are waiting on "null".)
Ian Rogersdd7624d2014-03-14 17:43:00 -0700684 MutexLock mu(self, *self->GetWaitMutex());
685 DCHECK(self->GetWaitMonitor() != nullptr);
686 self->SetWaitMonitor(nullptr);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800687 }
688
Mathieu Chartierdaed5d82016-03-10 10:49:35 -0800689 // Allocate the interrupted exception not holding the monitor lock since it may cause a GC.
690 // If the GC requires acquiring the monitor for enqueuing cleared references, this would
691 // cause a deadlock if the monitor is held.
692 if (was_interrupted && interruptShouldThrow) {
693 /*
694 * We were interrupted while waiting, or somebody interrupted an
695 * un-interruptible thread earlier and we're bailing out immediately.
696 *
697 * The doc sayeth: "The interrupted status of the current thread is
698 * cleared when this exception is thrown."
699 */
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000700 self->SetInterrupted(false);
Mathieu Chartierdaed5d82016-03-10 10:49:35 -0800701 self->ThrowNewException("Ljava/lang/InterruptedException;", nullptr);
702 }
703
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700704 AtraceMonitorUnlock(); // End Wait().
705
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700706 // Re-acquire the monitor and lock.
Elliott Hughes5f791332011-09-15 17:45:30 -0700707 Lock(self);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700708 monitor_lock_.Lock(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700709 self->GetWaitMutex()->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700710
Elliott Hughes5f791332011-09-15 17:45:30 -0700711 /*
712 * We remove our thread from wait set after restoring the count
713 * and owner fields so the subroutine can check that the calling
714 * thread owns the monitor. Aside from that, the order of member
715 * updates is not order sensitive as we hold the pthread mutex.
716 */
717 owner_ = self;
Ian Rogers0399dde2012-06-06 17:09:28 -0700718 lock_count_ = prev_lock_count;
719 locking_method_ = saved_method;
720 locking_dex_pc_ = saved_dex_pc;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700721 --num_waiters_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700722 RemoveFromWaitSet(self);
723
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700724 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700725}
726
727void Monitor::Notify(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700728 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700729 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700730 // Make sure that we hold the lock.
731 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800732 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700733 return;
734 }
735 // Signal the first waiting thread in the wait set.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700736 while (wait_set_ != nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700737 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700738 wait_set_ = thread->GetWaitNext();
739 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700740
741 // Check to see if the thread is still waiting.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800742 MutexLock wait_mu(self, *thread->GetWaitMutex());
Ian Rogersdd7624d2014-03-14 17:43:00 -0700743 if (thread->GetWaitMonitor() != nullptr) {
744 thread->GetWaitConditionVariable()->Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700745 return;
746 }
747 }
748}
749
750void Monitor::NotifyAll(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700751 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700752 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700753 // Make sure that we hold the lock.
754 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800755 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700756 return;
757 }
758 // Signal all threads in the wait set.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700759 while (wait_set_ != nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700760 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700761 wait_set_ = thread->GetWaitNext();
762 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700763 thread->Notify();
764 }
765}
766
Mathieu Chartier590fee92013-09-13 13:46:47 -0700767bool Monitor::Deflate(Thread* self, mirror::Object* obj) {
768 DCHECK(obj != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700769 // Don't need volatile since we only deflate with mutators suspended.
770 LockWord lw(obj->GetLockWord(false));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700771 // If the lock isn't an inflated monitor, then we don't need to deflate anything.
772 if (lw.GetState() == LockWord::kFatLocked) {
773 Monitor* monitor = lw.FatLockMonitor();
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700774 DCHECK(monitor != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700775 MutexLock mu(self, monitor->monitor_lock_);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700776 // Can't deflate if we have anybody waiting on the CV.
777 if (monitor->num_waiters_ > 0) {
778 return false;
779 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700780 Thread* owner = monitor->owner_;
781 if (owner != nullptr) {
782 // Can't deflate if we are locked and have a hash code.
783 if (monitor->HasHashCode()) {
784 return false;
785 }
786 // Can't deflate if our lock count is too high.
Mathieu Chartier1cf194f2016-11-01 20:13:24 -0700787 if (static_cast<uint32_t>(monitor->lock_count_) > LockWord::kThinLockMaxCount) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700788 return false;
789 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700790 // Deflate to a thin lock.
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700791 LockWord new_lw = LockWord::FromThinLockId(owner->GetThreadId(),
792 monitor->lock_count_,
793 lw.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800794 // Assume no concurrent read barrier state changes as mutators are suspended.
795 obj->SetLockWord(new_lw, false);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700796 VLOG(monitor) << "Deflated " << obj << " to thin lock " << owner->GetTid() << " / "
797 << monitor->lock_count_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700798 } else if (monitor->HasHashCode()) {
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700799 LockWord new_lw = LockWord::FromHashCode(monitor->GetHashCode(), lw.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800800 // Assume no concurrent read barrier state changes as mutators are suspended.
801 obj->SetLockWord(new_lw, false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700802 VLOG(monitor) << "Deflated " << obj << " to hash monitor " << monitor->GetHashCode();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700803 } else {
804 // No lock and no hash, just put an empty lock word inside the object.
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700805 LockWord new_lw = LockWord::FromDefault(lw.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800806 // Assume no concurrent read barrier state changes as mutators are suspended.
807 obj->SetLockWord(new_lw, false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700808 VLOG(monitor) << "Deflated" << obj << " to empty lock word";
Mathieu Chartier590fee92013-09-13 13:46:47 -0700809 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700810 // 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 -0700811 // next GC.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700812 monitor->obj_ = GcRoot<mirror::Object>(nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700813 }
814 return true;
815}
816
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700817void Monitor::Inflate(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code) {
Andreas Gampe74240812014-04-17 10:35:09 -0700818 DCHECK(self != nullptr);
819 DCHECK(obj != nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700820 // Allocate and acquire a new monitor.
Andreas Gampe74240812014-04-17 10:35:09 -0700821 Monitor* m = MonitorPool::CreateMonitor(self, owner, obj, hash_code);
822 DCHECK(m != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700823 if (m->Install(self)) {
Haifeng Li86ab7912014-05-16 10:47:59 +0800824 if (owner != nullptr) {
825 VLOG(monitor) << "monitor: thread" << owner->GetThreadId()
Andreas Gampe74240812014-04-17 10:35:09 -0700826 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800827 } else {
828 VLOG(monitor) << "monitor: Inflate with hashcode " << hash_code
Andreas Gampe74240812014-04-17 10:35:09 -0700829 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800830 }
Andreas Gampe74240812014-04-17 10:35:09 -0700831 Runtime::Current()->GetMonitorList()->Add(m);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700832 CHECK_EQ(obj->GetLockWord(true).GetState(), LockWord::kFatLocked);
Andreas Gampe74240812014-04-17 10:35:09 -0700833 } else {
834 MonitorPool::ReleaseMonitor(self, m);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700835 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700836}
837
Mathieu Chartier0cd81352014-05-22 16:48:55 -0700838void Monitor::InflateThinLocked(Thread* self, Handle<mirror::Object> obj, LockWord lock_word,
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700839 uint32_t hash_code) {
840 DCHECK_EQ(lock_word.GetState(), LockWord::kThinLocked);
841 uint32_t owner_thread_id = lock_word.ThinLockOwner();
842 if (owner_thread_id == self->GetThreadId()) {
843 // We own the monitor, we can easily inflate it.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700844 Inflate(self, self, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700845 } else {
846 ThreadList* thread_list = Runtime::Current()->GetThreadList();
847 // Suspend the owner, inflate. First change to blocked and give up mutator_lock_.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700848 self->SetMonitorEnterObject(obj.Get());
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700849 bool timed_out;
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700850 Thread* owner;
851 {
852 ScopedThreadSuspension sts(self, kBlocked);
853 owner = thread_list->SuspendThreadByThreadId(owner_thread_id, false, &timed_out);
854 }
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700855 if (owner != nullptr) {
856 // We succeeded in suspending the thread, check the lock's status didn't change.
857 lock_word = obj->GetLockWord(true);
858 if (lock_word.GetState() == LockWord::kThinLocked &&
859 lock_word.ThinLockOwner() == owner_thread_id) {
860 // Go ahead and inflate the lock.
861 Inflate(self, owner, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700862 }
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700863 thread_list->Resume(owner, false);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700864 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700865 self->SetMonitorEnterObject(nullptr);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700866 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700867}
868
Ian Rogers719d1a32014-03-06 12:13:39 -0800869// Fool annotalysis into thinking that the lock on obj is acquired.
870static mirror::Object* FakeLock(mirror::Object* obj)
871 EXCLUSIVE_LOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
872 return obj;
873}
874
875// Fool annotalysis into thinking that the lock on obj is release.
876static mirror::Object* FakeUnlock(mirror::Object* obj)
877 UNLOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
878 return obj;
879}
880
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700881mirror::Object* Monitor::MonitorEnter(Thread* self, mirror::Object* obj, bool trylock) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700882 DCHECK(self != nullptr);
883 DCHECK(obj != nullptr);
Mathieu Chartier2d096c92015-10-12 16:18:20 -0700884 self->AssertThreadSuspensionIsAllowable();
Ian Rogers719d1a32014-03-06 12:13:39 -0800885 obj = FakeLock(obj);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700886 uint32_t thread_id = self->GetThreadId();
887 size_t contention_count = 0;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700888 StackHandleScope<1> hs(self);
889 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700890 while (true) {
Hans Boehmb3da36c2016-12-15 13:12:59 -0800891 // We initially read the lockword with ordinary Java/relaxed semantics. When stronger
892 // semantics are needed, we address it below. Since GetLockWord bottoms out to a relaxed load,
893 // we can fix it later, in an infrequently executed case, with a fence.
894 LockWord lock_word = h_obj->GetLockWord(false);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700895 switch (lock_word.GetState()) {
896 case LockWord::kUnlocked: {
Hans Boehmb3da36c2016-12-15 13:12:59 -0800897 // No ordering required for preceding lockword read, since we retest.
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700898 LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0, lock_word.GCState()));
Hans Boehmb3da36c2016-12-15 13:12:59 -0800899 if (h_obj->CasLockWordWeakAcquire(lock_word, thin_locked)) {
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700900 AtraceMonitorLock(self, h_obj.Get(), false /* is_wait */);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700901 return h_obj.Get(); // Success!
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700902 }
903 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -0700904 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700905 case LockWord::kThinLocked: {
906 uint32_t owner_thread_id = lock_word.ThinLockOwner();
907 if (owner_thread_id == thread_id) {
Hans Boehmb3da36c2016-12-15 13:12:59 -0800908 // No ordering required for initial lockword read.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700909 // We own the lock, increase the recursion count.
910 uint32_t new_count = lock_word.ThinLockCount() + 1;
911 if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700912 LockWord thin_locked(LockWord::FromThinLockId(thread_id,
913 new_count,
914 lock_word.GCState()));
Hans Boehmb3da36c2016-12-15 13:12:59 -0800915 // Only this thread pays attention to the count. Thus there is no need for stronger
916 // than relaxed memory ordering.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800917 if (!kUseReadBarrier) {
Hans Boehmb3da36c2016-12-15 13:12:59 -0800918 h_obj->SetLockWord(thin_locked, false /* volatile */);
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700919 AtraceMonitorLock(self, h_obj.Get(), false /* is_wait */);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800920 return h_obj.Get(); // Success!
921 } else {
922 // Use CAS to preserve the read barrier state.
Hans Boehmb3da36c2016-12-15 13:12:59 -0800923 if (h_obj->CasLockWordWeakRelaxed(lock_word, thin_locked)) {
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700924 AtraceMonitorLock(self, h_obj.Get(), false /* is_wait */);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800925 return h_obj.Get(); // Success!
926 }
927 }
928 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -0700929 } else {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700930 // We'd overflow the recursion count, so inflate the monitor.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700931 InflateThinLocked(self, h_obj, lock_word, 0);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700932 }
933 } else {
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700934 if (trylock) {
935 return nullptr;
936 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700937 // Contention.
938 contention_count++;
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700939 Runtime* runtime = Runtime::Current();
Hans Boehmb3da36c2016-12-15 13:12:59 -0800940 if (contention_count <= runtime->GetMaxSpinsBeforeThinLockInflation()) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700941 // TODO: Consider switching the thread state to kBlocked when we are yielding.
Mathieu Chartier251755c2014-07-15 18:10:25 -0700942 // Use sched_yield instead of NanoSleep since NanoSleep can wait much longer than the
943 // parameter you pass in. This can cause thread suspension to take excessively long
Mathieu Chartierb363f662014-07-16 13:28:58 -0700944 // and make long pauses. See b/16307460.
Hans Boehmb3da36c2016-12-15 13:12:59 -0800945 // TODO: We should literally spin first, without sched_yield. Sched_yield either does
946 // nothing (at significant expense), or guarantees that we wait at least microseconds.
947 // If the owner is running, I would expect the median lock hold time to be hundreds
948 // of nanoseconds or less.
Mathieu Chartier251755c2014-07-15 18:10:25 -0700949 sched_yield();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700950 } else {
951 contention_count = 0;
Hans Boehmb3da36c2016-12-15 13:12:59 -0800952 // No ordering required for initial lockword read. Install rereads it anyway.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700953 InflateThinLocked(self, h_obj, lock_word, 0);
Elliott Hughes5f791332011-09-15 17:45:30 -0700954 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700955 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700956 continue; // Start from the beginning.
Elliott Hughes5f791332011-09-15 17:45:30 -0700957 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700958 case LockWord::kFatLocked: {
Hans Boehmb3da36c2016-12-15 13:12:59 -0800959 // We should have done an acquire read of the lockword initially, to ensure
960 // visibility of the monitor data structure. Use an explicit fence instead.
961 QuasiAtomic::ThreadFenceAcquire();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700962 Monitor* mon = lock_word.FatLockMonitor();
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700963 if (trylock) {
964 return mon->TryLock(self) ? h_obj.Get() : nullptr;
965 } else {
966 mon->Lock(self);
967 return h_obj.Get(); // Success!
968 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700969 }
Ian Rogers719d1a32014-03-06 12:13:39 -0800970 case LockWord::kHashCode:
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700971 // Inflate with the existing hashcode.
Hans Boehmb3da36c2016-12-15 13:12:59 -0800972 // Again no ordering required for initial lockword read, since we don't rely
973 // on the visibility of any prior computation.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700974 Inflate(self, nullptr, h_obj.Get(), lock_word.GetHashCode());
Ian Rogers719d1a32014-03-06 12:13:39 -0800975 continue; // Start from the beginning.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700976 default: {
977 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700978 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700979 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700980 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700981 }
982}
983
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800984bool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700985 DCHECK(self != nullptr);
986 DCHECK(obj != nullptr);
Mathieu Chartier2d096c92015-10-12 16:18:20 -0700987 self->AssertThreadSuspensionIsAllowable();
Ian Rogers719d1a32014-03-06 12:13:39 -0800988 obj = FakeUnlock(obj);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700989 StackHandleScope<1> hs(self);
990 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800991 while (true) {
992 LockWord lock_word = obj->GetLockWord(true);
993 switch (lock_word.GetState()) {
994 case LockWord::kHashCode:
995 // Fall-through.
996 case LockWord::kUnlocked:
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700997 FailedUnlock(h_obj.Get(), self->GetThreadId(), 0u, nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700998 return false; // Failure.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800999 case LockWord::kThinLocked: {
1000 uint32_t thread_id = self->GetThreadId();
1001 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1002 if (owner_thread_id != thread_id) {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -07001003 FailedUnlock(h_obj.Get(), thread_id, owner_thread_id, nullptr);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001004 return false; // Failure.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001005 } else {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001006 // We own the lock, decrease the recursion count.
1007 LockWord new_lw = LockWord::Default();
1008 if (lock_word.ThinLockCount() != 0) {
1009 uint32_t new_count = lock_word.ThinLockCount() - 1;
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001010 new_lw = LockWord::FromThinLockId(thread_id, new_count, lock_word.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001011 } else {
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001012 new_lw = LockWord::FromDefault(lock_word.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001013 }
1014 if (!kUseReadBarrier) {
1015 DCHECK_EQ(new_lw.ReadBarrierState(), 0U);
Hans Boehmb3da36c2016-12-15 13:12:59 -08001016 // TODO: This really only needs memory_order_release, but we currently have
1017 // no way to specify that. In fact there seem to be no legitimate uses of SetLockWord
1018 // with a final argument of true. This slows down x86 and ARMv7, but probably not v8.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001019 h_obj->SetLockWord(new_lw, true);
Andreas Gampe6e759ad2016-05-17 10:13:10 -07001020 AtraceMonitorUnlock();
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001021 // Success!
1022 return true;
1023 } else {
1024 // Use CAS to preserve the read barrier state.
Hans Boehmb3da36c2016-12-15 13:12:59 -08001025 if (h_obj->CasLockWordWeakRelease(lock_word, new_lw)) {
Andreas Gampe6e759ad2016-05-17 10:13:10 -07001026 AtraceMonitorUnlock();
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001027 // Success!
1028 return true;
1029 }
1030 }
1031 continue; // Go again.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001032 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001033 }
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001034 case LockWord::kFatLocked: {
1035 Monitor* mon = lock_word.FatLockMonitor();
1036 return mon->Unlock(self);
1037 }
1038 default: {
1039 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1040 return false;
1041 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001042 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001043 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001044}
1045
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001046void Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
Elliott Hughes4cd121e2013-01-07 17:35:41 -08001047 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001048 DCHECK(self != nullptr);
1049 DCHECK(obj != nullptr);
1050 LockWord lock_word = obj->GetLockWord(true);
Ian Rogers43c69cc2014-08-15 11:09:28 -07001051 while (lock_word.GetState() != LockWord::kFatLocked) {
1052 switch (lock_word.GetState()) {
1053 case LockWord::kHashCode:
1054 // Fall-through.
1055 case LockWord::kUnlocked:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001056 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
1057 return; // Failure.
Ian Rogers43c69cc2014-08-15 11:09:28 -07001058 case LockWord::kThinLocked: {
1059 uint32_t thread_id = self->GetThreadId();
1060 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1061 if (owner_thread_id != thread_id) {
1062 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
1063 return; // Failure.
1064 } else {
1065 // We own the lock, inflate to enqueue ourself on the Monitor. May fail spuriously so
1066 // re-load.
1067 Inflate(self, self, obj, 0);
1068 lock_word = obj->GetLockWord(true);
1069 }
1070 break;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001071 }
Ian Rogers43c69cc2014-08-15 11:09:28 -07001072 case LockWord::kFatLocked: // Unreachable given the loop condition above. Fall-through.
1073 default: {
1074 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1075 return;
1076 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001077 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001078 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001079 Monitor* mon = lock_word.FatLockMonitor();
1080 mon->Wait(self, ms, ns, interruptShouldThrow, why);
Elliott Hughes5f791332011-09-15 17:45:30 -07001081}
1082
Ian Rogers13c479e2013-10-11 07:59:01 -07001083void Monitor::DoNotify(Thread* self, mirror::Object* obj, bool notify_all) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001084 DCHECK(self != nullptr);
1085 DCHECK(obj != nullptr);
1086 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001087 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001088 case LockWord::kHashCode:
1089 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001090 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -08001091 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001092 return; // Failure.
1093 case LockWord::kThinLocked: {
1094 uint32_t thread_id = self->GetThreadId();
1095 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1096 if (owner_thread_id != thread_id) {
1097 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
1098 return; // Failure.
1099 } else {
1100 // We own the lock but there's no Monitor and therefore no waiters.
1101 return; // Success.
1102 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001103 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001104 case LockWord::kFatLocked: {
1105 Monitor* mon = lock_word.FatLockMonitor();
1106 if (notify_all) {
1107 mon->NotifyAll(self);
1108 } else {
1109 mon->Notify(self);
1110 }
1111 return; // Success.
1112 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001113 default: {
1114 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1115 return;
1116 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001117 }
1118}
1119
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001120uint32_t Monitor::GetLockOwnerThreadId(mirror::Object* obj) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001121 DCHECK(obj != nullptr);
1122 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001123 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001124 case LockWord::kHashCode:
1125 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001126 case LockWord::kUnlocked:
1127 return ThreadList::kInvalidThreadId;
1128 case LockWord::kThinLocked:
1129 return lock_word.ThinLockOwner();
1130 case LockWord::kFatLocked: {
1131 Monitor* mon = lock_word.FatLockMonitor();
1132 return mon->GetOwnerThreadId();
Elliott Hughes5f791332011-09-15 17:45:30 -07001133 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001134 default: {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001135 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001136 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001137 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001138 }
1139}
1140
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001141void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
Ian Rogersd803bc72014-04-01 15:33:03 -07001142 // Determine the wait message and object we're waiting or blocked upon.
1143 mirror::Object* pretty_object = nullptr;
1144 const char* wait_message = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001145 uint32_t lock_owner = ThreadList::kInvalidThreadId;
Ian Rogersd803bc72014-04-01 15:33:03 -07001146 ThreadState state = thread->GetState();
Elliott Hughesb4e94fd2013-01-08 14:41:26 -08001147 if (state == kWaiting || state == kTimedWaiting || state == kSleeping) {
Ian Rogersd803bc72014-04-01 15:33:03 -07001148 wait_message = (state == kSleeping) ? " - sleeping on " : " - waiting on ";
1149 Thread* self = Thread::Current();
1150 MutexLock mu(self, *thread->GetWaitMutex());
1151 Monitor* monitor = thread->GetWaitMonitor();
1152 if (monitor != nullptr) {
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001153 pretty_object = monitor->GetObject();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001154 }
Elliott Hughes34e06962012-04-09 13:55:55 -07001155 } else if (state == kBlocked) {
Ian Rogersd803bc72014-04-01 15:33:03 -07001156 wait_message = " - waiting to lock ";
1157 pretty_object = thread->GetMonitorEnterObject();
1158 if (pretty_object != nullptr) {
Hiroshi Yamauchi7b08ae42016-10-04 15:20:36 -07001159 if (kUseReadBarrier && Thread::Current()->GetIsGcMarking()) {
1160 // We may call Thread::Dump() in the middle of the CC thread flip and this thread's stack
1161 // may have not been flipped yet and "pretty_object" may be a from-space (stale) ref, in
1162 // which case the GetLockOwnerThreadId() call below will crash. So explicitly mark/forward
1163 // it here.
1164 pretty_object = ReadBarrier::Mark(pretty_object);
1165 }
Ian Rogersd803bc72014-04-01 15:33:03 -07001166 lock_owner = pretty_object->GetLockOwnerThreadId();
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001167 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001168 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001169
Ian Rogersd803bc72014-04-01 15:33:03 -07001170 if (wait_message != nullptr) {
1171 if (pretty_object == nullptr) {
1172 os << wait_message << "an unknown object";
1173 } else {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001174 if ((pretty_object->GetLockWord(true).GetState() == LockWord::kThinLocked) &&
Ian Rogersd803bc72014-04-01 15:33:03 -07001175 Locks::mutator_lock_->IsExclusiveHeld(Thread::Current())) {
1176 // Getting the identity hashcode here would result in lock inflation and suspension of the
1177 // current thread, which isn't safe if this is the only runnable thread.
1178 os << wait_message << StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)",
1179 reinterpret_cast<intptr_t>(pretty_object),
David Sehr709b0702016-10-13 09:12:37 -07001180 pretty_object->PrettyTypeOf().c_str());
Ian Rogersd803bc72014-04-01 15:33:03 -07001181 } else {
1182 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
Mathieu Chartier49361592015-01-22 16:36:10 -08001183 // Call PrettyTypeOf before IdentityHashCode since IdentityHashCode can cause thread
1184 // suspension and move pretty_object.
David Sehr709b0702016-10-13 09:12:37 -07001185 const std::string pretty_type(pretty_object->PrettyTypeOf());
Ian Rogersd803bc72014-04-01 15:33:03 -07001186 os << wait_message << StringPrintf("<0x%08x> (a %s)", pretty_object->IdentityHashCode(),
Mathieu Chartier49361592015-01-22 16:36:10 -08001187 pretty_type.c_str());
Ian Rogersd803bc72014-04-01 15:33:03 -07001188 }
1189 }
1190 // - waiting to lock <0x613f83d8> (a java.lang.Object) held by thread 5
1191 if (lock_owner != ThreadList::kInvalidThreadId) {
1192 os << " held by thread " << lock_owner;
1193 }
1194 os << "\n";
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001195 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001196}
1197
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001198mirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -08001199 // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
1200 // definition of contended that includes a monitor a thread is trying to enter...
Ian Rogersdd7624d2014-03-14 17:43:00 -07001201 mirror::Object* result = thread->GetMonitorEnterObject();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001202 if (result == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001203 // ...but also a monitor that the thread is waiting on.
Ian Rogersdd7624d2014-03-14 17:43:00 -07001204 MutexLock mu(Thread::Current(), *thread->GetWaitMutex());
1205 Monitor* monitor = thread->GetWaitMonitor();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001206 if (monitor != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001207 result = monitor->GetObject();
Elliott Hughesf9501702013-01-11 11:22:27 -08001208 }
1209 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001210 return result;
Elliott Hughesf9501702013-01-11 11:22:27 -08001211}
1212
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001213void Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
Andreas Gampe760172c2014-08-16 13:41:10 -07001214 void* callback_context, bool abort_on_failure) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001215 ArtMethod* m = stack_visitor->GetMethod();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001216 CHECK(m != nullptr);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001217
1218 // Native methods are an easy special case.
1219 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
1220 if (m->IsNative()) {
1221 if (m->IsSynchronized()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001222 mirror::Object* jni_this =
1223 stack_visitor->GetCurrentHandleScope(sizeof(void*))->GetReference(0);
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001224 callback(jni_this, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001225 }
1226 return;
1227 }
1228
jeffhao61f916c2012-10-25 17:48:51 -07001229 // Proxy methods should not be synchronized.
1230 if (m->IsProxyMethod()) {
1231 CHECK(!m->IsSynchronized());
1232 return;
1233 }
1234
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001235 // Is there any reason to believe there's any synchronization in this method?
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001236 const DexFile::CodeItem* code_item = m->GetCodeItem();
David Sehr709b0702016-10-13 09:12:37 -07001237 CHECK(code_item != nullptr) << m->PrettyMethod();
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001238 if (code_item->tries_size_ == 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001239 return; // No "tries" implies no synchronization, so no held locks to report.
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001240 }
1241
Andreas Gampe760172c2014-08-16 13:41:10 -07001242 // Get the dex pc. If abort_on_failure is false, GetDexPc will not abort in the case it cannot
1243 // find the dex pc, and instead return kDexNoIndex. Then bail out, as it indicates we have an
1244 // inconsistent stack anyways.
1245 uint32_t dex_pc = stack_visitor->GetDexPc(abort_on_failure);
1246 if (!abort_on_failure && dex_pc == DexFile::kDexNoIndex) {
David Sehr709b0702016-10-13 09:12:37 -07001247 LOG(ERROR) << "Could not find dex_pc for " << m->PrettyMethod();
Andreas Gampe760172c2014-08-16 13:41:10 -07001248 return;
1249 }
1250
Elliott Hughes80537bb2013-01-04 16:37:26 -08001251 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
1252 // the locks held in this stack frame.
1253 std::vector<uint32_t> monitor_enter_dex_pcs;
Andreas Gampe760172c2014-08-16 13:41:10 -07001254 verifier::MethodVerifier::FindLocksAtDexPc(m, dex_pc, &monitor_enter_dex_pcs);
Mathieu Chartiere6a8eec2015-01-06 14:17:57 -08001255 for (uint32_t monitor_dex_pc : monitor_enter_dex_pcs) {
Elliott Hughes80537bb2013-01-04 16:37:26 -08001256 // The verifier works in terms of the dex pcs of the monitor-enter instructions.
1257 // We want the registers used by those instructions (so we can read the values out of them).
Sebastien Hertz0f7c9332015-11-05 15:57:30 +01001258 const Instruction* monitor_enter_instruction =
1259 Instruction::At(&code_item->insns_[monitor_dex_pc]);
Elliott Hughes80537bb2013-01-04 16:37:26 -08001260
1261 // Quick sanity check.
Sebastien Hertz0f7c9332015-11-05 15:57:30 +01001262 CHECK_EQ(monitor_enter_instruction->Opcode(), Instruction::MONITOR_ENTER)
1263 << "expected monitor-enter @" << monitor_dex_pc << "; was "
1264 << reinterpret_cast<const void*>(monitor_enter_instruction);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001265
Sebastien Hertz0f7c9332015-11-05 15:57:30 +01001266 uint16_t monitor_register = monitor_enter_instruction->VRegA();
Nicolas Geoffray15b9d522015-03-12 15:05:13 +00001267 uint32_t value;
1268 bool success = stack_visitor->GetVReg(m, monitor_register, kReferenceVReg, &value);
1269 CHECK(success) << "Failed to read v" << monitor_register << " of kind "
David Sehr709b0702016-10-13 09:12:37 -07001270 << kReferenceVReg << " in method " << m->PrettyMethod();
Nicolas Geoffray15b9d522015-03-12 15:05:13 +00001271 mirror::Object* o = reinterpret_cast<mirror::Object*>(value);
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001272 callback(o, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001273 }
1274}
1275
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001276bool Monitor::IsValidLockWord(LockWord lock_word) {
1277 switch (lock_word.GetState()) {
1278 case LockWord::kUnlocked:
1279 // Nothing to check.
1280 return true;
1281 case LockWord::kThinLocked:
1282 // Basic sanity check of owner.
1283 return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
1284 case LockWord::kFatLocked: {
1285 // Check the monitor appears in the monitor list.
1286 Monitor* mon = lock_word.FatLockMonitor();
1287 MonitorList* list = Runtime::Current()->GetMonitorList();
1288 MutexLock mu(Thread::Current(), list->monitor_list_lock_);
1289 for (Monitor* list_mon : list->list_) {
1290 if (mon == list_mon) {
1291 return true; // Found our monitor.
1292 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001293 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001294 return false; // Fail - unowned monitor in an object.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001295 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001296 case LockWord::kHashCode:
1297 return true;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001298 default:
1299 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001300 UNREACHABLE();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001301 }
1302}
1303
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001304bool Monitor::IsLocked() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001305 MutexLock mu(Thread::Current(), monitor_lock_);
1306 return owner_ != nullptr;
1307}
1308
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -07001309void Monitor::TranslateLocation(ArtMethod* method,
1310 uint32_t dex_pc,
1311 const char** source_file,
1312 int32_t* line_number) {
jeffhao33dc7712011-11-09 17:54:24 -08001313 // If method is null, location is unknown
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001314 if (method == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001315 *source_file = "";
1316 *line_number = 0;
jeffhao33dc7712011-11-09 17:54:24 -08001317 return;
1318 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001319 *source_file = method->GetDeclaringClassSourceFile();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001320 if (*source_file == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001321 *source_file = "";
Elliott Hughes12c51e32012-01-17 20:25:05 -08001322 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001323 *line_number = method->GetLineNumFromDexPC(dex_pc);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001324}
1325
1326uint32_t Monitor::GetOwnerThreadId() {
1327 MutexLock mu(Thread::Current(), monitor_lock_);
1328 Thread* owner = owner_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001329 if (owner != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001330 return owner->GetThreadId();
1331 } else {
1332 return ThreadList::kInvalidThreadId;
1333 }
jeffhao33dc7712011-11-09 17:54:24 -08001334}
1335
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001336MonitorList::MonitorList()
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001337 : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock", kMonitorListLock),
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001338 monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001339}
1340
1341MonitorList::~MonitorList() {
Andreas Gampe74240812014-04-17 10:35:09 -07001342 Thread* self = Thread::Current();
1343 MutexLock mu(self, monitor_list_lock_);
1344 // Release all monitors to the pool.
1345 // TODO: Is it an invariant that *all* open monitors are in the list? Then we could
1346 // clear faster in the pool.
1347 MonitorPool::ReleaseMonitors(self, &list_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001348}
1349
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001350void MonitorList::DisallowNewMonitors() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001351 CHECK(!kUseReadBarrier);
Ian Rogers50b35e22012-10-04 10:09:15 -07001352 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001353 allow_new_monitors_ = false;
1354}
1355
1356void MonitorList::AllowNewMonitors() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001357 CHECK(!kUseReadBarrier);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001358 Thread* self = Thread::Current();
1359 MutexLock mu(self, monitor_list_lock_);
1360 allow_new_monitors_ = true;
1361 monitor_add_condition_.Broadcast(self);
1362}
1363
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001364void MonitorList::BroadcastForNewMonitors() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001365 Thread* self = Thread::Current();
1366 MutexLock mu(self, monitor_list_lock_);
1367 monitor_add_condition_.Broadcast(self);
1368}
1369
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001370void MonitorList::Add(Monitor* m) {
1371 Thread* self = Thread::Current();
1372 MutexLock mu(self, monitor_list_lock_);
Hiroshi Yamauchif1c6f872017-01-06 12:23:47 -08001373 // CMS needs this to block for concurrent reference processing because an object allocated during
1374 // the GC won't be marked and concurrent reference processing would incorrectly clear the JNI weak
1375 // ref. But CC (kUseReadBarrier == true) doesn't because of the to-space invariant.
1376 while (!kUseReadBarrier && UNLIKELY(!allow_new_monitors_)) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -07001377 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
1378 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -08001379 self->CheckEmptyCheckpointFromWeakRefAccess(&monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001380 monitor_add_condition_.WaitHoldingLocks(self);
1381 }
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001382 list_.push_front(m);
1383}
1384
Mathieu Chartier97509952015-07-13 14:35:43 -07001385void MonitorList::SweepMonitorList(IsMarkedVisitor* visitor) {
Andreas Gampe74240812014-04-17 10:35:09 -07001386 Thread* self = Thread::Current();
1387 MutexLock mu(self, monitor_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001388 for (auto it = list_.begin(); it != list_.end(); ) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001389 Monitor* m = *it;
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001390 // Disable the read barrier in GetObject() as this is called by GC.
1391 mirror::Object* obj = m->GetObject<kWithoutReadBarrier>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001392 // The object of a monitor can be null if we have deflated it.
Mathieu Chartier97509952015-07-13 14:35:43 -07001393 mirror::Object* new_obj = obj != nullptr ? visitor->IsMarked(obj) : nullptr;
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001394 if (new_obj == nullptr) {
1395 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001396 << obj;
Andreas Gampe74240812014-04-17 10:35:09 -07001397 MonitorPool::ReleaseMonitor(self, m);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001398 it = list_.erase(it);
1399 } else {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001400 m->SetObject(new_obj);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001401 ++it;
1402 }
1403 }
1404}
1405
Hans Boehm6fe97e02016-05-04 18:35:57 -07001406size_t MonitorList::Size() {
1407 Thread* self = Thread::Current();
1408 MutexLock mu(self, monitor_list_lock_);
1409 return list_.size();
1410}
1411
Mathieu Chartier97509952015-07-13 14:35:43 -07001412class MonitorDeflateVisitor : public IsMarkedVisitor {
1413 public:
1414 MonitorDeflateVisitor() : self_(Thread::Current()), deflate_count_(0) {}
1415
1416 virtual mirror::Object* IsMarked(mirror::Object* object) OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001417 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001418 if (Monitor::Deflate(self_, object)) {
1419 DCHECK_NE(object->GetLockWord(true).GetState(), LockWord::kFatLocked);
1420 ++deflate_count_;
1421 // If we deflated, return null so that the monitor gets removed from the array.
1422 return nullptr;
1423 }
1424 return object; // Monitor was not deflated.
1425 }
1426
1427 Thread* const self_;
1428 size_t deflate_count_;
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001429};
1430
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001431size_t MonitorList::DeflateMonitors() {
Mathieu Chartier97509952015-07-13 14:35:43 -07001432 MonitorDeflateVisitor visitor;
1433 Locks::mutator_lock_->AssertExclusiveHeld(visitor.self_);
1434 SweepMonitorList(&visitor);
1435 return visitor.deflate_count_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001436}
1437
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001438MonitorInfo::MonitorInfo(mirror::Object* obj) : owner_(nullptr), entry_count_(0) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001439 DCHECK(obj != nullptr);
1440 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001441 switch (lock_word.GetState()) {
1442 case LockWord::kUnlocked:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001443 // Fall-through.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001444 case LockWord::kForwardingAddress:
1445 // Fall-through.
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001446 case LockWord::kHashCode:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001447 break;
1448 case LockWord::kThinLocked:
1449 owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
1450 entry_count_ = 1 + lock_word.ThinLockCount();
1451 // Thin locks have no waiters.
1452 break;
1453 case LockWord::kFatLocked: {
1454 Monitor* mon = lock_word.FatLockMonitor();
1455 owner_ = mon->owner_;
1456 entry_count_ = 1 + mon->lock_count_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001457 for (Thread* waiter = mon->wait_set_; waiter != nullptr; waiter = waiter->GetWaitNext()) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001458 waiters_.push_back(waiter);
1459 }
1460 break;
Elliott Hughesf327e072013-01-09 16:01:26 -08001461 }
1462 }
1463}
1464
Elliott Hughes5f791332011-09-15 17:45:30 -07001465} // namespace art