blob: 4d309bfcd290e45876c14a9e44a873a725a0ab66 [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"
Andreas Gampe5d08fcc2017-06-05 17:56:46 -070034#include "object_callbacks.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070035#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070036#include "stack.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070037#include "thread.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070038#include "thread_list.h"
Elliott Hughes08fc03a2012-06-26 17:34:00 -070039#include "verifier/method_verifier.h"
Elliott Hughes044288f2012-06-25 14:46:39 -070040#include "well_known_classes.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070041
42namespace art {
43
Andreas Gampe46ee31b2016-12-14 10:11:49 -080044using android::base::StringPrintf;
45
Mathieu Chartierb9001ab2014-10-03 13:28:46 -070046static constexpr uint64_t kLongWaitMs = 100;
47
Elliott Hughes5f791332011-09-15 17:45:30 -070048/*
Ian Rogersd9c4fc92013-10-01 19:45:43 -070049 * Every Object has a monitor associated with it, but not every Object is actually locked. Even
50 * the ones that are locked do not need a full-fledged monitor until a) there is actual contention
51 * or b) wait() is called on the Object.
Elliott Hughes5f791332011-09-15 17:45:30 -070052 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070053 * For Android, we have implemented a scheme similar to the one described in Bacon et al.'s
54 * "Thin locks: featherweight synchronization for Java" (ACM 1998). Things are even easier for us,
55 * though, because we have a full 32 bits to work with.
Elliott Hughes5f791332011-09-15 17:45:30 -070056 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070057 * The two states of an Object's lock are referred to as "thin" and "fat". A lock may transition
58 * from the "thin" state to the "fat" state and this transition is referred to as inflation. Once
59 * a lock has been inflated it remains in the "fat" state indefinitely.
Elliott Hughes5f791332011-09-15 17:45:30 -070060 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070061 * The lock value itself is stored in mirror::Object::monitor_ and the representation is described
62 * in the LockWord value type.
Elliott Hughes54e7df12011-09-16 11:47:04 -070063 *
Elliott Hughes5f791332011-09-15 17:45:30 -070064 * Monitors provide:
65 * - mutually exclusive access to resources
66 * - a way for multiple threads to wait for notification
67 *
68 * In effect, they fill the role of both mutexes and condition variables.
69 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070070 * Only one thread can own the monitor at any time. There may be several threads waiting on it
71 * (the wait call unlocks it). One or more waiting threads may be getting interrupted or notified
72 * at any given time.
Elliott Hughes5f791332011-09-15 17:45:30 -070073 */
Elliott Hughes54e7df12011-09-16 11:47:04 -070074
Elliott Hughesfc861622011-10-17 17:57:47 -070075uint32_t Monitor::lock_profiling_threshold_ = 0;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070076
Calin Juravleb2771b42016-04-07 17:09:25 +010077void Monitor::Init(uint32_t lock_profiling_threshold) {
Elliott Hughesfc861622011-10-17 17:57:47 -070078 lock_profiling_threshold_ = lock_profiling_threshold;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070079}
80
Ian Rogersef7d42f2014-01-06 12:55:46 -080081Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code)
Ian Rogers00f7d0e2012-07-19 15:28:27 -070082 : monitor_lock_("a monitor lock", kMonitorLock),
Ian Rogersd9c4fc92013-10-01 19:45:43 -070083 monitor_contenders_("monitor contenders", monitor_lock_),
Mathieu Chartier46bc7782013-11-12 17:03:02 -080084 num_waiters_(0),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070085 owner_(owner),
Elliott Hughes5f791332011-09-15 17:45:30 -070086 lock_count_(0),
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070087 obj_(GcRoot<mirror::Object>(obj)),
Mathieu Chartier2cebb242015-04-21 16:50:40 -070088 wait_set_(nullptr),
Mathieu Chartierad2541a2013-10-25 10:05:23 -070089 hash_code_(hash_code),
Mathieu Chartier2cebb242015-04-21 16:50:40 -070090 locking_method_(nullptr),
Ian Rogersef7d42f2014-01-06 12:55:46 -080091 locking_dex_pc_(0),
Andreas Gampe74240812014-04-17 10:35:09 -070092 monitor_id_(MonitorPool::ComputeMonitorId(this, self)) {
93#ifdef __LP64__
94 DCHECK(false) << "Should not be reached in 64b";
95 next_free_ = nullptr;
96#endif
97 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
98 // with the owner unlocking the thin-lock.
99 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
100 // The identity hash code is set for the life time of the monitor.
101}
102
103Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code,
104 MonitorId id)
105 : monitor_lock_("a monitor lock", kMonitorLock),
106 monitor_contenders_("monitor contenders", monitor_lock_),
107 num_waiters_(0),
108 owner_(owner),
109 lock_count_(0),
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700110 obj_(GcRoot<mirror::Object>(obj)),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700111 wait_set_(nullptr),
Andreas Gampe74240812014-04-17 10:35:09 -0700112 hash_code_(hash_code),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700113 locking_method_(nullptr),
Andreas Gampe74240812014-04-17 10:35:09 -0700114 locking_dex_pc_(0),
115 monitor_id_(id) {
116#ifdef __LP64__
117 next_free_ = nullptr;
118#endif
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700119 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
120 // with the owner unlocking the thin-lock.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800121 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700122 // The identity hash code is set for the life time of the monitor.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700123}
124
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700125int32_t Monitor::GetHashCode() {
126 while (!HasHashCode()) {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700127 if (hash_code_.CompareExchangeWeakRelaxed(0, mirror::Object::GenerateIdentityHashCode())) {
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700128 break;
129 }
130 }
131 DCHECK(HasHashCode());
Ian Rogers3e5cf302014-05-20 16:40:37 -0700132 return hash_code_.LoadRelaxed();
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700133}
134
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700135bool Monitor::Install(Thread* self) {
136 MutexLock mu(self, monitor_lock_); // Uncontended mutex acquisition as monitor isn't yet public.
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700137 CHECK(owner_ == nullptr || owner_ == self || owner_->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700138 // Propagate the lock state.
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700139 LockWord lw(GetObject()->GetLockWord(false));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700140 switch (lw.GetState()) {
141 case LockWord::kThinLocked: {
142 CHECK_EQ(owner_->GetThreadId(), lw.ThinLockOwner());
143 lock_count_ = lw.ThinLockCount();
144 break;
145 }
146 case LockWord::kHashCode: {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700147 CHECK_EQ(hash_code_.LoadRelaxed(), static_cast<int32_t>(lw.GetHashCode()));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700148 break;
149 }
150 case LockWord::kFatLocked: {
151 // The owner_ is suspended but another thread beat us to install a monitor.
152 return false;
153 }
154 case LockWord::kUnlocked: {
155 LOG(FATAL) << "Inflating unlocked lock word";
156 break;
157 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700158 default: {
159 LOG(FATAL) << "Invalid monitor state " << lw.GetState();
160 return false;
161 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700162 }
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700163 LockWord fat(this, lw.GCState());
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700164 // Publish the updated lock word, which may race with other threads.
Hans Boehmb3da36c2016-12-15 13:12:59 -0800165 bool success = GetObject()->CasLockWordWeakRelease(lw, fat);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700166 // Lock profiling.
Mathieu Chartier9728f912013-10-30 09:45:13 -0700167 if (success && owner_ != nullptr && lock_profiling_threshold_ != 0) {
Andreas Gampe6ec8ebd2014-07-25 13:36:56 -0700168 // Do not abort on dex pc errors. This can easily happen when we want to dump a stack trace on
169 // abort.
170 locking_method_ = owner_->GetCurrentMethod(&locking_dex_pc_, false);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700171 }
172 return success;
Elliott Hughes5f791332011-09-15 17:45:30 -0700173}
174
175Monitor::~Monitor() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700176 // Deflated monitors have a null object.
Elliott Hughes5f791332011-09-15 17:45:30 -0700177}
178
Elliott Hughes5f791332011-09-15 17:45:30 -0700179void Monitor::AppendToWaitSet(Thread* thread) {
180 DCHECK(owner_ == Thread::Current());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700181 DCHECK(thread != nullptr);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700182 DCHECK(thread->GetWaitNext() == nullptr) << thread->GetWaitNext();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700183 if (wait_set_ == nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700184 wait_set_ = thread;
185 return;
186 }
187
188 // push_back.
189 Thread* t = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700190 while (t->GetWaitNext() != nullptr) {
191 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700192 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700193 t->SetWaitNext(thread);
Elliott Hughes5f791332011-09-15 17:45:30 -0700194}
195
Elliott Hughes5f791332011-09-15 17:45:30 -0700196void Monitor::RemoveFromWaitSet(Thread *thread) {
197 DCHECK(owner_ == Thread::Current());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700198 DCHECK(thread != nullptr);
199 if (wait_set_ == nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700200 return;
201 }
202 if (wait_set_ == thread) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700203 wait_set_ = thread->GetWaitNext();
204 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700205 return;
206 }
207
208 Thread* t = wait_set_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700209 while (t->GetWaitNext() != nullptr) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700210 if (t->GetWaitNext() == thread) {
211 t->SetWaitNext(thread->GetWaitNext());
212 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700213 return;
214 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700215 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700216 }
217}
218
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700219void Monitor::SetObject(mirror::Object* object) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700220 obj_ = GcRoot<mirror::Object>(object);
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700221}
222
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700223// Note: Adapted from CurrentMethodVisitor in thread.cc. We must not resolve here.
224
225struct NthCallerWithDexPcVisitor FINAL : public StackVisitor {
226 explicit NthCallerWithDexPcVisitor(Thread* thread, size_t frame)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700227 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +0100228 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700229 method_(nullptr),
230 dex_pc_(0),
231 current_frame_number_(0),
232 wanted_frame_number_(frame) {}
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700233 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700234 ArtMethod* m = GetMethod();
235 if (m == nullptr || m->IsRuntimeMethod()) {
236 // Runtime method, upcall, or resolution issue. Skip.
237 return true;
238 }
239
240 // Is this the requested frame?
241 if (current_frame_number_ == wanted_frame_number_) {
242 method_ = m;
243 dex_pc_ = GetDexPc(false /* abort_on_error*/);
244 return false;
245 }
246
247 // Look for more.
248 current_frame_number_++;
249 return true;
250 }
251
252 ArtMethod* method_;
253 uint32_t dex_pc_;
254
255 private:
256 size_t current_frame_number_;
257 const size_t wanted_frame_number_;
258};
259
260// This function is inlined and just helps to not have the VLOG and ATRACE check at all the
261// potential tracing points.
262void Monitor::AtraceMonitorLock(Thread* self, mirror::Object* obj, bool is_wait) {
263 if (UNLIKELY(VLOG_IS_ON(systrace_lock_logging) && ATRACE_ENABLED())) {
264 AtraceMonitorLockImpl(self, obj, is_wait);
265 }
266}
267
268void Monitor::AtraceMonitorLockImpl(Thread* self, mirror::Object* obj, bool is_wait) {
269 // Wait() requires a deeper call stack to be useful. Otherwise you'll see "Waiting at
270 // Object.java". Assume that we'll wait a nontrivial amount, so it's OK to do a longer
271 // stack walk than if !is_wait.
272 NthCallerWithDexPcVisitor visitor(self, is_wait ? 1U : 0U);
273 visitor.WalkStack(false);
274 const char* prefix = is_wait ? "Waiting on " : "Locking ";
275
276 const char* filename;
277 int32_t line_number;
278 TranslateLocation(visitor.method_, visitor.dex_pc_, &filename, &line_number);
279
280 // It would be nice to have a stable "ID" for the object here. However, the only stable thing
281 // would be the identity hashcode. But we cannot use IdentityHashcode here: For one, there are
282 // times when it is unsafe to make that call (see stack dumping for an explanation). More
283 // importantly, we would have to give up on thin-locking when adding systrace locks, as the
284 // identity hashcode is stored in the lockword normally (so can't be used with thin-locks).
285 //
286 // Because of thin-locks we also cannot use the monitor id (as there is no monitor). Monitor ids
287 // also do not have to be stable, as the monitor may be deflated.
288 std::string tmp = StringPrintf("%s %d at %s:%d",
289 prefix,
290 (obj == nullptr ? -1 : static_cast<int32_t>(reinterpret_cast<uintptr_t>(obj))),
291 (filename != nullptr ? filename : "null"),
292 line_number);
293 ATRACE_BEGIN(tmp.c_str());
294}
295
296void Monitor::AtraceMonitorUnlock() {
297 if (UNLIKELY(VLOG_IS_ON(systrace_lock_logging))) {
298 ATRACE_END();
299 }
300}
301
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700302std::string Monitor::PrettyContentionInfo(const std::string& owner_name,
303 pid_t owner_tid,
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700304 ArtMethod* owners_method,
305 uint32_t owners_dex_pc,
306 size_t num_waiters) {
Hiroshi Yamauchi71cd68d2017-01-25 18:28:12 -0800307 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700308 const char* owners_filename;
Goran Jakovljevic49c882b2016-04-19 10:27:21 +0200309 int32_t owners_line_number = 0;
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700310 if (owners_method != nullptr) {
311 TranslateLocation(owners_method, owners_dex_pc, &owners_filename, &owners_line_number);
312 }
313 std::ostringstream oss;
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700314 oss << "monitor contention with owner " << owner_name << " (" << owner_tid << ")";
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700315 if (owners_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700316 oss << " at " << owners_method->PrettyMethod();
Mathieu Chartier36891fe2016-04-28 17:21:08 -0700317 oss << "(" << owners_filename << ":" << owners_line_number << ")";
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700318 }
319 oss << " waiters=" << num_waiters;
320 return oss.str();
321}
322
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700323bool Monitor::TryLockLocked(Thread* self) {
324 if (owner_ == nullptr) { // Unowned.
325 owner_ = self;
326 CHECK_EQ(lock_count_, 0);
327 // When debugging, save the current monitor holder for future
328 // acquisition failures to use in sampled logging.
329 if (lock_profiling_threshold_ != 0) {
330 locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
331 }
332 } else if (owner_ == self) { // Recursive.
333 lock_count_++;
334 } else {
335 return false;
336 }
337 AtraceMonitorLock(self, GetObject(), false /* is_wait */);
338 return true;
339}
340
341bool Monitor::TryLock(Thread* self) {
342 MutexLock mu(self, monitor_lock_);
343 return TryLockLocked(self);
344}
345
Elliott Hughes5f791332011-09-15 17:45:30 -0700346void Monitor::Lock(Thread* self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700347 MutexLock mu(self, monitor_lock_);
348 while (true) {
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700349 if (TryLockLocked(self)) {
350 return;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700351 }
352 // Contended.
353 const bool log_contention = (lock_profiling_threshold_ != 0);
Xin Guanb894a192014-08-22 11:55:37 -0500354 uint64_t wait_start_ms = log_contention ? MilliTime() : 0;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700355 ArtMethod* owners_method = locking_method_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700356 uint32_t owners_dex_pc = locking_dex_pc_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700357 // Do this before releasing the lock so that we don't get deflated.
Mathieu Chartierb9001ab2014-10-03 13:28:46 -0700358 size_t num_waiters = num_waiters_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700359 ++num_waiters_;
Andreas Gampe2702d562017-02-06 09:48:00 -0800360
361 // If systrace logging is enabled, first look at the lock owner. Acquiring the monitor's
362 // lock and then re-acquiring the mutator lock can deadlock.
363 bool started_trace = false;
364 if (ATRACE_ENABLED()) {
365 if (owner_ != nullptr) { // Did the owner_ give the lock up?
366 std::ostringstream oss;
367 std::string name;
368 owner_->GetThreadName(name);
369 oss << PrettyContentionInfo(name,
370 owner_->GetTid(),
371 owners_method,
372 owners_dex_pc,
373 num_waiters);
374 // Add info for contending thread.
375 uint32_t pc;
376 ArtMethod* m = self->GetCurrentMethod(&pc);
377 const char* filename;
378 int32_t line_number;
379 TranslateLocation(m, pc, &filename, &line_number);
380 oss << " blocking from "
381 << ArtMethod::PrettyMethod(m) << "(" << (filename != nullptr ? filename : "null")
382 << ":" << line_number << ")";
383 ATRACE_BEGIN(oss.str().c_str());
384 started_trace = true;
385 }
386 }
387
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700388 monitor_lock_.Unlock(self); // Let go of locks in order.
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700389 self->SetMonitorEnterObject(GetObject());
Elliott Hughes5f791332011-09-15 17:45:30 -0700390 {
Hiroshi Yamauchi71cd68d2017-01-25 18:28:12 -0800391 ScopedThreadSuspension tsc(self, kBlocked); // Change to blocked and give up mutator_lock_.
Andreas Gampe2702d562017-02-06 09:48:00 -0800392 uint32_t original_owner_thread_id = 0u;
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700393 {
394 // Reacquire monitor_lock_ without mutator_lock_ for Wait.
395 MutexLock mu2(self, monitor_lock_);
396 if (owner_ != nullptr) { // Did the owner_ give the lock up?
397 original_owner_thread_id = owner_->GetThreadId();
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700398 monitor_contenders_.Wait(self); // Still contended so wait.
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800399 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700400 }
401 if (original_owner_thread_id != 0u) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700402 // Woken from contention.
403 if (log_contention) {
Andreas Gampe111b1092017-06-22 20:28:23 -0700404 uint64_t wait_ms = MilliTime() - wait_start_ms;
405 uint32_t sample_percent;
406 if (wait_ms >= lock_profiling_threshold_) {
407 sample_percent = 100;
408 } else {
409 sample_percent = 100 * wait_ms / lock_profiling_threshold_;
410 }
411 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
412 // Reacquire mutator_lock_ for logging.
413 ScopedObjectAccess soa(self);
414 // Acquire thread-list lock to find thread and keep it from dying until we're done.
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700415 MutexLock mu2(Thread::Current(), *Locks::thread_list_lock_);
Andreas Gampe111b1092017-06-22 20:28:23 -0700416
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700417 // Re-find the owner in case the thread got killed.
418 Thread* original_owner = Runtime::Current()->GetThreadList()->FindThreadByThreadId(
419 original_owner_thread_id);
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700420
Andreas Gampe111b1092017-06-22 20:28:23 -0700421 if (original_owner != nullptr) {
422 pid_t original_owner_tid = original_owner->GetTid();
423 std::string original_owner_name;
424 original_owner->GetThreadName(original_owner_name);
425
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700426 if (wait_ms > kLongWaitMs && owners_method != nullptr) {
Mathieu Chartier36891fe2016-04-28 17:21:08 -0700427 uint32_t pc;
428 ArtMethod* m = self->GetCurrentMethod(&pc);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700429 // TODO: We should maybe check that original_owner is still a live thread.
430 LOG(WARNING) << "Long "
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700431 << PrettyContentionInfo(original_owner_name,
432 original_owner_tid,
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700433 owners_method,
434 owners_dex_pc,
435 num_waiters)
David Sehr709b0702016-10-13 09:12:37 -0700436 << " in " << ArtMethod::PrettyMethod(m) << " for "
437 << PrettyDuration(MsToNs(wait_ms));
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700438 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700439 LogContentionEvent(self,
440 wait_ms,
441 sample_percent,
Andreas Gampe39b98112017-06-01 16:28:27 -0700442 owners_method,
443 owners_dex_pc);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700444 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700445 }
446 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700447 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700448 }
Andreas Gampe2702d562017-02-06 09:48:00 -0800449 if (started_trace) {
450 ATRACE_END();
451 }
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700452 self->SetMonitorEnterObject(nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700453 monitor_lock_.Lock(self); // Reacquire locks in order.
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700454 --num_waiters_;
Elliott Hughesfc861622011-10-17 17:57:47 -0700455 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700456}
457
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800458static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
459 __attribute__((format(printf, 1, 2)));
460
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700461static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700462 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800463 va_list args;
464 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800465 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000466 self->ThrowNewExceptionV("Ljava/lang/IllegalMonitorStateException;", fmt, args);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700467 if (!Runtime::Current()->IsStarted() || VLOG_IS_ON(monitor)) {
Brian Carlstrom64277f32012-03-26 23:53:34 -0700468 std::ostringstream ss;
Ian Rogers62d6c772013-02-27 08:32:07 -0800469 self->Dump(ss);
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700470 LOG(Runtime::Current()->IsStarted() ? ::android::base::INFO : ::android::base::ERROR)
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000471 << self->GetException()->Dump() << "\n" << ss.str();
Brian Carlstrom64277f32012-03-26 23:53:34 -0700472 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800473 va_end(args);
474}
475
Elliott Hughesd4237412012-02-21 11:24:45 -0800476static std::string ThreadToString(Thread* thread) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700477 if (thread == nullptr) {
478 return "nullptr";
Elliott Hughesd4237412012-02-21 11:24:45 -0800479 }
480 std::ostringstream oss;
481 // TODO: alternatively, we could just return the thread's name.
482 oss << *thread;
483 return oss.str();
484}
485
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700486void Monitor::FailedUnlock(mirror::Object* o,
487 uint32_t expected_owner_thread_id,
488 uint32_t found_owner_thread_id,
Elliott Hughesffb465f2012-03-01 18:46:05 -0800489 Monitor* monitor) {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700490 // Acquire thread list lock so threads won't disappear from under us.
Elliott Hughesffb465f2012-03-01 18:46:05 -0800491 std::string current_owner_string;
492 std::string expected_owner_string;
493 std::string found_owner_string;
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700494 uint32_t current_owner_thread_id = 0u;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800495 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700496 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700497 ThreadList* const thread_list = Runtime::Current()->GetThreadList();
498 Thread* expected_owner = thread_list->FindThreadByThreadId(expected_owner_thread_id);
499 Thread* found_owner = thread_list->FindThreadByThreadId(found_owner_thread_id);
500
Elliott Hughesffb465f2012-03-01 18:46:05 -0800501 // Re-read owner now that we hold lock.
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700502 Thread* current_owner = (monitor != nullptr) ? monitor->GetOwner() : nullptr;
503 if (current_owner != nullptr) {
504 current_owner_thread_id = current_owner->GetThreadId();
505 }
Elliott Hughesffb465f2012-03-01 18:46:05 -0800506 // Get short descriptions of the threads involved.
507 current_owner_string = ThreadToString(current_owner);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700508 expected_owner_string = expected_owner != nullptr ? ThreadToString(expected_owner) : "unnamed";
509 found_owner_string = found_owner != nullptr ? ThreadToString(found_owner) : "unnamed";
Elliott Hughesffb465f2012-03-01 18:46:05 -0800510 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700511
512 if (current_owner_thread_id == 0u) {
513 if (found_owner_thread_id == 0u) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800514 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
515 " on thread '%s'",
David Sehr709b0702016-10-13 09:12:37 -0700516 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800517 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800518 } else {
519 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800520 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
521 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800522 found_owner_string.c_str(),
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 }
526 } else {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700527 if (found_owner_thread_id == 0u) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800528 // Race: originally there was no owner, there is now
529 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
530 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800531 current_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700532 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800533 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800534 } else {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700535 if (found_owner_thread_id != current_owner_thread_id) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800536 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800537 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
538 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800539 found_owner_string.c_str(),
540 current_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700541 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800542 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800543 } else {
544 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
545 " on thread '%s",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800546 current_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700547 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800548 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800549 }
550 }
551 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700552}
553
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700554bool Monitor::Unlock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700555 DCHECK(self != nullptr);
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700556 uint32_t owner_thread_id = 0u;
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700557 {
558 MutexLock mu(self, monitor_lock_);
559 Thread* owner = owner_;
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700560 if (owner != nullptr) {
561 owner_thread_id = owner->GetThreadId();
562 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700563 if (owner == self) {
564 // We own the monitor, so nobody else can be in here.
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700565 AtraceMonitorUnlock();
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700566 if (lock_count_ == 0) {
567 owner_ = nullptr;
568 locking_method_ = nullptr;
569 locking_dex_pc_ = 0;
570 // Wake a contender.
571 monitor_contenders_.Signal(self);
572 } else {
573 --lock_count_;
574 }
575 return true;
Elliott Hughes5f791332011-09-15 17:45:30 -0700576 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700577 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700578 // We don't own this, so we're not allowed to unlock it.
579 // The JNI spec says that we should throw IllegalMonitorStateException in this case.
580 FailedUnlock(GetObject(), self->GetThreadId(), owner_thread_id, this);
581 return false;
Elliott Hughes5f791332011-09-15 17:45:30 -0700582}
583
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800584void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
585 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700586 DCHECK(self != nullptr);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800587 DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
Elliott Hughes5f791332011-09-15 17:45:30 -0700588
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700589 monitor_lock_.Lock(self);
590
Elliott Hughes5f791332011-09-15 17:45:30 -0700591 // Make sure that we hold the lock.
592 if (owner_ != self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700593 monitor_lock_.Unlock(self);
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700594 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700595 return;
596 }
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800597
Elliott Hughesdf42c482013-01-09 12:49:02 -0800598 // We need to turn a zero-length timed wait into a regular wait because
599 // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
600 if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
601 why = kWaiting;
602 }
603
Elliott Hughes5f791332011-09-15 17:45:30 -0700604 // Enforce the timeout range.
605 if (ms < 0 || ns < 0 || ns > 999999) {
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700606 monitor_lock_.Unlock(self);
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000607 self->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
Ian Rogersef7d42f2014-01-06 12:55:46 -0800608 "timeout arguments out of range: ms=%" PRId64 " ns=%d", ms, ns);
Elliott Hughes5f791332011-09-15 17:45:30 -0700609 return;
610 }
611
Elliott Hughes5f791332011-09-15 17:45:30 -0700612 /*
613 * Add ourselves to the set of threads waiting on this monitor, and
614 * release our hold. We need to let it go even if we're a few levels
615 * deep in a recursive lock, and we need to restore that later.
616 *
617 * We append to the wait set ahead of clearing the count and owner
618 * fields so the subroutine can check that the calling thread owns
619 * the monitor. Aside from that, the order of member updates is
620 * not order sensitive as we hold the pthread mutex.
621 */
622 AppendToWaitSet(self);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700623 ++num_waiters_;
Ian Rogers0399dde2012-06-06 17:09:28 -0700624 int prev_lock_count = lock_count_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700625 lock_count_ = 0;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700626 owner_ = nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700627 ArtMethod* saved_method = locking_method_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700628 locking_method_ = nullptr;
Ian Rogers0399dde2012-06-06 17:09:28 -0700629 uintptr_t saved_dex_pc = locking_dex_pc_;
630 locking_dex_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700631
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700632 AtraceMonitorUnlock(); // For the implict Unlock() just above. This will only end the deepest
633 // nesting, but that is enough for the visualization, and corresponds to
634 // the single Lock() we do afterwards.
635 AtraceMonitorLock(self, GetObject(), true /* is_wait */);
636
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800637 bool was_interrupted = false;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700638 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700639 // Update thread state. If the GC wakes up, it'll ignore us, knowing
640 // that we won't touch any references in this state, and we'll check
641 // our suspend mode before we transition out.
642 ScopedThreadSuspension sts(self, why);
643
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700644 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700645 MutexLock mu(self, *self->GetWaitMutex());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700646
647 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700648 // non-null a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700649 // up.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700650 DCHECK(self->GetWaitMonitor() == nullptr);
651 self->SetWaitMonitor(this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700652
653 // Release the monitor lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700654 monitor_contenders_.Signal(self);
655 monitor_lock_.Unlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700656
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800657 // Handle the case where the thread was interrupted before we called wait().
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000658 if (self->IsInterrupted()) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800659 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700660 } else {
661 // Wait for a notification or a timeout to occur.
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800662 if (why == kWaiting) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700663 self->GetWaitConditionVariable()->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700664 } else {
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800665 DCHECK(why == kTimedWaiting || why == kSleeping) << why;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700666 self->GetWaitConditionVariable()->TimedWait(self, ms, ns);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700667 }
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000668 was_interrupted = self->IsInterrupted();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700669 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700670 }
671
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800672 {
673 // We reset the thread's wait_monitor_ field after transitioning back to runnable so
674 // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
675 // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
676 // are waiting on "null".)
Ian Rogersdd7624d2014-03-14 17:43:00 -0700677 MutexLock mu(self, *self->GetWaitMutex());
678 DCHECK(self->GetWaitMonitor() != nullptr);
679 self->SetWaitMonitor(nullptr);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800680 }
681
Mathieu Chartierdaed5d82016-03-10 10:49:35 -0800682 // Allocate the interrupted exception not holding the monitor lock since it may cause a GC.
683 // If the GC requires acquiring the monitor for enqueuing cleared references, this would
684 // cause a deadlock if the monitor is held.
685 if (was_interrupted && interruptShouldThrow) {
686 /*
687 * We were interrupted while waiting, or somebody interrupted an
688 * un-interruptible thread earlier and we're bailing out immediately.
689 *
690 * The doc sayeth: "The interrupted status of the current thread is
691 * cleared when this exception is thrown."
692 */
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000693 self->SetInterrupted(false);
Mathieu Chartierdaed5d82016-03-10 10:49:35 -0800694 self->ThrowNewException("Ljava/lang/InterruptedException;", nullptr);
695 }
696
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700697 AtraceMonitorUnlock(); // End Wait().
698
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700699 // Re-acquire the monitor and lock.
Elliott Hughes5f791332011-09-15 17:45:30 -0700700 Lock(self);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700701 monitor_lock_.Lock(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700702 self->GetWaitMutex()->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700703
Elliott Hughes5f791332011-09-15 17:45:30 -0700704 /*
705 * We remove our thread from wait set after restoring the count
706 * and owner fields so the subroutine can check that the calling
707 * thread owns the monitor. Aside from that, the order of member
708 * updates is not order sensitive as we hold the pthread mutex.
709 */
710 owner_ = self;
Ian Rogers0399dde2012-06-06 17:09:28 -0700711 lock_count_ = prev_lock_count;
712 locking_method_ = saved_method;
713 locking_dex_pc_ = saved_dex_pc;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700714 --num_waiters_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700715 RemoveFromWaitSet(self);
716
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700717 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700718}
719
720void Monitor::Notify(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700721 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700722 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700723 // Make sure that we hold the lock.
724 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800725 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700726 return;
727 }
728 // Signal the first waiting thread in the wait set.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700729 while (wait_set_ != nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700730 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700731 wait_set_ = thread->GetWaitNext();
732 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700733
734 // Check to see if the thread is still waiting.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800735 MutexLock wait_mu(self, *thread->GetWaitMutex());
Ian Rogersdd7624d2014-03-14 17:43:00 -0700736 if (thread->GetWaitMonitor() != nullptr) {
737 thread->GetWaitConditionVariable()->Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700738 return;
739 }
740 }
741}
742
743void Monitor::NotifyAll(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700744 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700745 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700746 // Make sure that we hold the lock.
747 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800748 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700749 return;
750 }
751 // Signal all threads in the wait set.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700752 while (wait_set_ != nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700753 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700754 wait_set_ = thread->GetWaitNext();
755 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700756 thread->Notify();
757 }
758}
759
Mathieu Chartier590fee92013-09-13 13:46:47 -0700760bool Monitor::Deflate(Thread* self, mirror::Object* obj) {
761 DCHECK(obj != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700762 // Don't need volatile since we only deflate with mutators suspended.
763 LockWord lw(obj->GetLockWord(false));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700764 // If the lock isn't an inflated monitor, then we don't need to deflate anything.
765 if (lw.GetState() == LockWord::kFatLocked) {
766 Monitor* monitor = lw.FatLockMonitor();
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700767 DCHECK(monitor != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700768 MutexLock mu(self, monitor->monitor_lock_);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700769 // Can't deflate if we have anybody waiting on the CV.
770 if (monitor->num_waiters_ > 0) {
771 return false;
772 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700773 Thread* owner = monitor->owner_;
774 if (owner != nullptr) {
775 // Can't deflate if we are locked and have a hash code.
776 if (monitor->HasHashCode()) {
777 return false;
778 }
779 // Can't deflate if our lock count is too high.
Mathieu Chartier1cf194f2016-11-01 20:13:24 -0700780 if (static_cast<uint32_t>(monitor->lock_count_) > LockWord::kThinLockMaxCount) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700781 return false;
782 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700783 // Deflate to a thin lock.
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700784 LockWord new_lw = LockWord::FromThinLockId(owner->GetThreadId(),
785 monitor->lock_count_,
786 lw.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800787 // Assume no concurrent read barrier state changes as mutators are suspended.
788 obj->SetLockWord(new_lw, false);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700789 VLOG(monitor) << "Deflated " << obj << " to thin lock " << owner->GetTid() << " / "
790 << monitor->lock_count_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700791 } else if (monitor->HasHashCode()) {
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700792 LockWord new_lw = LockWord::FromHashCode(monitor->GetHashCode(), lw.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800793 // Assume no concurrent read barrier state changes as mutators are suspended.
794 obj->SetLockWord(new_lw, false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700795 VLOG(monitor) << "Deflated " << obj << " to hash monitor " << monitor->GetHashCode();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700796 } else {
797 // No lock and no hash, just put an empty lock word inside the object.
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700798 LockWord new_lw = LockWord::FromDefault(lw.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800799 // Assume no concurrent read barrier state changes as mutators are suspended.
800 obj->SetLockWord(new_lw, false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700801 VLOG(monitor) << "Deflated" << obj << " to empty lock word";
Mathieu Chartier590fee92013-09-13 13:46:47 -0700802 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700803 // 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 -0700804 // next GC.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700805 monitor->obj_ = GcRoot<mirror::Object>(nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700806 }
807 return true;
808}
809
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700810void Monitor::Inflate(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code) {
Andreas Gampe74240812014-04-17 10:35:09 -0700811 DCHECK(self != nullptr);
812 DCHECK(obj != nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700813 // Allocate and acquire a new monitor.
Andreas Gampe74240812014-04-17 10:35:09 -0700814 Monitor* m = MonitorPool::CreateMonitor(self, owner, obj, hash_code);
815 DCHECK(m != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700816 if (m->Install(self)) {
Haifeng Li86ab7912014-05-16 10:47:59 +0800817 if (owner != nullptr) {
818 VLOG(monitor) << "monitor: thread" << owner->GetThreadId()
Andreas Gampe74240812014-04-17 10:35:09 -0700819 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800820 } else {
821 VLOG(monitor) << "monitor: Inflate with hashcode " << hash_code
Andreas Gampe74240812014-04-17 10:35:09 -0700822 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800823 }
Andreas Gampe74240812014-04-17 10:35:09 -0700824 Runtime::Current()->GetMonitorList()->Add(m);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700825 CHECK_EQ(obj->GetLockWord(true).GetState(), LockWord::kFatLocked);
Andreas Gampe74240812014-04-17 10:35:09 -0700826 } else {
827 MonitorPool::ReleaseMonitor(self, m);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700828 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700829}
830
Mathieu Chartier0cd81352014-05-22 16:48:55 -0700831void Monitor::InflateThinLocked(Thread* self, Handle<mirror::Object> obj, LockWord lock_word,
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700832 uint32_t hash_code) {
833 DCHECK_EQ(lock_word.GetState(), LockWord::kThinLocked);
834 uint32_t owner_thread_id = lock_word.ThinLockOwner();
835 if (owner_thread_id == self->GetThreadId()) {
836 // We own the monitor, we can easily inflate it.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700837 Inflate(self, self, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700838 } else {
839 ThreadList* thread_list = Runtime::Current()->GetThreadList();
840 // Suspend the owner, inflate. First change to blocked and give up mutator_lock_.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700841 self->SetMonitorEnterObject(obj.Get());
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700842 bool timed_out;
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700843 Thread* owner;
844 {
845 ScopedThreadSuspension sts(self, kBlocked);
846 owner = thread_list->SuspendThreadByThreadId(owner_thread_id, false, &timed_out);
847 }
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700848 if (owner != nullptr) {
849 // We succeeded in suspending the thread, check the lock's status didn't change.
850 lock_word = obj->GetLockWord(true);
851 if (lock_word.GetState() == LockWord::kThinLocked &&
852 lock_word.ThinLockOwner() == owner_thread_id) {
853 // Go ahead and inflate the lock.
854 Inflate(self, owner, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700855 }
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700856 thread_list->Resume(owner, false);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700857 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700858 self->SetMonitorEnterObject(nullptr);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700859 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700860}
861
Ian Rogers719d1a32014-03-06 12:13:39 -0800862// Fool annotalysis into thinking that the lock on obj is acquired.
863static mirror::Object* FakeLock(mirror::Object* obj)
864 EXCLUSIVE_LOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
865 return obj;
866}
867
868// Fool annotalysis into thinking that the lock on obj is release.
869static mirror::Object* FakeUnlock(mirror::Object* obj)
870 UNLOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
871 return obj;
872}
873
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700874mirror::Object* Monitor::MonitorEnter(Thread* self, mirror::Object* obj, bool trylock) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700875 DCHECK(self != nullptr);
876 DCHECK(obj != nullptr);
Mathieu Chartier2d096c92015-10-12 16:18:20 -0700877 self->AssertThreadSuspensionIsAllowable();
Ian Rogers719d1a32014-03-06 12:13:39 -0800878 obj = FakeLock(obj);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700879 uint32_t thread_id = self->GetThreadId();
880 size_t contention_count = 0;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700881 StackHandleScope<1> hs(self);
882 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700883 while (true) {
Hans Boehmb3da36c2016-12-15 13:12:59 -0800884 // We initially read the lockword with ordinary Java/relaxed semantics. When stronger
885 // semantics are needed, we address it below. Since GetLockWord bottoms out to a relaxed load,
886 // we can fix it later, in an infrequently executed case, with a fence.
887 LockWord lock_word = h_obj->GetLockWord(false);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700888 switch (lock_word.GetState()) {
889 case LockWord::kUnlocked: {
Hans Boehmb3da36c2016-12-15 13:12:59 -0800890 // No ordering required for preceding lockword read, since we retest.
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700891 LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0, lock_word.GCState()));
Hans Boehmb3da36c2016-12-15 13:12:59 -0800892 if (h_obj->CasLockWordWeakAcquire(lock_word, thin_locked)) {
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700893 AtraceMonitorLock(self, h_obj.Get(), false /* is_wait */);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700894 return h_obj.Get(); // Success!
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700895 }
896 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -0700897 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700898 case LockWord::kThinLocked: {
899 uint32_t owner_thread_id = lock_word.ThinLockOwner();
900 if (owner_thread_id == thread_id) {
Hans Boehmb3da36c2016-12-15 13:12:59 -0800901 // No ordering required for initial lockword read.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700902 // We own the lock, increase the recursion count.
903 uint32_t new_count = lock_word.ThinLockCount() + 1;
904 if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700905 LockWord thin_locked(LockWord::FromThinLockId(thread_id,
906 new_count,
907 lock_word.GCState()));
Hans Boehmb3da36c2016-12-15 13:12:59 -0800908 // Only this thread pays attention to the count. Thus there is no need for stronger
909 // than relaxed memory ordering.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800910 if (!kUseReadBarrier) {
Hans Boehmb3da36c2016-12-15 13:12:59 -0800911 h_obj->SetLockWord(thin_locked, false /* volatile */);
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700912 AtraceMonitorLock(self, h_obj.Get(), false /* is_wait */);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800913 return h_obj.Get(); // Success!
914 } else {
915 // Use CAS to preserve the read barrier state.
Hans Boehmb3da36c2016-12-15 13:12:59 -0800916 if (h_obj->CasLockWordWeakRelaxed(lock_word, thin_locked)) {
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700917 AtraceMonitorLock(self, h_obj.Get(), false /* is_wait */);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800918 return h_obj.Get(); // Success!
919 }
920 }
921 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -0700922 } else {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700923 // We'd overflow the recursion count, so inflate the monitor.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700924 InflateThinLocked(self, h_obj, lock_word, 0);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700925 }
926 } else {
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700927 if (trylock) {
928 return nullptr;
929 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700930 // Contention.
931 contention_count++;
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700932 Runtime* runtime = Runtime::Current();
Hans Boehmb3da36c2016-12-15 13:12:59 -0800933 if (contention_count <= runtime->GetMaxSpinsBeforeThinLockInflation()) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700934 // TODO: Consider switching the thread state to kBlocked when we are yielding.
Mathieu Chartier251755c2014-07-15 18:10:25 -0700935 // Use sched_yield instead of NanoSleep since NanoSleep can wait much longer than the
936 // parameter you pass in. This can cause thread suspension to take excessively long
Mathieu Chartierb363f662014-07-16 13:28:58 -0700937 // and make long pauses. See b/16307460.
Hans Boehmb3da36c2016-12-15 13:12:59 -0800938 // TODO: We should literally spin first, without sched_yield. Sched_yield either does
939 // nothing (at significant expense), or guarantees that we wait at least microseconds.
940 // If the owner is running, I would expect the median lock hold time to be hundreds
941 // of nanoseconds or less.
Mathieu Chartier251755c2014-07-15 18:10:25 -0700942 sched_yield();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700943 } else {
944 contention_count = 0;
Hans Boehmb3da36c2016-12-15 13:12:59 -0800945 // No ordering required for initial lockword read. Install rereads it anyway.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700946 InflateThinLocked(self, h_obj, lock_word, 0);
Elliott Hughes5f791332011-09-15 17:45:30 -0700947 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700948 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700949 continue; // Start from the beginning.
Elliott Hughes5f791332011-09-15 17:45:30 -0700950 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700951 case LockWord::kFatLocked: {
Hans Boehmb3da36c2016-12-15 13:12:59 -0800952 // We should have done an acquire read of the lockword initially, to ensure
953 // visibility of the monitor data structure. Use an explicit fence instead.
954 QuasiAtomic::ThreadFenceAcquire();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700955 Monitor* mon = lock_word.FatLockMonitor();
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700956 if (trylock) {
957 return mon->TryLock(self) ? h_obj.Get() : nullptr;
958 } else {
959 mon->Lock(self);
960 return h_obj.Get(); // Success!
961 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700962 }
Ian Rogers719d1a32014-03-06 12:13:39 -0800963 case LockWord::kHashCode:
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700964 // Inflate with the existing hashcode.
Hans Boehmb3da36c2016-12-15 13:12:59 -0800965 // Again no ordering required for initial lockword read, since we don't rely
966 // on the visibility of any prior computation.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700967 Inflate(self, nullptr, h_obj.Get(), lock_word.GetHashCode());
Ian Rogers719d1a32014-03-06 12:13:39 -0800968 continue; // Start from the beginning.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700969 default: {
970 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700971 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700972 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700973 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700974 }
975}
976
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800977bool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700978 DCHECK(self != nullptr);
979 DCHECK(obj != nullptr);
Mathieu Chartier2d096c92015-10-12 16:18:20 -0700980 self->AssertThreadSuspensionIsAllowable();
Ian Rogers719d1a32014-03-06 12:13:39 -0800981 obj = FakeUnlock(obj);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700982 StackHandleScope<1> hs(self);
983 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800984 while (true) {
985 LockWord lock_word = obj->GetLockWord(true);
986 switch (lock_word.GetState()) {
987 case LockWord::kHashCode:
988 // Fall-through.
989 case LockWord::kUnlocked:
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700990 FailedUnlock(h_obj.Get(), self->GetThreadId(), 0u, nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700991 return false; // Failure.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800992 case LockWord::kThinLocked: {
993 uint32_t thread_id = self->GetThreadId();
994 uint32_t owner_thread_id = lock_word.ThinLockOwner();
995 if (owner_thread_id != thread_id) {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700996 FailedUnlock(h_obj.Get(), thread_id, owner_thread_id, nullptr);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800997 return false; // Failure.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700998 } else {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800999 // We own the lock, decrease the recursion count.
1000 LockWord new_lw = LockWord::Default();
1001 if (lock_word.ThinLockCount() != 0) {
1002 uint32_t new_count = lock_word.ThinLockCount() - 1;
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001003 new_lw = LockWord::FromThinLockId(thread_id, new_count, lock_word.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001004 } else {
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001005 new_lw = LockWord::FromDefault(lock_word.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001006 }
1007 if (!kUseReadBarrier) {
1008 DCHECK_EQ(new_lw.ReadBarrierState(), 0U);
Hans Boehmb3da36c2016-12-15 13:12:59 -08001009 // TODO: This really only needs memory_order_release, but we currently have
1010 // no way to specify that. In fact there seem to be no legitimate uses of SetLockWord
1011 // with a final argument of true. This slows down x86 and ARMv7, but probably not v8.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001012 h_obj->SetLockWord(new_lw, true);
Andreas Gampe6e759ad2016-05-17 10:13:10 -07001013 AtraceMonitorUnlock();
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001014 // Success!
1015 return true;
1016 } else {
1017 // Use CAS to preserve the read barrier state.
Hans Boehmb3da36c2016-12-15 13:12:59 -08001018 if (h_obj->CasLockWordWeakRelease(lock_word, new_lw)) {
Andreas Gampe6e759ad2016-05-17 10:13:10 -07001019 AtraceMonitorUnlock();
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001020 // Success!
1021 return true;
1022 }
1023 }
1024 continue; // Go again.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001025 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001026 }
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001027 case LockWord::kFatLocked: {
1028 Monitor* mon = lock_word.FatLockMonitor();
1029 return mon->Unlock(self);
1030 }
1031 default: {
1032 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1033 return false;
1034 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001035 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001036 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001037}
1038
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001039void Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
Elliott Hughes4cd121e2013-01-07 17:35:41 -08001040 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001041 DCHECK(self != nullptr);
1042 DCHECK(obj != nullptr);
1043 LockWord lock_word = obj->GetLockWord(true);
Ian Rogers43c69cc2014-08-15 11:09:28 -07001044 while (lock_word.GetState() != LockWord::kFatLocked) {
1045 switch (lock_word.GetState()) {
1046 case LockWord::kHashCode:
1047 // Fall-through.
1048 case LockWord::kUnlocked:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001049 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
1050 return; // Failure.
Ian Rogers43c69cc2014-08-15 11:09:28 -07001051 case LockWord::kThinLocked: {
1052 uint32_t thread_id = self->GetThreadId();
1053 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1054 if (owner_thread_id != thread_id) {
1055 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
1056 return; // Failure.
1057 } else {
1058 // We own the lock, inflate to enqueue ourself on the Monitor. May fail spuriously so
1059 // re-load.
1060 Inflate(self, self, obj, 0);
1061 lock_word = obj->GetLockWord(true);
1062 }
1063 break;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001064 }
Ian Rogers43c69cc2014-08-15 11:09:28 -07001065 case LockWord::kFatLocked: // Unreachable given the loop condition above. Fall-through.
1066 default: {
1067 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1068 return;
1069 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001070 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001071 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001072 Monitor* mon = lock_word.FatLockMonitor();
1073 mon->Wait(self, ms, ns, interruptShouldThrow, why);
Elliott Hughes5f791332011-09-15 17:45:30 -07001074}
1075
Ian Rogers13c479e2013-10-11 07:59:01 -07001076void Monitor::DoNotify(Thread* self, mirror::Object* obj, bool notify_all) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001077 DCHECK(self != nullptr);
1078 DCHECK(obj != nullptr);
1079 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001080 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001081 case LockWord::kHashCode:
1082 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001083 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -08001084 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001085 return; // Failure.
1086 case LockWord::kThinLocked: {
1087 uint32_t thread_id = self->GetThreadId();
1088 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1089 if (owner_thread_id != thread_id) {
1090 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
1091 return; // Failure.
1092 } else {
1093 // We own the lock but there's no Monitor and therefore no waiters.
1094 return; // Success.
1095 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001096 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001097 case LockWord::kFatLocked: {
1098 Monitor* mon = lock_word.FatLockMonitor();
1099 if (notify_all) {
1100 mon->NotifyAll(self);
1101 } else {
1102 mon->Notify(self);
1103 }
1104 return; // Success.
1105 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001106 default: {
1107 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1108 return;
1109 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001110 }
1111}
1112
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001113uint32_t Monitor::GetLockOwnerThreadId(mirror::Object* obj) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001114 DCHECK(obj != nullptr);
1115 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001116 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001117 case LockWord::kHashCode:
1118 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001119 case LockWord::kUnlocked:
1120 return ThreadList::kInvalidThreadId;
1121 case LockWord::kThinLocked:
1122 return lock_word.ThinLockOwner();
1123 case LockWord::kFatLocked: {
1124 Monitor* mon = lock_word.FatLockMonitor();
1125 return mon->GetOwnerThreadId();
Elliott Hughes5f791332011-09-15 17:45:30 -07001126 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001127 default: {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001128 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001129 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001130 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001131 }
1132}
1133
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001134void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
Ian Rogersd803bc72014-04-01 15:33:03 -07001135 // Determine the wait message and object we're waiting or blocked upon.
1136 mirror::Object* pretty_object = nullptr;
1137 const char* wait_message = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001138 uint32_t lock_owner = ThreadList::kInvalidThreadId;
Ian Rogersd803bc72014-04-01 15:33:03 -07001139 ThreadState state = thread->GetState();
Elliott Hughesb4e94fd2013-01-08 14:41:26 -08001140 if (state == kWaiting || state == kTimedWaiting || state == kSleeping) {
Ian Rogersd803bc72014-04-01 15:33:03 -07001141 wait_message = (state == kSleeping) ? " - sleeping on " : " - waiting on ";
1142 Thread* self = Thread::Current();
1143 MutexLock mu(self, *thread->GetWaitMutex());
1144 Monitor* monitor = thread->GetWaitMonitor();
1145 if (monitor != nullptr) {
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001146 pretty_object = monitor->GetObject();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001147 }
Elliott Hughes34e06962012-04-09 13:55:55 -07001148 } else if (state == kBlocked) {
Ian Rogersd803bc72014-04-01 15:33:03 -07001149 wait_message = " - waiting to lock ";
1150 pretty_object = thread->GetMonitorEnterObject();
1151 if (pretty_object != nullptr) {
Hiroshi Yamauchi7b08ae42016-10-04 15:20:36 -07001152 if (kUseReadBarrier && Thread::Current()->GetIsGcMarking()) {
1153 // We may call Thread::Dump() in the middle of the CC thread flip and this thread's stack
1154 // may have not been flipped yet and "pretty_object" may be a from-space (stale) ref, in
1155 // which case the GetLockOwnerThreadId() call below will crash. So explicitly mark/forward
1156 // it here.
1157 pretty_object = ReadBarrier::Mark(pretty_object);
1158 }
Ian Rogersd803bc72014-04-01 15:33:03 -07001159 lock_owner = pretty_object->GetLockOwnerThreadId();
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001160 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001161 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001162
Ian Rogersd803bc72014-04-01 15:33:03 -07001163 if (wait_message != nullptr) {
1164 if (pretty_object == nullptr) {
1165 os << wait_message << "an unknown object";
1166 } else {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001167 if ((pretty_object->GetLockWord(true).GetState() == LockWord::kThinLocked) &&
Ian Rogersd803bc72014-04-01 15:33:03 -07001168 Locks::mutator_lock_->IsExclusiveHeld(Thread::Current())) {
1169 // Getting the identity hashcode here would result in lock inflation and suspension of the
1170 // current thread, which isn't safe if this is the only runnable thread.
1171 os << wait_message << StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)",
1172 reinterpret_cast<intptr_t>(pretty_object),
David Sehr709b0702016-10-13 09:12:37 -07001173 pretty_object->PrettyTypeOf().c_str());
Ian Rogersd803bc72014-04-01 15:33:03 -07001174 } else {
1175 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
Mathieu Chartier49361592015-01-22 16:36:10 -08001176 // Call PrettyTypeOf before IdentityHashCode since IdentityHashCode can cause thread
1177 // suspension and move pretty_object.
David Sehr709b0702016-10-13 09:12:37 -07001178 const std::string pretty_type(pretty_object->PrettyTypeOf());
Ian Rogersd803bc72014-04-01 15:33:03 -07001179 os << wait_message << StringPrintf("<0x%08x> (a %s)", pretty_object->IdentityHashCode(),
Mathieu Chartier49361592015-01-22 16:36:10 -08001180 pretty_type.c_str());
Ian Rogersd803bc72014-04-01 15:33:03 -07001181 }
1182 }
1183 // - waiting to lock <0x613f83d8> (a java.lang.Object) held by thread 5
1184 if (lock_owner != ThreadList::kInvalidThreadId) {
1185 os << " held by thread " << lock_owner;
1186 }
1187 os << "\n";
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001188 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001189}
1190
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001191mirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -08001192 // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
1193 // definition of contended that includes a monitor a thread is trying to enter...
Ian Rogersdd7624d2014-03-14 17:43:00 -07001194 mirror::Object* result = thread->GetMonitorEnterObject();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001195 if (result == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001196 // ...but also a monitor that the thread is waiting on.
Ian Rogersdd7624d2014-03-14 17:43:00 -07001197 MutexLock mu(Thread::Current(), *thread->GetWaitMutex());
1198 Monitor* monitor = thread->GetWaitMonitor();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001199 if (monitor != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001200 result = monitor->GetObject();
Elliott Hughesf9501702013-01-11 11:22:27 -08001201 }
1202 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001203 return result;
Elliott Hughesf9501702013-01-11 11:22:27 -08001204}
1205
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001206void Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
Andreas Gampe760172c2014-08-16 13:41:10 -07001207 void* callback_context, bool abort_on_failure) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001208 ArtMethod* m = stack_visitor->GetMethod();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001209 CHECK(m != nullptr);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001210
1211 // Native methods are an easy special case.
1212 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
1213 if (m->IsNative()) {
1214 if (m->IsSynchronized()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001215 mirror::Object* jni_this =
1216 stack_visitor->GetCurrentHandleScope(sizeof(void*))->GetReference(0);
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001217 callback(jni_this, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001218 }
1219 return;
1220 }
1221
jeffhao61f916c2012-10-25 17:48:51 -07001222 // Proxy methods should not be synchronized.
1223 if (m->IsProxyMethod()) {
1224 CHECK(!m->IsSynchronized());
1225 return;
1226 }
1227
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001228 // Is there any reason to believe there's any synchronization in this method?
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001229 const DexFile::CodeItem* code_item = m->GetCodeItem();
David Sehr709b0702016-10-13 09:12:37 -07001230 CHECK(code_item != nullptr) << m->PrettyMethod();
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001231 if (code_item->tries_size_ == 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001232 return; // No "tries" implies no synchronization, so no held locks to report.
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001233 }
1234
Andreas Gampe760172c2014-08-16 13:41:10 -07001235 // Get the dex pc. If abort_on_failure is false, GetDexPc will not abort in the case it cannot
1236 // find the dex pc, and instead return kDexNoIndex. Then bail out, as it indicates we have an
1237 // inconsistent stack anyways.
1238 uint32_t dex_pc = stack_visitor->GetDexPc(abort_on_failure);
1239 if (!abort_on_failure && dex_pc == DexFile::kDexNoIndex) {
David Sehr709b0702016-10-13 09:12:37 -07001240 LOG(ERROR) << "Could not find dex_pc for " << m->PrettyMethod();
Andreas Gampe760172c2014-08-16 13:41:10 -07001241 return;
1242 }
1243
Elliott Hughes80537bb2013-01-04 16:37:26 -08001244 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
1245 // the locks held in this stack frame.
1246 std::vector<uint32_t> monitor_enter_dex_pcs;
Andreas Gampe760172c2014-08-16 13:41:10 -07001247 verifier::MethodVerifier::FindLocksAtDexPc(m, dex_pc, &monitor_enter_dex_pcs);
Mathieu Chartiere6a8eec2015-01-06 14:17:57 -08001248 for (uint32_t monitor_dex_pc : monitor_enter_dex_pcs) {
Elliott Hughes80537bb2013-01-04 16:37:26 -08001249 // The verifier works in terms of the dex pcs of the monitor-enter instructions.
1250 // We want the registers used by those instructions (so we can read the values out of them).
Sebastien Hertz0f7c9332015-11-05 15:57:30 +01001251 const Instruction* monitor_enter_instruction =
1252 Instruction::At(&code_item->insns_[monitor_dex_pc]);
Elliott Hughes80537bb2013-01-04 16:37:26 -08001253
1254 // Quick sanity check.
Sebastien Hertz0f7c9332015-11-05 15:57:30 +01001255 CHECK_EQ(monitor_enter_instruction->Opcode(), Instruction::MONITOR_ENTER)
1256 << "expected monitor-enter @" << monitor_dex_pc << "; was "
1257 << reinterpret_cast<const void*>(monitor_enter_instruction);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001258
Sebastien Hertz0f7c9332015-11-05 15:57:30 +01001259 uint16_t monitor_register = monitor_enter_instruction->VRegA();
Nicolas Geoffray15b9d522015-03-12 15:05:13 +00001260 uint32_t value;
1261 bool success = stack_visitor->GetVReg(m, monitor_register, kReferenceVReg, &value);
1262 CHECK(success) << "Failed to read v" << monitor_register << " of kind "
David Sehr709b0702016-10-13 09:12:37 -07001263 << kReferenceVReg << " in method " << m->PrettyMethod();
Nicolas Geoffray15b9d522015-03-12 15:05:13 +00001264 mirror::Object* o = reinterpret_cast<mirror::Object*>(value);
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001265 callback(o, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001266 }
1267}
1268
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001269bool Monitor::IsValidLockWord(LockWord lock_word) {
1270 switch (lock_word.GetState()) {
1271 case LockWord::kUnlocked:
1272 // Nothing to check.
1273 return true;
1274 case LockWord::kThinLocked:
1275 // Basic sanity check of owner.
1276 return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
1277 case LockWord::kFatLocked: {
1278 // Check the monitor appears in the monitor list.
1279 Monitor* mon = lock_word.FatLockMonitor();
1280 MonitorList* list = Runtime::Current()->GetMonitorList();
1281 MutexLock mu(Thread::Current(), list->monitor_list_lock_);
1282 for (Monitor* list_mon : list->list_) {
1283 if (mon == list_mon) {
1284 return true; // Found our monitor.
1285 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001286 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001287 return false; // Fail - unowned monitor in an object.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001288 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001289 case LockWord::kHashCode:
1290 return true;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001291 default:
1292 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001293 UNREACHABLE();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001294 }
1295}
1296
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001297bool Monitor::IsLocked() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001298 MutexLock mu(Thread::Current(), monitor_lock_);
1299 return owner_ != nullptr;
1300}
1301
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -07001302void Monitor::TranslateLocation(ArtMethod* method,
1303 uint32_t dex_pc,
1304 const char** source_file,
1305 int32_t* line_number) {
jeffhao33dc7712011-11-09 17:54:24 -08001306 // If method is null, location is unknown
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001307 if (method == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001308 *source_file = "";
1309 *line_number = 0;
jeffhao33dc7712011-11-09 17:54:24 -08001310 return;
1311 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001312 *source_file = method->GetDeclaringClassSourceFile();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001313 if (*source_file == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001314 *source_file = "";
Elliott Hughes12c51e32012-01-17 20:25:05 -08001315 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001316 *line_number = method->GetLineNumFromDexPC(dex_pc);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001317}
1318
1319uint32_t Monitor::GetOwnerThreadId() {
1320 MutexLock mu(Thread::Current(), monitor_lock_);
1321 Thread* owner = owner_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001322 if (owner != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001323 return owner->GetThreadId();
1324 } else {
1325 return ThreadList::kInvalidThreadId;
1326 }
jeffhao33dc7712011-11-09 17:54:24 -08001327}
1328
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001329MonitorList::MonitorList()
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001330 : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock", kMonitorListLock),
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001331 monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001332}
1333
1334MonitorList::~MonitorList() {
Andreas Gampe74240812014-04-17 10:35:09 -07001335 Thread* self = Thread::Current();
1336 MutexLock mu(self, monitor_list_lock_);
1337 // Release all monitors to the pool.
1338 // TODO: Is it an invariant that *all* open monitors are in the list? Then we could
1339 // clear faster in the pool.
1340 MonitorPool::ReleaseMonitors(self, &list_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001341}
1342
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001343void MonitorList::DisallowNewMonitors() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001344 CHECK(!kUseReadBarrier);
Ian Rogers50b35e22012-10-04 10:09:15 -07001345 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001346 allow_new_monitors_ = false;
1347}
1348
1349void MonitorList::AllowNewMonitors() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001350 CHECK(!kUseReadBarrier);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001351 Thread* self = Thread::Current();
1352 MutexLock mu(self, monitor_list_lock_);
1353 allow_new_monitors_ = true;
1354 monitor_add_condition_.Broadcast(self);
1355}
1356
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001357void MonitorList::BroadcastForNewMonitors() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001358 Thread* self = Thread::Current();
1359 MutexLock mu(self, monitor_list_lock_);
1360 monitor_add_condition_.Broadcast(self);
1361}
1362
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001363void MonitorList::Add(Monitor* m) {
1364 Thread* self = Thread::Current();
1365 MutexLock mu(self, monitor_list_lock_);
Hiroshi Yamauchif1c6f872017-01-06 12:23:47 -08001366 // CMS needs this to block for concurrent reference processing because an object allocated during
1367 // the GC won't be marked and concurrent reference processing would incorrectly clear the JNI weak
1368 // ref. But CC (kUseReadBarrier == true) doesn't because of the to-space invariant.
1369 while (!kUseReadBarrier && UNLIKELY(!allow_new_monitors_)) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -07001370 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
1371 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -08001372 self->CheckEmptyCheckpointFromWeakRefAccess(&monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001373 monitor_add_condition_.WaitHoldingLocks(self);
1374 }
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001375 list_.push_front(m);
1376}
1377
Mathieu Chartier97509952015-07-13 14:35:43 -07001378void MonitorList::SweepMonitorList(IsMarkedVisitor* visitor) {
Andreas Gampe74240812014-04-17 10:35:09 -07001379 Thread* self = Thread::Current();
1380 MutexLock mu(self, monitor_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001381 for (auto it = list_.begin(); it != list_.end(); ) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001382 Monitor* m = *it;
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001383 // Disable the read barrier in GetObject() as this is called by GC.
1384 mirror::Object* obj = m->GetObject<kWithoutReadBarrier>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001385 // The object of a monitor can be null if we have deflated it.
Mathieu Chartier97509952015-07-13 14:35:43 -07001386 mirror::Object* new_obj = obj != nullptr ? visitor->IsMarked(obj) : nullptr;
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001387 if (new_obj == nullptr) {
1388 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001389 << obj;
Andreas Gampe74240812014-04-17 10:35:09 -07001390 MonitorPool::ReleaseMonitor(self, m);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001391 it = list_.erase(it);
1392 } else {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001393 m->SetObject(new_obj);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001394 ++it;
1395 }
1396 }
1397}
1398
Hans Boehm6fe97e02016-05-04 18:35:57 -07001399size_t MonitorList::Size() {
1400 Thread* self = Thread::Current();
1401 MutexLock mu(self, monitor_list_lock_);
1402 return list_.size();
1403}
1404
Mathieu Chartier97509952015-07-13 14:35:43 -07001405class MonitorDeflateVisitor : public IsMarkedVisitor {
1406 public:
1407 MonitorDeflateVisitor() : self_(Thread::Current()), deflate_count_(0) {}
1408
1409 virtual mirror::Object* IsMarked(mirror::Object* object) OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001410 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001411 if (Monitor::Deflate(self_, object)) {
1412 DCHECK_NE(object->GetLockWord(true).GetState(), LockWord::kFatLocked);
1413 ++deflate_count_;
1414 // If we deflated, return null so that the monitor gets removed from the array.
1415 return nullptr;
1416 }
1417 return object; // Monitor was not deflated.
1418 }
1419
1420 Thread* const self_;
1421 size_t deflate_count_;
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001422};
1423
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001424size_t MonitorList::DeflateMonitors() {
Mathieu Chartier97509952015-07-13 14:35:43 -07001425 MonitorDeflateVisitor visitor;
1426 Locks::mutator_lock_->AssertExclusiveHeld(visitor.self_);
1427 SweepMonitorList(&visitor);
1428 return visitor.deflate_count_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001429}
1430
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001431MonitorInfo::MonitorInfo(mirror::Object* obj) : owner_(nullptr), entry_count_(0) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001432 DCHECK(obj != nullptr);
1433 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001434 switch (lock_word.GetState()) {
1435 case LockWord::kUnlocked:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001436 // Fall-through.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001437 case LockWord::kForwardingAddress:
1438 // Fall-through.
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001439 case LockWord::kHashCode:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001440 break;
1441 case LockWord::kThinLocked:
1442 owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
1443 entry_count_ = 1 + lock_word.ThinLockCount();
1444 // Thin locks have no waiters.
1445 break;
1446 case LockWord::kFatLocked: {
1447 Monitor* mon = lock_word.FatLockMonitor();
1448 owner_ = mon->owner_;
1449 entry_count_ = 1 + mon->lock_count_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001450 for (Thread* waiter = mon->wait_set_; waiter != nullptr; waiter = waiter->GetWaitNext()) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001451 waiters_.push_back(waiter);
1452 }
1453 break;
Elliott Hughesf327e072013-01-09 16:01:26 -08001454 }
1455 }
1456}
1457
Elliott Hughes5f791332011-09-15 17:45:30 -07001458} // namespace art