blob: f4700f9619d93f9e87ece4b5594e574e7b493ae2 [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"
Andreas Gampe513061a2017-06-01 09:17:34 -070035#include "stack.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
Andreas Gampe46ee31b2016-12-14 10:11:49 -080043using android::base::StringPrintf;
44
Mathieu Chartierb9001ab2014-10-03 13:28:46 -070045static constexpr uint64_t kLongWaitMs = 100;
46
Elliott Hughes5f791332011-09-15 17:45:30 -070047/*
Ian Rogersd9c4fc92013-10-01 19:45:43 -070048 * Every Object has a monitor associated with it, but not every Object is actually locked. Even
49 * the ones that are locked do not need a full-fledged monitor until a) there is actual contention
50 * or b) wait() is called on the Object.
Elliott Hughes5f791332011-09-15 17:45:30 -070051 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070052 * For Android, we have implemented a scheme similar to the one described in Bacon et al.'s
53 * "Thin locks: featherweight synchronization for Java" (ACM 1998). Things are even easier for us,
54 * though, because we have a full 32 bits to work with.
Elliott Hughes5f791332011-09-15 17:45:30 -070055 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070056 * The two states of an Object's lock are referred to as "thin" and "fat". A lock may transition
57 * from the "thin" state to the "fat" state and this transition is referred to as inflation. Once
58 * a lock has been inflated it remains in the "fat" state indefinitely.
Elliott Hughes5f791332011-09-15 17:45:30 -070059 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070060 * The lock value itself is stored in mirror::Object::monitor_ and the representation is described
61 * in the LockWord value type.
Elliott Hughes54e7df12011-09-16 11:47:04 -070062 *
Elliott Hughes5f791332011-09-15 17:45:30 -070063 * Monitors provide:
64 * - mutually exclusive access to resources
65 * - a way for multiple threads to wait for notification
66 *
67 * In effect, they fill the role of both mutexes and condition variables.
68 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070069 * Only one thread can own the monitor at any time. There may be several threads waiting on it
70 * (the wait call unlocks it). One or more waiting threads may be getting interrupted or notified
71 * at any given time.
Elliott Hughes5f791332011-09-15 17:45:30 -070072 */
Elliott Hughes54e7df12011-09-16 11:47:04 -070073
Elliott Hughesfc861622011-10-17 17:57:47 -070074uint32_t Monitor::lock_profiling_threshold_ = 0;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070075
Calin Juravleb2771b42016-04-07 17:09:25 +010076void Monitor::Init(uint32_t lock_profiling_threshold) {
Elliott Hughesfc861622011-10-17 17:57:47 -070077 lock_profiling_threshold_ = lock_profiling_threshold;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070078}
79
Ian Rogersef7d42f2014-01-06 12:55:46 -080080Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code)
Ian Rogers00f7d0e2012-07-19 15:28:27 -070081 : monitor_lock_("a monitor lock", kMonitorLock),
Ian Rogersd9c4fc92013-10-01 19:45:43 -070082 monitor_contenders_("monitor contenders", monitor_lock_),
Mathieu Chartier46bc7782013-11-12 17:03:02 -080083 num_waiters_(0),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070084 owner_(owner),
Elliott Hughes5f791332011-09-15 17:45:30 -070085 lock_count_(0),
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070086 obj_(GcRoot<mirror::Object>(obj)),
Mathieu Chartier2cebb242015-04-21 16:50:40 -070087 wait_set_(nullptr),
Mathieu Chartierad2541a2013-10-25 10:05:23 -070088 hash_code_(hash_code),
Mathieu Chartier2cebb242015-04-21 16:50:40 -070089 locking_method_(nullptr),
Ian Rogersef7d42f2014-01-06 12:55:46 -080090 locking_dex_pc_(0),
Andreas Gampe74240812014-04-17 10:35:09 -070091 monitor_id_(MonitorPool::ComputeMonitorId(this, self)) {
92#ifdef __LP64__
93 DCHECK(false) << "Should not be reached in 64b";
94 next_free_ = nullptr;
95#endif
96 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
97 // with the owner unlocking the thin-lock.
98 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
99 // The identity hash code is set for the life time of the monitor.
100}
101
102Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code,
103 MonitorId id)
104 : monitor_lock_("a monitor lock", kMonitorLock),
105 monitor_contenders_("monitor contenders", monitor_lock_),
106 num_waiters_(0),
107 owner_(owner),
108 lock_count_(0),
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700109 obj_(GcRoot<mirror::Object>(obj)),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700110 wait_set_(nullptr),
Andreas Gampe74240812014-04-17 10:35:09 -0700111 hash_code_(hash_code),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700112 locking_method_(nullptr),
Andreas Gampe74240812014-04-17 10:35:09 -0700113 locking_dex_pc_(0),
114 monitor_id_(id) {
115#ifdef __LP64__
116 next_free_ = nullptr;
117#endif
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700118 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
119 // with the owner unlocking the thin-lock.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800120 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700121 // The identity hash code is set for the life time of the monitor.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700122}
123
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700124int32_t Monitor::GetHashCode() {
125 while (!HasHashCode()) {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700126 if (hash_code_.CompareExchangeWeakRelaxed(0, mirror::Object::GenerateIdentityHashCode())) {
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700127 break;
128 }
129 }
130 DCHECK(HasHashCode());
Ian Rogers3e5cf302014-05-20 16:40:37 -0700131 return hash_code_.LoadRelaxed();
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700132}
133
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700134bool Monitor::Install(Thread* self) {
135 MutexLock mu(self, monitor_lock_); // Uncontended mutex acquisition as monitor isn't yet public.
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700136 CHECK(owner_ == nullptr || owner_ == self || owner_->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700137 // Propagate the lock state.
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700138 LockWord lw(GetObject()->GetLockWord(false));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700139 switch (lw.GetState()) {
140 case LockWord::kThinLocked: {
141 CHECK_EQ(owner_->GetThreadId(), lw.ThinLockOwner());
142 lock_count_ = lw.ThinLockCount();
143 break;
144 }
145 case LockWord::kHashCode: {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700146 CHECK_EQ(hash_code_.LoadRelaxed(), static_cast<int32_t>(lw.GetHashCode()));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700147 break;
148 }
149 case LockWord::kFatLocked: {
150 // The owner_ is suspended but another thread beat us to install a monitor.
151 return false;
152 }
153 case LockWord::kUnlocked: {
154 LOG(FATAL) << "Inflating unlocked lock word";
155 break;
156 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700157 default: {
158 LOG(FATAL) << "Invalid monitor state " << lw.GetState();
159 return false;
160 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700161 }
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700162 LockWord fat(this, lw.GCState());
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700163 // Publish the updated lock word, which may race with other threads.
Hans Boehmb3da36c2016-12-15 13:12:59 -0800164 bool success = GetObject()->CasLockWordWeakRelease(lw, fat);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700165 // Lock profiling.
Mathieu Chartier9728f912013-10-30 09:45:13 -0700166 if (success && owner_ != nullptr && lock_profiling_threshold_ != 0) {
Andreas Gampe6ec8ebd2014-07-25 13:36:56 -0700167 // Do not abort on dex pc errors. This can easily happen when we want to dump a stack trace on
168 // abort.
169 locking_method_ = owner_->GetCurrentMethod(&locking_dex_pc_, false);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700170 }
171 return success;
Elliott Hughes5f791332011-09-15 17:45:30 -0700172}
173
174Monitor::~Monitor() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700175 // Deflated monitors have a null object.
Elliott Hughes5f791332011-09-15 17:45:30 -0700176}
177
Elliott Hughes5f791332011-09-15 17:45:30 -0700178void Monitor::AppendToWaitSet(Thread* thread) {
179 DCHECK(owner_ == Thread::Current());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700180 DCHECK(thread != nullptr);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700181 DCHECK(thread->GetWaitNext() == nullptr) << thread->GetWaitNext();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700182 if (wait_set_ == nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700183 wait_set_ = thread;
184 return;
185 }
186
187 // push_back.
188 Thread* t = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700189 while (t->GetWaitNext() != nullptr) {
190 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700191 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700192 t->SetWaitNext(thread);
Elliott Hughes5f791332011-09-15 17:45:30 -0700193}
194
Elliott Hughes5f791332011-09-15 17:45:30 -0700195void Monitor::RemoveFromWaitSet(Thread *thread) {
196 DCHECK(owner_ == Thread::Current());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700197 DCHECK(thread != nullptr);
198 if (wait_set_ == nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700199 return;
200 }
201 if (wait_set_ == thread) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700202 wait_set_ = thread->GetWaitNext();
203 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700204 return;
205 }
206
207 Thread* t = wait_set_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700208 while (t->GetWaitNext() != nullptr) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700209 if (t->GetWaitNext() == thread) {
210 t->SetWaitNext(thread->GetWaitNext());
211 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700212 return;
213 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700214 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700215 }
216}
217
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700218void Monitor::SetObject(mirror::Object* object) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700219 obj_ = GcRoot<mirror::Object>(object);
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700220}
221
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700222// Note: Adapted from CurrentMethodVisitor in thread.cc. We must not resolve here.
223
224struct NthCallerWithDexPcVisitor FINAL : public StackVisitor {
225 explicit NthCallerWithDexPcVisitor(Thread* thread, size_t frame)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700226 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +0100227 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700228 method_(nullptr),
229 dex_pc_(0),
230 current_frame_number_(0),
231 wanted_frame_number_(frame) {}
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700232 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700233 ArtMethod* m = GetMethod();
234 if (m == nullptr || m->IsRuntimeMethod()) {
235 // Runtime method, upcall, or resolution issue. Skip.
236 return true;
237 }
238
239 // Is this the requested frame?
240 if (current_frame_number_ == wanted_frame_number_) {
241 method_ = m;
242 dex_pc_ = GetDexPc(false /* abort_on_error*/);
243 return false;
244 }
245
246 // Look for more.
247 current_frame_number_++;
248 return true;
249 }
250
251 ArtMethod* method_;
252 uint32_t dex_pc_;
253
254 private:
255 size_t current_frame_number_;
256 const size_t wanted_frame_number_;
257};
258
259// This function is inlined and just helps to not have the VLOG and ATRACE check at all the
260// potential tracing points.
261void Monitor::AtraceMonitorLock(Thread* self, mirror::Object* obj, bool is_wait) {
262 if (UNLIKELY(VLOG_IS_ON(systrace_lock_logging) && ATRACE_ENABLED())) {
263 AtraceMonitorLockImpl(self, obj, is_wait);
264 }
265}
266
267void Monitor::AtraceMonitorLockImpl(Thread* self, mirror::Object* obj, bool is_wait) {
268 // Wait() requires a deeper call stack to be useful. Otherwise you'll see "Waiting at
269 // Object.java". Assume that we'll wait a nontrivial amount, so it's OK to do a longer
270 // stack walk than if !is_wait.
271 NthCallerWithDexPcVisitor visitor(self, is_wait ? 1U : 0U);
272 visitor.WalkStack(false);
273 const char* prefix = is_wait ? "Waiting on " : "Locking ";
274
275 const char* filename;
276 int32_t line_number;
277 TranslateLocation(visitor.method_, visitor.dex_pc_, &filename, &line_number);
278
279 // It would be nice to have a stable "ID" for the object here. However, the only stable thing
280 // would be the identity hashcode. But we cannot use IdentityHashcode here: For one, there are
281 // times when it is unsafe to make that call (see stack dumping for an explanation). More
282 // importantly, we would have to give up on thin-locking when adding systrace locks, as the
283 // identity hashcode is stored in the lockword normally (so can't be used with thin-locks).
284 //
285 // Because of thin-locks we also cannot use the monitor id (as there is no monitor). Monitor ids
286 // also do not have to be stable, as the monitor may be deflated.
287 std::string tmp = StringPrintf("%s %d at %s:%d",
288 prefix,
289 (obj == nullptr ? -1 : static_cast<int32_t>(reinterpret_cast<uintptr_t>(obj))),
290 (filename != nullptr ? filename : "null"),
291 line_number);
292 ATRACE_BEGIN(tmp.c_str());
293}
294
295void Monitor::AtraceMonitorUnlock() {
296 if (UNLIKELY(VLOG_IS_ON(systrace_lock_logging))) {
297 ATRACE_END();
298 }
299}
300
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700301std::string Monitor::PrettyContentionInfo(const std::string& owner_name,
302 pid_t owner_tid,
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700303 ArtMethod* owners_method,
304 uint32_t owners_dex_pc,
305 size_t num_waiters) {
Hiroshi Yamauchi71cd68d2017-01-25 18:28:12 -0800306 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700307 const char* owners_filename;
Goran Jakovljevic49c882b2016-04-19 10:27:21 +0200308 int32_t owners_line_number = 0;
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700309 if (owners_method != nullptr) {
310 TranslateLocation(owners_method, owners_dex_pc, &owners_filename, &owners_line_number);
311 }
312 std::ostringstream oss;
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700313 oss << "monitor contention with owner " << owner_name << " (" << owner_tid << ")";
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700314 if (owners_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700315 oss << " at " << owners_method->PrettyMethod();
Mathieu Chartier36891fe2016-04-28 17:21:08 -0700316 oss << "(" << owners_filename << ":" << owners_line_number << ")";
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700317 }
318 oss << " waiters=" << num_waiters;
319 return oss.str();
320}
321
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700322bool Monitor::TryLockLocked(Thread* self) {
323 if (owner_ == nullptr) { // Unowned.
324 owner_ = self;
325 CHECK_EQ(lock_count_, 0);
326 // When debugging, save the current monitor holder for future
327 // acquisition failures to use in sampled logging.
328 if (lock_profiling_threshold_ != 0) {
329 locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
330 }
331 } else if (owner_ == self) { // Recursive.
332 lock_count_++;
333 } else {
334 return false;
335 }
336 AtraceMonitorLock(self, GetObject(), false /* is_wait */);
337 return true;
338}
339
340bool Monitor::TryLock(Thread* self) {
341 MutexLock mu(self, monitor_lock_);
342 return TryLockLocked(self);
343}
344
Elliott Hughes5f791332011-09-15 17:45:30 -0700345void Monitor::Lock(Thread* self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700346 MutexLock mu(self, monitor_lock_);
347 while (true) {
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700348 if (TryLockLocked(self)) {
349 return;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700350 }
351 // Contended.
352 const bool log_contention = (lock_profiling_threshold_ != 0);
Xin Guanb894a192014-08-22 11:55:37 -0500353 uint64_t wait_start_ms = log_contention ? MilliTime() : 0;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700354 ArtMethod* owners_method = locking_method_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700355 uint32_t owners_dex_pc = locking_dex_pc_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700356 // Do this before releasing the lock so that we don't get deflated.
Mathieu Chartierb9001ab2014-10-03 13:28:46 -0700357 size_t num_waiters = num_waiters_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700358 ++num_waiters_;
Andreas Gampe2702d562017-02-06 09:48:00 -0800359
360 // If systrace logging is enabled, first look at the lock owner. Acquiring the monitor's
361 // lock and then re-acquiring the mutator lock can deadlock.
362 bool started_trace = false;
363 if (ATRACE_ENABLED()) {
364 if (owner_ != nullptr) { // Did the owner_ give the lock up?
365 std::ostringstream oss;
366 std::string name;
367 owner_->GetThreadName(name);
368 oss << PrettyContentionInfo(name,
369 owner_->GetTid(),
370 owners_method,
371 owners_dex_pc,
372 num_waiters);
373 // Add info for contending thread.
374 uint32_t pc;
375 ArtMethod* m = self->GetCurrentMethod(&pc);
376 const char* filename;
377 int32_t line_number;
378 TranslateLocation(m, pc, &filename, &line_number);
379 oss << " blocking from "
380 << ArtMethod::PrettyMethod(m) << "(" << (filename != nullptr ? filename : "null")
381 << ":" << line_number << ")";
382 ATRACE_BEGIN(oss.str().c_str());
383 started_trace = true;
384 }
385 }
386
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700387 monitor_lock_.Unlock(self); // Let go of locks in order.
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700388 self->SetMonitorEnterObject(GetObject());
Elliott Hughes5f791332011-09-15 17:45:30 -0700389 {
Hiroshi Yamauchi71cd68d2017-01-25 18:28:12 -0800390 ScopedThreadSuspension tsc(self, kBlocked); // Change to blocked and give up mutator_lock_.
Andreas Gampe2702d562017-02-06 09:48:00 -0800391 uint32_t original_owner_thread_id = 0u;
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700392 {
393 // Reacquire monitor_lock_ without mutator_lock_ for Wait.
394 MutexLock mu2(self, monitor_lock_);
395 if (owner_ != nullptr) { // Did the owner_ give the lock up?
396 original_owner_thread_id = owner_->GetThreadId();
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700397 monitor_contenders_.Wait(self); // Still contended so wait.
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800398 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700399 }
400 if (original_owner_thread_id != 0u) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700401 // Woken from contention.
402 if (log_contention) {
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700403 uint32_t original_owner_tid = 0;
404 std::string original_owner_name;
405 {
406 MutexLock mu2(Thread::Current(), *Locks::thread_list_lock_);
407 // Re-find the owner in case the thread got killed.
408 Thread* original_owner = Runtime::Current()->GetThreadList()->FindThreadByThreadId(
409 original_owner_thread_id);
410 // Do not do any work that requires the mutator lock.
411 if (original_owner != nullptr) {
412 original_owner_tid = original_owner->GetTid();
413 original_owner->GetThreadName(original_owner_name);
414 }
415 }
416
417 if (original_owner_tid != 0u) {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700418 uint64_t wait_ms = MilliTime() - wait_start_ms;
419 uint32_t sample_percent;
420 if (wait_ms >= lock_profiling_threshold_) {
421 sample_percent = 100;
422 } else {
423 sample_percent = 100 * wait_ms / lock_profiling_threshold_;
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700424 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700425 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
Hiroshi Yamauchi71cd68d2017-01-25 18:28:12 -0800426 // Reacquire mutator_lock_ for logging.
427 ScopedObjectAccess soa(self);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700428 if (wait_ms > kLongWaitMs && owners_method != nullptr) {
Mathieu Chartier36891fe2016-04-28 17:21:08 -0700429 uint32_t pc;
430 ArtMethod* m = self->GetCurrentMethod(&pc);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700431 // TODO: We should maybe check that original_owner is still a live thread.
432 LOG(WARNING) << "Long "
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700433 << PrettyContentionInfo(original_owner_name,
434 original_owner_tid,
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700435 owners_method,
436 owners_dex_pc,
437 num_waiters)
David Sehr709b0702016-10-13 09:12:37 -0700438 << " in " << ArtMethod::PrettyMethod(m) << " for "
439 << PrettyDuration(MsToNs(wait_ms));
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700440 }
441 const char* owners_filename;
442 int32_t owners_line_number;
443 TranslateLocation(owners_method,
444 owners_dex_pc,
445 &owners_filename,
446 &owners_line_number);
447 LogContentionEvent(self,
448 wait_ms,
449 sample_percent,
450 owners_filename,
451 owners_line_number);
452 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700453 }
454 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700455 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700456 }
Andreas Gampe2702d562017-02-06 09:48:00 -0800457 if (started_trace) {
458 ATRACE_END();
459 }
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700460 self->SetMonitorEnterObject(nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700461 monitor_lock_.Lock(self); // Reacquire locks in order.
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700462 --num_waiters_;
Elliott Hughesfc861622011-10-17 17:57:47 -0700463 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700464}
465
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800466static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
467 __attribute__((format(printf, 1, 2)));
468
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700469static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700470 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800471 va_list args;
472 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800473 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000474 self->ThrowNewExceptionV("Ljava/lang/IllegalMonitorStateException;", fmt, args);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700475 if (!Runtime::Current()->IsStarted() || VLOG_IS_ON(monitor)) {
Brian Carlstrom64277f32012-03-26 23:53:34 -0700476 std::ostringstream ss;
Ian Rogers62d6c772013-02-27 08:32:07 -0800477 self->Dump(ss);
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700478 LOG(Runtime::Current()->IsStarted() ? ::android::base::INFO : ::android::base::ERROR)
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000479 << self->GetException()->Dump() << "\n" << ss.str();
Brian Carlstrom64277f32012-03-26 23:53:34 -0700480 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800481 va_end(args);
482}
483
Elliott Hughesd4237412012-02-21 11:24:45 -0800484static std::string ThreadToString(Thread* thread) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700485 if (thread == nullptr) {
486 return "nullptr";
Elliott Hughesd4237412012-02-21 11:24:45 -0800487 }
488 std::ostringstream oss;
489 // TODO: alternatively, we could just return the thread's name.
490 oss << *thread;
491 return oss.str();
492}
493
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700494void Monitor::FailedUnlock(mirror::Object* o,
495 uint32_t expected_owner_thread_id,
496 uint32_t found_owner_thread_id,
Elliott Hughesffb465f2012-03-01 18:46:05 -0800497 Monitor* monitor) {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700498 // Acquire thread list lock so threads won't disappear from under us.
Elliott Hughesffb465f2012-03-01 18:46:05 -0800499 std::string current_owner_string;
500 std::string expected_owner_string;
501 std::string found_owner_string;
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700502 uint32_t current_owner_thread_id = 0u;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800503 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700504 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700505 ThreadList* const thread_list = Runtime::Current()->GetThreadList();
506 Thread* expected_owner = thread_list->FindThreadByThreadId(expected_owner_thread_id);
507 Thread* found_owner = thread_list->FindThreadByThreadId(found_owner_thread_id);
508
Elliott Hughesffb465f2012-03-01 18:46:05 -0800509 // Re-read owner now that we hold lock.
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700510 Thread* current_owner = (monitor != nullptr) ? monitor->GetOwner() : nullptr;
511 if (current_owner != nullptr) {
512 current_owner_thread_id = current_owner->GetThreadId();
513 }
Elliott Hughesffb465f2012-03-01 18:46:05 -0800514 // Get short descriptions of the threads involved.
515 current_owner_string = ThreadToString(current_owner);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700516 expected_owner_string = expected_owner != nullptr ? ThreadToString(expected_owner) : "unnamed";
517 found_owner_string = found_owner != nullptr ? ThreadToString(found_owner) : "unnamed";
Elliott Hughesffb465f2012-03-01 18:46:05 -0800518 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700519
520 if (current_owner_thread_id == 0u) {
521 if (found_owner_thread_id == 0u) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800522 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
523 " on thread '%s'",
David Sehr709b0702016-10-13 09:12:37 -0700524 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800525 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800526 } else {
527 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800528 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
529 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800530 found_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700531 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800532 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800533 }
534 } else {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700535 if (found_owner_thread_id == 0u) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800536 // Race: originally there was no owner, there is now
537 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
538 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800539 current_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700540 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800541 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800542 } else {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700543 if (found_owner_thread_id != current_owner_thread_id) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800544 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800545 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
546 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800547 found_owner_string.c_str(),
548 current_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700549 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800550 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800551 } else {
552 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
553 " on thread '%s",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800554 current_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700555 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800556 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800557 }
558 }
559 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700560}
561
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700562bool Monitor::Unlock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700563 DCHECK(self != nullptr);
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700564 uint32_t owner_thread_id = 0u;
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700565 {
566 MutexLock mu(self, monitor_lock_);
567 Thread* owner = owner_;
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700568 if (owner != nullptr) {
569 owner_thread_id = owner->GetThreadId();
570 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700571 if (owner == self) {
572 // We own the monitor, so nobody else can be in here.
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700573 AtraceMonitorUnlock();
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700574 if (lock_count_ == 0) {
575 owner_ = nullptr;
576 locking_method_ = nullptr;
577 locking_dex_pc_ = 0;
578 // Wake a contender.
579 monitor_contenders_.Signal(self);
580 } else {
581 --lock_count_;
582 }
583 return true;
Elliott Hughes5f791332011-09-15 17:45:30 -0700584 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700585 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700586 // We don't own this, so we're not allowed to unlock it.
587 // The JNI spec says that we should throw IllegalMonitorStateException in this case.
588 FailedUnlock(GetObject(), self->GetThreadId(), owner_thread_id, this);
589 return false;
Elliott Hughes5f791332011-09-15 17:45:30 -0700590}
591
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800592void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
593 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700594 DCHECK(self != nullptr);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800595 DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
Elliott Hughes5f791332011-09-15 17:45:30 -0700596
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700597 monitor_lock_.Lock(self);
598
Elliott Hughes5f791332011-09-15 17:45:30 -0700599 // Make sure that we hold the lock.
600 if (owner_ != self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700601 monitor_lock_.Unlock(self);
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700602 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700603 return;
604 }
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800605
Elliott Hughesdf42c482013-01-09 12:49:02 -0800606 // We need to turn a zero-length timed wait into a regular wait because
607 // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
608 if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
609 why = kWaiting;
610 }
611
Elliott Hughes5f791332011-09-15 17:45:30 -0700612 // Enforce the timeout range.
613 if (ms < 0 || ns < 0 || ns > 999999) {
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700614 monitor_lock_.Unlock(self);
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000615 self->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
Ian Rogersef7d42f2014-01-06 12:55:46 -0800616 "timeout arguments out of range: ms=%" PRId64 " ns=%d", ms, ns);
Elliott Hughes5f791332011-09-15 17:45:30 -0700617 return;
618 }
619
Elliott Hughes5f791332011-09-15 17:45:30 -0700620 /*
621 * Add ourselves to the set of threads waiting on this monitor, and
622 * release our hold. We need to let it go even if we're a few levels
623 * deep in a recursive lock, and we need to restore that later.
624 *
625 * We append to the wait set ahead of clearing the count and owner
626 * fields so the subroutine can check that the calling thread owns
627 * the monitor. Aside from that, the order of member updates is
628 * not order sensitive as we hold the pthread mutex.
629 */
630 AppendToWaitSet(self);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700631 ++num_waiters_;
Ian Rogers0399dde2012-06-06 17:09:28 -0700632 int prev_lock_count = lock_count_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700633 lock_count_ = 0;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700634 owner_ = nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700635 ArtMethod* saved_method = locking_method_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700636 locking_method_ = nullptr;
Ian Rogers0399dde2012-06-06 17:09:28 -0700637 uintptr_t saved_dex_pc = locking_dex_pc_;
638 locking_dex_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700639
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700640 AtraceMonitorUnlock(); // For the implict Unlock() just above. This will only end the deepest
641 // nesting, but that is enough for the visualization, and corresponds to
642 // the single Lock() we do afterwards.
643 AtraceMonitorLock(self, GetObject(), true /* is_wait */);
644
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800645 bool was_interrupted = false;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700646 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700647 // Update thread state. If the GC wakes up, it'll ignore us, knowing
648 // that we won't touch any references in this state, and we'll check
649 // our suspend mode before we transition out.
650 ScopedThreadSuspension sts(self, why);
651
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700652 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700653 MutexLock mu(self, *self->GetWaitMutex());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700654
655 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700656 // non-null a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700657 // up.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700658 DCHECK(self->GetWaitMonitor() == nullptr);
659 self->SetWaitMonitor(this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700660
661 // Release the monitor lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700662 monitor_contenders_.Signal(self);
663 monitor_lock_.Unlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700664
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800665 // Handle the case where the thread was interrupted before we called wait().
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000666 if (self->IsInterrupted()) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800667 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700668 } else {
669 // Wait for a notification or a timeout to occur.
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800670 if (why == kWaiting) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700671 self->GetWaitConditionVariable()->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700672 } else {
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800673 DCHECK(why == kTimedWaiting || why == kSleeping) << why;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700674 self->GetWaitConditionVariable()->TimedWait(self, ms, ns);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700675 }
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000676 was_interrupted = self->IsInterrupted();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700677 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700678 }
679
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800680 {
681 // We reset the thread's wait_monitor_ field after transitioning back to runnable so
682 // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
683 // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
684 // are waiting on "null".)
Ian Rogersdd7624d2014-03-14 17:43:00 -0700685 MutexLock mu(self, *self->GetWaitMutex());
686 DCHECK(self->GetWaitMonitor() != nullptr);
687 self->SetWaitMonitor(nullptr);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800688 }
689
Mathieu Chartierdaed5d82016-03-10 10:49:35 -0800690 // Allocate the interrupted exception not holding the monitor lock since it may cause a GC.
691 // If the GC requires acquiring the monitor for enqueuing cleared references, this would
692 // cause a deadlock if the monitor is held.
693 if (was_interrupted && interruptShouldThrow) {
694 /*
695 * We were interrupted while waiting, or somebody interrupted an
696 * un-interruptible thread earlier and we're bailing out immediately.
697 *
698 * The doc sayeth: "The interrupted status of the current thread is
699 * cleared when this exception is thrown."
700 */
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000701 self->SetInterrupted(false);
Mathieu Chartierdaed5d82016-03-10 10:49:35 -0800702 self->ThrowNewException("Ljava/lang/InterruptedException;", nullptr);
703 }
704
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700705 AtraceMonitorUnlock(); // End Wait().
706
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700707 // Re-acquire the monitor and lock.
Elliott Hughes5f791332011-09-15 17:45:30 -0700708 Lock(self);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700709 monitor_lock_.Lock(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700710 self->GetWaitMutex()->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700711
Elliott Hughes5f791332011-09-15 17:45:30 -0700712 /*
713 * We remove our thread from wait set after restoring the count
714 * and owner fields so the subroutine can check that the calling
715 * thread owns the monitor. Aside from that, the order of member
716 * updates is not order sensitive as we hold the pthread mutex.
717 */
718 owner_ = self;
Ian Rogers0399dde2012-06-06 17:09:28 -0700719 lock_count_ = prev_lock_count;
720 locking_method_ = saved_method;
721 locking_dex_pc_ = saved_dex_pc;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700722 --num_waiters_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700723 RemoveFromWaitSet(self);
724
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700725 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700726}
727
728void Monitor::Notify(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700729 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700730 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700731 // Make sure that we hold the lock.
732 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800733 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700734 return;
735 }
736 // Signal the first waiting thread in the wait set.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700737 while (wait_set_ != nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700738 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700739 wait_set_ = thread->GetWaitNext();
740 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700741
742 // Check to see if the thread is still waiting.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800743 MutexLock wait_mu(self, *thread->GetWaitMutex());
Ian Rogersdd7624d2014-03-14 17:43:00 -0700744 if (thread->GetWaitMonitor() != nullptr) {
745 thread->GetWaitConditionVariable()->Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700746 return;
747 }
748 }
749}
750
751void Monitor::NotifyAll(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700752 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700753 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700754 // Make sure that we hold the lock.
755 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800756 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700757 return;
758 }
759 // Signal all threads in the wait set.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700760 while (wait_set_ != nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700761 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700762 wait_set_ = thread->GetWaitNext();
763 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700764 thread->Notify();
765 }
766}
767
Mathieu Chartier590fee92013-09-13 13:46:47 -0700768bool Monitor::Deflate(Thread* self, mirror::Object* obj) {
769 DCHECK(obj != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700770 // Don't need volatile since we only deflate with mutators suspended.
771 LockWord lw(obj->GetLockWord(false));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700772 // If the lock isn't an inflated monitor, then we don't need to deflate anything.
773 if (lw.GetState() == LockWord::kFatLocked) {
774 Monitor* monitor = lw.FatLockMonitor();
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700775 DCHECK(monitor != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700776 MutexLock mu(self, monitor->monitor_lock_);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700777 // Can't deflate if we have anybody waiting on the CV.
778 if (monitor->num_waiters_ > 0) {
779 return false;
780 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700781 Thread* owner = monitor->owner_;
782 if (owner != nullptr) {
783 // Can't deflate if we are locked and have a hash code.
784 if (monitor->HasHashCode()) {
785 return false;
786 }
787 // Can't deflate if our lock count is too high.
Mathieu Chartier1cf194f2016-11-01 20:13:24 -0700788 if (static_cast<uint32_t>(monitor->lock_count_) > LockWord::kThinLockMaxCount) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700789 return false;
790 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700791 // Deflate to a thin lock.
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700792 LockWord new_lw = LockWord::FromThinLockId(owner->GetThreadId(),
793 monitor->lock_count_,
794 lw.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800795 // Assume no concurrent read barrier state changes as mutators are suspended.
796 obj->SetLockWord(new_lw, false);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700797 VLOG(monitor) << "Deflated " << obj << " to thin lock " << owner->GetTid() << " / "
798 << monitor->lock_count_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700799 } else if (monitor->HasHashCode()) {
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700800 LockWord new_lw = LockWord::FromHashCode(monitor->GetHashCode(), lw.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800801 // Assume no concurrent read barrier state changes as mutators are suspended.
802 obj->SetLockWord(new_lw, false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700803 VLOG(monitor) << "Deflated " << obj << " to hash monitor " << monitor->GetHashCode();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700804 } else {
805 // No lock and no hash, just put an empty lock word inside the object.
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700806 LockWord new_lw = LockWord::FromDefault(lw.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800807 // Assume no concurrent read barrier state changes as mutators are suspended.
808 obj->SetLockWord(new_lw, false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700809 VLOG(monitor) << "Deflated" << obj << " to empty lock word";
Mathieu Chartier590fee92013-09-13 13:46:47 -0700810 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700811 // 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 -0700812 // next GC.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700813 monitor->obj_ = GcRoot<mirror::Object>(nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700814 }
815 return true;
816}
817
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700818void Monitor::Inflate(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code) {
Andreas Gampe74240812014-04-17 10:35:09 -0700819 DCHECK(self != nullptr);
820 DCHECK(obj != nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700821 // Allocate and acquire a new monitor.
Andreas Gampe74240812014-04-17 10:35:09 -0700822 Monitor* m = MonitorPool::CreateMonitor(self, owner, obj, hash_code);
823 DCHECK(m != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700824 if (m->Install(self)) {
Haifeng Li86ab7912014-05-16 10:47:59 +0800825 if (owner != nullptr) {
826 VLOG(monitor) << "monitor: thread" << owner->GetThreadId()
Andreas Gampe74240812014-04-17 10:35:09 -0700827 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800828 } else {
829 VLOG(monitor) << "monitor: Inflate with hashcode " << hash_code
Andreas Gampe74240812014-04-17 10:35:09 -0700830 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800831 }
Andreas Gampe74240812014-04-17 10:35:09 -0700832 Runtime::Current()->GetMonitorList()->Add(m);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700833 CHECK_EQ(obj->GetLockWord(true).GetState(), LockWord::kFatLocked);
Andreas Gampe74240812014-04-17 10:35:09 -0700834 } else {
835 MonitorPool::ReleaseMonitor(self, m);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700836 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700837}
838
Mathieu Chartier0cd81352014-05-22 16:48:55 -0700839void Monitor::InflateThinLocked(Thread* self, Handle<mirror::Object> obj, LockWord lock_word,
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700840 uint32_t hash_code) {
841 DCHECK_EQ(lock_word.GetState(), LockWord::kThinLocked);
842 uint32_t owner_thread_id = lock_word.ThinLockOwner();
843 if (owner_thread_id == self->GetThreadId()) {
844 // We own the monitor, we can easily inflate it.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700845 Inflate(self, self, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700846 } else {
847 ThreadList* thread_list = Runtime::Current()->GetThreadList();
848 // Suspend the owner, inflate. First change to blocked and give up mutator_lock_.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700849 self->SetMonitorEnterObject(obj.Get());
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700850 bool timed_out;
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700851 Thread* owner;
852 {
853 ScopedThreadSuspension sts(self, kBlocked);
854 owner = thread_list->SuspendThreadByThreadId(owner_thread_id, false, &timed_out);
855 }
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700856 if (owner != nullptr) {
857 // We succeeded in suspending the thread, check the lock's status didn't change.
858 lock_word = obj->GetLockWord(true);
859 if (lock_word.GetState() == LockWord::kThinLocked &&
860 lock_word.ThinLockOwner() == owner_thread_id) {
861 // Go ahead and inflate the lock.
862 Inflate(self, owner, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700863 }
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700864 thread_list->Resume(owner, false);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700865 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700866 self->SetMonitorEnterObject(nullptr);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700867 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700868}
869
Ian Rogers719d1a32014-03-06 12:13:39 -0800870// Fool annotalysis into thinking that the lock on obj is acquired.
871static mirror::Object* FakeLock(mirror::Object* obj)
872 EXCLUSIVE_LOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
873 return obj;
874}
875
876// Fool annotalysis into thinking that the lock on obj is release.
877static mirror::Object* FakeUnlock(mirror::Object* obj)
878 UNLOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
879 return obj;
880}
881
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700882mirror::Object* Monitor::MonitorEnter(Thread* self, mirror::Object* obj, bool trylock) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700883 DCHECK(self != nullptr);
884 DCHECK(obj != nullptr);
Mathieu Chartier2d096c92015-10-12 16:18:20 -0700885 self->AssertThreadSuspensionIsAllowable();
Ian Rogers719d1a32014-03-06 12:13:39 -0800886 obj = FakeLock(obj);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700887 uint32_t thread_id = self->GetThreadId();
888 size_t contention_count = 0;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700889 StackHandleScope<1> hs(self);
890 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700891 while (true) {
Hans Boehmb3da36c2016-12-15 13:12:59 -0800892 // We initially read the lockword with ordinary Java/relaxed semantics. When stronger
893 // semantics are needed, we address it below. Since GetLockWord bottoms out to a relaxed load,
894 // we can fix it later, in an infrequently executed case, with a fence.
895 LockWord lock_word = h_obj->GetLockWord(false);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700896 switch (lock_word.GetState()) {
897 case LockWord::kUnlocked: {
Hans Boehmb3da36c2016-12-15 13:12:59 -0800898 // No ordering required for preceding lockword read, since we retest.
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700899 LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0, lock_word.GCState()));
Hans Boehmb3da36c2016-12-15 13:12:59 -0800900 if (h_obj->CasLockWordWeakAcquire(lock_word, thin_locked)) {
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700901 AtraceMonitorLock(self, h_obj.Get(), false /* is_wait */);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700902 return h_obj.Get(); // Success!
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700903 }
904 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -0700905 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700906 case LockWord::kThinLocked: {
907 uint32_t owner_thread_id = lock_word.ThinLockOwner();
908 if (owner_thread_id == thread_id) {
Hans Boehmb3da36c2016-12-15 13:12:59 -0800909 // No ordering required for initial lockword read.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700910 // We own the lock, increase the recursion count.
911 uint32_t new_count = lock_word.ThinLockCount() + 1;
912 if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700913 LockWord thin_locked(LockWord::FromThinLockId(thread_id,
914 new_count,
915 lock_word.GCState()));
Hans Boehmb3da36c2016-12-15 13:12:59 -0800916 // Only this thread pays attention to the count. Thus there is no need for stronger
917 // than relaxed memory ordering.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800918 if (!kUseReadBarrier) {
Hans Boehmb3da36c2016-12-15 13:12:59 -0800919 h_obj->SetLockWord(thin_locked, false /* volatile */);
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700920 AtraceMonitorLock(self, h_obj.Get(), false /* is_wait */);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800921 return h_obj.Get(); // Success!
922 } else {
923 // Use CAS to preserve the read barrier state.
Hans Boehmb3da36c2016-12-15 13:12:59 -0800924 if (h_obj->CasLockWordWeakRelaxed(lock_word, thin_locked)) {
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700925 AtraceMonitorLock(self, h_obj.Get(), false /* is_wait */);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800926 return h_obj.Get(); // Success!
927 }
928 }
929 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -0700930 } else {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700931 // We'd overflow the recursion count, so inflate the monitor.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700932 InflateThinLocked(self, h_obj, lock_word, 0);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700933 }
934 } else {
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700935 if (trylock) {
936 return nullptr;
937 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700938 // Contention.
939 contention_count++;
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700940 Runtime* runtime = Runtime::Current();
Hans Boehmb3da36c2016-12-15 13:12:59 -0800941 if (contention_count <= runtime->GetMaxSpinsBeforeThinLockInflation()) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700942 // TODO: Consider switching the thread state to kBlocked when we are yielding.
Mathieu Chartier251755c2014-07-15 18:10:25 -0700943 // Use sched_yield instead of NanoSleep since NanoSleep can wait much longer than the
944 // parameter you pass in. This can cause thread suspension to take excessively long
Mathieu Chartierb363f662014-07-16 13:28:58 -0700945 // and make long pauses. See b/16307460.
Hans Boehmb3da36c2016-12-15 13:12:59 -0800946 // TODO: We should literally spin first, without sched_yield. Sched_yield either does
947 // nothing (at significant expense), or guarantees that we wait at least microseconds.
948 // If the owner is running, I would expect the median lock hold time to be hundreds
949 // of nanoseconds or less.
Mathieu Chartier251755c2014-07-15 18:10:25 -0700950 sched_yield();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700951 } else {
952 contention_count = 0;
Hans Boehmb3da36c2016-12-15 13:12:59 -0800953 // No ordering required for initial lockword read. Install rereads it anyway.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700954 InflateThinLocked(self, h_obj, lock_word, 0);
Elliott Hughes5f791332011-09-15 17:45:30 -0700955 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700956 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700957 continue; // Start from the beginning.
Elliott Hughes5f791332011-09-15 17:45:30 -0700958 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700959 case LockWord::kFatLocked: {
Hans Boehmb3da36c2016-12-15 13:12:59 -0800960 // We should have done an acquire read of the lockword initially, to ensure
961 // visibility of the monitor data structure. Use an explicit fence instead.
962 QuasiAtomic::ThreadFenceAcquire();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700963 Monitor* mon = lock_word.FatLockMonitor();
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700964 if (trylock) {
965 return mon->TryLock(self) ? h_obj.Get() : nullptr;
966 } else {
967 mon->Lock(self);
968 return h_obj.Get(); // Success!
969 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700970 }
Ian Rogers719d1a32014-03-06 12:13:39 -0800971 case LockWord::kHashCode:
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700972 // Inflate with the existing hashcode.
Hans Boehmb3da36c2016-12-15 13:12:59 -0800973 // Again no ordering required for initial lockword read, since we don't rely
974 // on the visibility of any prior computation.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700975 Inflate(self, nullptr, h_obj.Get(), lock_word.GetHashCode());
Ian Rogers719d1a32014-03-06 12:13:39 -0800976 continue; // Start from the beginning.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700977 default: {
978 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700979 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700980 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700981 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700982 }
983}
984
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800985bool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700986 DCHECK(self != nullptr);
987 DCHECK(obj != nullptr);
Mathieu Chartier2d096c92015-10-12 16:18:20 -0700988 self->AssertThreadSuspensionIsAllowable();
Ian Rogers719d1a32014-03-06 12:13:39 -0800989 obj = FakeUnlock(obj);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700990 StackHandleScope<1> hs(self);
991 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800992 while (true) {
993 LockWord lock_word = obj->GetLockWord(true);
994 switch (lock_word.GetState()) {
995 case LockWord::kHashCode:
996 // Fall-through.
997 case LockWord::kUnlocked:
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700998 FailedUnlock(h_obj.Get(), self->GetThreadId(), 0u, nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700999 return false; // Failure.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001000 case LockWord::kThinLocked: {
1001 uint32_t thread_id = self->GetThreadId();
1002 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1003 if (owner_thread_id != thread_id) {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -07001004 FailedUnlock(h_obj.Get(), thread_id, owner_thread_id, nullptr);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001005 return false; // Failure.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001006 } else {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001007 // We own the lock, decrease the recursion count.
1008 LockWord new_lw = LockWord::Default();
1009 if (lock_word.ThinLockCount() != 0) {
1010 uint32_t new_count = lock_word.ThinLockCount() - 1;
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001011 new_lw = LockWord::FromThinLockId(thread_id, new_count, lock_word.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001012 } else {
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001013 new_lw = LockWord::FromDefault(lock_word.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001014 }
1015 if (!kUseReadBarrier) {
1016 DCHECK_EQ(new_lw.ReadBarrierState(), 0U);
Hans Boehmb3da36c2016-12-15 13:12:59 -08001017 // TODO: This really only needs memory_order_release, but we currently have
1018 // no way to specify that. In fact there seem to be no legitimate uses of SetLockWord
1019 // with a final argument of true. This slows down x86 and ARMv7, but probably not v8.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001020 h_obj->SetLockWord(new_lw, true);
Andreas Gampe6e759ad2016-05-17 10:13:10 -07001021 AtraceMonitorUnlock();
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001022 // Success!
1023 return true;
1024 } else {
1025 // Use CAS to preserve the read barrier state.
Hans Boehmb3da36c2016-12-15 13:12:59 -08001026 if (h_obj->CasLockWordWeakRelease(lock_word, new_lw)) {
Andreas Gampe6e759ad2016-05-17 10:13:10 -07001027 AtraceMonitorUnlock();
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001028 // Success!
1029 return true;
1030 }
1031 }
1032 continue; // Go again.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001033 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001034 }
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001035 case LockWord::kFatLocked: {
1036 Monitor* mon = lock_word.FatLockMonitor();
1037 return mon->Unlock(self);
1038 }
1039 default: {
1040 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1041 return false;
1042 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001043 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001044 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001045}
1046
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001047void Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
Elliott Hughes4cd121e2013-01-07 17:35:41 -08001048 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001049 DCHECK(self != nullptr);
1050 DCHECK(obj != nullptr);
1051 LockWord lock_word = obj->GetLockWord(true);
Ian Rogers43c69cc2014-08-15 11:09:28 -07001052 while (lock_word.GetState() != LockWord::kFatLocked) {
1053 switch (lock_word.GetState()) {
1054 case LockWord::kHashCode:
1055 // Fall-through.
1056 case LockWord::kUnlocked:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001057 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
1058 return; // Failure.
Ian Rogers43c69cc2014-08-15 11:09:28 -07001059 case LockWord::kThinLocked: {
1060 uint32_t thread_id = self->GetThreadId();
1061 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1062 if (owner_thread_id != thread_id) {
1063 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
1064 return; // Failure.
1065 } else {
1066 // We own the lock, inflate to enqueue ourself on the Monitor. May fail spuriously so
1067 // re-load.
1068 Inflate(self, self, obj, 0);
1069 lock_word = obj->GetLockWord(true);
1070 }
1071 break;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001072 }
Ian Rogers43c69cc2014-08-15 11:09:28 -07001073 case LockWord::kFatLocked: // Unreachable given the loop condition above. Fall-through.
1074 default: {
1075 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1076 return;
1077 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001078 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001079 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001080 Monitor* mon = lock_word.FatLockMonitor();
1081 mon->Wait(self, ms, ns, interruptShouldThrow, why);
Elliott Hughes5f791332011-09-15 17:45:30 -07001082}
1083
Ian Rogers13c479e2013-10-11 07:59:01 -07001084void Monitor::DoNotify(Thread* self, mirror::Object* obj, bool notify_all) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001085 DCHECK(self != nullptr);
1086 DCHECK(obj != nullptr);
1087 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001088 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001089 case LockWord::kHashCode:
1090 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001091 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -08001092 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001093 return; // Failure.
1094 case LockWord::kThinLocked: {
1095 uint32_t thread_id = self->GetThreadId();
1096 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1097 if (owner_thread_id != thread_id) {
1098 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
1099 return; // Failure.
1100 } else {
1101 // We own the lock but there's no Monitor and therefore no waiters.
1102 return; // Success.
1103 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001104 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001105 case LockWord::kFatLocked: {
1106 Monitor* mon = lock_word.FatLockMonitor();
1107 if (notify_all) {
1108 mon->NotifyAll(self);
1109 } else {
1110 mon->Notify(self);
1111 }
1112 return; // Success.
1113 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001114 default: {
1115 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1116 return;
1117 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001118 }
1119}
1120
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001121uint32_t Monitor::GetLockOwnerThreadId(mirror::Object* obj) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001122 DCHECK(obj != nullptr);
1123 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001124 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001125 case LockWord::kHashCode:
1126 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001127 case LockWord::kUnlocked:
1128 return ThreadList::kInvalidThreadId;
1129 case LockWord::kThinLocked:
1130 return lock_word.ThinLockOwner();
1131 case LockWord::kFatLocked: {
1132 Monitor* mon = lock_word.FatLockMonitor();
1133 return mon->GetOwnerThreadId();
Elliott Hughes5f791332011-09-15 17:45:30 -07001134 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001135 default: {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001136 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001137 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001138 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001139 }
1140}
1141
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001142void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
Ian Rogersd803bc72014-04-01 15:33:03 -07001143 // Determine the wait message and object we're waiting or blocked upon.
1144 mirror::Object* pretty_object = nullptr;
1145 const char* wait_message = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001146 uint32_t lock_owner = ThreadList::kInvalidThreadId;
Ian Rogersd803bc72014-04-01 15:33:03 -07001147 ThreadState state = thread->GetState();
Elliott Hughesb4e94fd2013-01-08 14:41:26 -08001148 if (state == kWaiting || state == kTimedWaiting || state == kSleeping) {
Ian Rogersd803bc72014-04-01 15:33:03 -07001149 wait_message = (state == kSleeping) ? " - sleeping on " : " - waiting on ";
1150 Thread* self = Thread::Current();
1151 MutexLock mu(self, *thread->GetWaitMutex());
1152 Monitor* monitor = thread->GetWaitMonitor();
1153 if (monitor != nullptr) {
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001154 pretty_object = monitor->GetObject();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001155 }
Elliott Hughes34e06962012-04-09 13:55:55 -07001156 } else if (state == kBlocked) {
Ian Rogersd803bc72014-04-01 15:33:03 -07001157 wait_message = " - waiting to lock ";
1158 pretty_object = thread->GetMonitorEnterObject();
1159 if (pretty_object != nullptr) {
Hiroshi Yamauchi7b08ae42016-10-04 15:20:36 -07001160 if (kUseReadBarrier && Thread::Current()->GetIsGcMarking()) {
1161 // We may call Thread::Dump() in the middle of the CC thread flip and this thread's stack
1162 // may have not been flipped yet and "pretty_object" may be a from-space (stale) ref, in
1163 // which case the GetLockOwnerThreadId() call below will crash. So explicitly mark/forward
1164 // it here.
1165 pretty_object = ReadBarrier::Mark(pretty_object);
1166 }
Ian Rogersd803bc72014-04-01 15:33:03 -07001167 lock_owner = pretty_object->GetLockOwnerThreadId();
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001168 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001169 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001170
Ian Rogersd803bc72014-04-01 15:33:03 -07001171 if (wait_message != nullptr) {
1172 if (pretty_object == nullptr) {
1173 os << wait_message << "an unknown object";
1174 } else {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001175 if ((pretty_object->GetLockWord(true).GetState() == LockWord::kThinLocked) &&
Ian Rogersd803bc72014-04-01 15:33:03 -07001176 Locks::mutator_lock_->IsExclusiveHeld(Thread::Current())) {
1177 // Getting the identity hashcode here would result in lock inflation and suspension of the
1178 // current thread, which isn't safe if this is the only runnable thread.
1179 os << wait_message << StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)",
1180 reinterpret_cast<intptr_t>(pretty_object),
David Sehr709b0702016-10-13 09:12:37 -07001181 pretty_object->PrettyTypeOf().c_str());
Ian Rogersd803bc72014-04-01 15:33:03 -07001182 } else {
1183 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
Mathieu Chartier49361592015-01-22 16:36:10 -08001184 // Call PrettyTypeOf before IdentityHashCode since IdentityHashCode can cause thread
1185 // suspension and move pretty_object.
David Sehr709b0702016-10-13 09:12:37 -07001186 const std::string pretty_type(pretty_object->PrettyTypeOf());
Ian Rogersd803bc72014-04-01 15:33:03 -07001187 os << wait_message << StringPrintf("<0x%08x> (a %s)", pretty_object->IdentityHashCode(),
Mathieu Chartier49361592015-01-22 16:36:10 -08001188 pretty_type.c_str());
Ian Rogersd803bc72014-04-01 15:33:03 -07001189 }
1190 }
1191 // - waiting to lock <0x613f83d8> (a java.lang.Object) held by thread 5
1192 if (lock_owner != ThreadList::kInvalidThreadId) {
1193 os << " held by thread " << lock_owner;
1194 }
1195 os << "\n";
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001196 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001197}
1198
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001199mirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -08001200 // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
1201 // definition of contended that includes a monitor a thread is trying to enter...
Ian Rogersdd7624d2014-03-14 17:43:00 -07001202 mirror::Object* result = thread->GetMonitorEnterObject();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001203 if (result == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001204 // ...but also a monitor that the thread is waiting on.
Ian Rogersdd7624d2014-03-14 17:43:00 -07001205 MutexLock mu(Thread::Current(), *thread->GetWaitMutex());
1206 Monitor* monitor = thread->GetWaitMonitor();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001207 if (monitor != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001208 result = monitor->GetObject();
Elliott Hughesf9501702013-01-11 11:22:27 -08001209 }
1210 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001211 return result;
Elliott Hughesf9501702013-01-11 11:22:27 -08001212}
1213
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001214void Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
Andreas Gampe760172c2014-08-16 13:41:10 -07001215 void* callback_context, bool abort_on_failure) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001216 ArtMethod* m = stack_visitor->GetMethod();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001217 CHECK(m != nullptr);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001218
1219 // Native methods are an easy special case.
1220 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
1221 if (m->IsNative()) {
1222 if (m->IsSynchronized()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001223 mirror::Object* jni_this =
1224 stack_visitor->GetCurrentHandleScope(sizeof(void*))->GetReference(0);
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001225 callback(jni_this, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001226 }
1227 return;
1228 }
1229
jeffhao61f916c2012-10-25 17:48:51 -07001230 // Proxy methods should not be synchronized.
1231 if (m->IsProxyMethod()) {
1232 CHECK(!m->IsSynchronized());
1233 return;
1234 }
1235
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001236 // Is there any reason to believe there's any synchronization in this method?
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001237 const DexFile::CodeItem* code_item = m->GetCodeItem();
David Sehr709b0702016-10-13 09:12:37 -07001238 CHECK(code_item != nullptr) << m->PrettyMethod();
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001239 if (code_item->tries_size_ == 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001240 return; // No "tries" implies no synchronization, so no held locks to report.
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001241 }
1242
Andreas Gampe760172c2014-08-16 13:41:10 -07001243 // Get the dex pc. If abort_on_failure is false, GetDexPc will not abort in the case it cannot
1244 // find the dex pc, and instead return kDexNoIndex. Then bail out, as it indicates we have an
1245 // inconsistent stack anyways.
1246 uint32_t dex_pc = stack_visitor->GetDexPc(abort_on_failure);
1247 if (!abort_on_failure && dex_pc == DexFile::kDexNoIndex) {
David Sehr709b0702016-10-13 09:12:37 -07001248 LOG(ERROR) << "Could not find dex_pc for " << m->PrettyMethod();
Andreas Gampe760172c2014-08-16 13:41:10 -07001249 return;
1250 }
1251
Elliott Hughes80537bb2013-01-04 16:37:26 -08001252 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
1253 // the locks held in this stack frame.
1254 std::vector<uint32_t> monitor_enter_dex_pcs;
Andreas Gampe760172c2014-08-16 13:41:10 -07001255 verifier::MethodVerifier::FindLocksAtDexPc(m, dex_pc, &monitor_enter_dex_pcs);
Mathieu Chartiere6a8eec2015-01-06 14:17:57 -08001256 for (uint32_t monitor_dex_pc : monitor_enter_dex_pcs) {
Elliott Hughes80537bb2013-01-04 16:37:26 -08001257 // The verifier works in terms of the dex pcs of the monitor-enter instructions.
1258 // We want the registers used by those instructions (so we can read the values out of them).
Sebastien Hertz0f7c9332015-11-05 15:57:30 +01001259 const Instruction* monitor_enter_instruction =
1260 Instruction::At(&code_item->insns_[monitor_dex_pc]);
Elliott Hughes80537bb2013-01-04 16:37:26 -08001261
1262 // Quick sanity check.
Sebastien Hertz0f7c9332015-11-05 15:57:30 +01001263 CHECK_EQ(monitor_enter_instruction->Opcode(), Instruction::MONITOR_ENTER)
1264 << "expected monitor-enter @" << monitor_dex_pc << "; was "
1265 << reinterpret_cast<const void*>(monitor_enter_instruction);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001266
Sebastien Hertz0f7c9332015-11-05 15:57:30 +01001267 uint16_t monitor_register = monitor_enter_instruction->VRegA();
Nicolas Geoffray15b9d522015-03-12 15:05:13 +00001268 uint32_t value;
1269 bool success = stack_visitor->GetVReg(m, monitor_register, kReferenceVReg, &value);
1270 CHECK(success) << "Failed to read v" << monitor_register << " of kind "
David Sehr709b0702016-10-13 09:12:37 -07001271 << kReferenceVReg << " in method " << m->PrettyMethod();
Nicolas Geoffray15b9d522015-03-12 15:05:13 +00001272 mirror::Object* o = reinterpret_cast<mirror::Object*>(value);
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001273 callback(o, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001274 }
1275}
1276
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001277bool Monitor::IsValidLockWord(LockWord lock_word) {
1278 switch (lock_word.GetState()) {
1279 case LockWord::kUnlocked:
1280 // Nothing to check.
1281 return true;
1282 case LockWord::kThinLocked:
1283 // Basic sanity check of owner.
1284 return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
1285 case LockWord::kFatLocked: {
1286 // Check the monitor appears in the monitor list.
1287 Monitor* mon = lock_word.FatLockMonitor();
1288 MonitorList* list = Runtime::Current()->GetMonitorList();
1289 MutexLock mu(Thread::Current(), list->monitor_list_lock_);
1290 for (Monitor* list_mon : list->list_) {
1291 if (mon == list_mon) {
1292 return true; // Found our monitor.
1293 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001294 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001295 return false; // Fail - unowned monitor in an object.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001296 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001297 case LockWord::kHashCode:
1298 return true;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001299 default:
1300 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001301 UNREACHABLE();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001302 }
1303}
1304
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001305bool Monitor::IsLocked() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001306 MutexLock mu(Thread::Current(), monitor_lock_);
1307 return owner_ != nullptr;
1308}
1309
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -07001310void Monitor::TranslateLocation(ArtMethod* method,
1311 uint32_t dex_pc,
1312 const char** source_file,
1313 int32_t* line_number) {
jeffhao33dc7712011-11-09 17:54:24 -08001314 // If method is null, location is unknown
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001315 if (method == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001316 *source_file = "";
1317 *line_number = 0;
jeffhao33dc7712011-11-09 17:54:24 -08001318 return;
1319 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001320 *source_file = method->GetDeclaringClassSourceFile();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001321 if (*source_file == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001322 *source_file = "";
Elliott Hughes12c51e32012-01-17 20:25:05 -08001323 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001324 *line_number = method->GetLineNumFromDexPC(dex_pc);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001325}
1326
1327uint32_t Monitor::GetOwnerThreadId() {
1328 MutexLock mu(Thread::Current(), monitor_lock_);
1329 Thread* owner = owner_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001330 if (owner != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001331 return owner->GetThreadId();
1332 } else {
1333 return ThreadList::kInvalidThreadId;
1334 }
jeffhao33dc7712011-11-09 17:54:24 -08001335}
1336
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001337MonitorList::MonitorList()
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001338 : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock", kMonitorListLock),
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001339 monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001340}
1341
1342MonitorList::~MonitorList() {
Andreas Gampe74240812014-04-17 10:35:09 -07001343 Thread* self = Thread::Current();
1344 MutexLock mu(self, monitor_list_lock_);
1345 // Release all monitors to the pool.
1346 // TODO: Is it an invariant that *all* open monitors are in the list? Then we could
1347 // clear faster in the pool.
1348 MonitorPool::ReleaseMonitors(self, &list_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001349}
1350
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001351void MonitorList::DisallowNewMonitors() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001352 CHECK(!kUseReadBarrier);
Ian Rogers50b35e22012-10-04 10:09:15 -07001353 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001354 allow_new_monitors_ = false;
1355}
1356
1357void MonitorList::AllowNewMonitors() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001358 CHECK(!kUseReadBarrier);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001359 Thread* self = Thread::Current();
1360 MutexLock mu(self, monitor_list_lock_);
1361 allow_new_monitors_ = true;
1362 monitor_add_condition_.Broadcast(self);
1363}
1364
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001365void MonitorList::BroadcastForNewMonitors() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001366 Thread* self = Thread::Current();
1367 MutexLock mu(self, monitor_list_lock_);
1368 monitor_add_condition_.Broadcast(self);
1369}
1370
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001371void MonitorList::Add(Monitor* m) {
1372 Thread* self = Thread::Current();
1373 MutexLock mu(self, monitor_list_lock_);
Hiroshi Yamauchif1c6f872017-01-06 12:23:47 -08001374 // CMS needs this to block for concurrent reference processing because an object allocated during
1375 // the GC won't be marked and concurrent reference processing would incorrectly clear the JNI weak
1376 // ref. But CC (kUseReadBarrier == true) doesn't because of the to-space invariant.
1377 while (!kUseReadBarrier && UNLIKELY(!allow_new_monitors_)) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -07001378 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
1379 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -08001380 self->CheckEmptyCheckpointFromWeakRefAccess(&monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001381 monitor_add_condition_.WaitHoldingLocks(self);
1382 }
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001383 list_.push_front(m);
1384}
1385
Mathieu Chartier97509952015-07-13 14:35:43 -07001386void MonitorList::SweepMonitorList(IsMarkedVisitor* visitor) {
Andreas Gampe74240812014-04-17 10:35:09 -07001387 Thread* self = Thread::Current();
1388 MutexLock mu(self, monitor_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001389 for (auto it = list_.begin(); it != list_.end(); ) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001390 Monitor* m = *it;
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001391 // Disable the read barrier in GetObject() as this is called by GC.
1392 mirror::Object* obj = m->GetObject<kWithoutReadBarrier>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001393 // The object of a monitor can be null if we have deflated it.
Mathieu Chartier97509952015-07-13 14:35:43 -07001394 mirror::Object* new_obj = obj != nullptr ? visitor->IsMarked(obj) : nullptr;
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001395 if (new_obj == nullptr) {
1396 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001397 << obj;
Andreas Gampe74240812014-04-17 10:35:09 -07001398 MonitorPool::ReleaseMonitor(self, m);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001399 it = list_.erase(it);
1400 } else {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001401 m->SetObject(new_obj);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001402 ++it;
1403 }
1404 }
1405}
1406
Hans Boehm6fe97e02016-05-04 18:35:57 -07001407size_t MonitorList::Size() {
1408 Thread* self = Thread::Current();
1409 MutexLock mu(self, monitor_list_lock_);
1410 return list_.size();
1411}
1412
Mathieu Chartier97509952015-07-13 14:35:43 -07001413class MonitorDeflateVisitor : public IsMarkedVisitor {
1414 public:
1415 MonitorDeflateVisitor() : self_(Thread::Current()), deflate_count_(0) {}
1416
1417 virtual mirror::Object* IsMarked(mirror::Object* object) OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001418 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001419 if (Monitor::Deflate(self_, object)) {
1420 DCHECK_NE(object->GetLockWord(true).GetState(), LockWord::kFatLocked);
1421 ++deflate_count_;
1422 // If we deflated, return null so that the monitor gets removed from the array.
1423 return nullptr;
1424 }
1425 return object; // Monitor was not deflated.
1426 }
1427
1428 Thread* const self_;
1429 size_t deflate_count_;
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001430};
1431
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001432size_t MonitorList::DeflateMonitors() {
Mathieu Chartier97509952015-07-13 14:35:43 -07001433 MonitorDeflateVisitor visitor;
1434 Locks::mutator_lock_->AssertExclusiveHeld(visitor.self_);
1435 SweepMonitorList(&visitor);
1436 return visitor.deflate_count_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001437}
1438
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001439MonitorInfo::MonitorInfo(mirror::Object* obj) : owner_(nullptr), entry_count_(0) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001440 DCHECK(obj != nullptr);
1441 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001442 switch (lock_word.GetState()) {
1443 case LockWord::kUnlocked:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001444 // Fall-through.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001445 case LockWord::kForwardingAddress:
1446 // Fall-through.
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001447 case LockWord::kHashCode:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001448 break;
1449 case LockWord::kThinLocked:
1450 owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
1451 entry_count_ = 1 + lock_word.ThinLockCount();
1452 // Thin locks have no waiters.
1453 break;
1454 case LockWord::kFatLocked: {
1455 Monitor* mon = lock_word.FatLockMonitor();
1456 owner_ = mon->owner_;
1457 entry_count_ = 1 + mon->lock_count_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001458 for (Thread* waiter = mon->wait_set_; waiter != nullptr; waiter = waiter->GetWaitNext()) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001459 waiters_.push_back(waiter);
1460 }
1461 break;
Elliott Hughesf327e072013-01-09 16:01:26 -08001462 }
1463 }
1464}
1465
Elliott Hughes5f791332011-09-15 17:45:30 -07001466} // namespace art