blob: a617818c3f697ef804f51fcc66ebf3131699c384 [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) {
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700404 uint32_t original_owner_tid = 0;
405 std::string original_owner_name;
406 {
407 MutexLock mu2(Thread::Current(), *Locks::thread_list_lock_);
408 // Re-find the owner in case the thread got killed.
409 Thread* original_owner = Runtime::Current()->GetThreadList()->FindThreadByThreadId(
410 original_owner_thread_id);
411 // Do not do any work that requires the mutator lock.
412 if (original_owner != nullptr) {
413 original_owner_tid = original_owner->GetTid();
414 original_owner->GetThreadName(original_owner_name);
415 }
416 }
417
418 if (original_owner_tid != 0u) {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700419 uint64_t wait_ms = MilliTime() - wait_start_ms;
420 uint32_t sample_percent;
421 if (wait_ms >= lock_profiling_threshold_) {
422 sample_percent = 100;
423 } else {
424 sample_percent = 100 * wait_ms / lock_profiling_threshold_;
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700425 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700426 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
Hiroshi Yamauchi71cd68d2017-01-25 18:28:12 -0800427 // Reacquire mutator_lock_ for logging.
428 ScopedObjectAccess soa(self);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700429 if (wait_ms > kLongWaitMs && owners_method != nullptr) {
Mathieu Chartier36891fe2016-04-28 17:21:08 -0700430 uint32_t pc;
431 ArtMethod* m = self->GetCurrentMethod(&pc);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700432 // TODO: We should maybe check that original_owner is still a live thread.
433 LOG(WARNING) << "Long "
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700434 << PrettyContentionInfo(original_owner_name,
435 original_owner_tid,
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700436 owners_method,
437 owners_dex_pc,
438 num_waiters)
David Sehr709b0702016-10-13 09:12:37 -0700439 << " in " << ArtMethod::PrettyMethod(m) << " for "
440 << PrettyDuration(MsToNs(wait_ms));
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700441 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700442 LogContentionEvent(self,
443 wait_ms,
444 sample_percent,
Andreas Gampe39b98112017-06-01 16:28:27 -0700445 owners_method,
446 owners_dex_pc);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700447 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700448 }
449 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700450 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700451 }
Andreas Gampe2702d562017-02-06 09:48:00 -0800452 if (started_trace) {
453 ATRACE_END();
454 }
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700455 self->SetMonitorEnterObject(nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700456 monitor_lock_.Lock(self); // Reacquire locks in order.
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700457 --num_waiters_;
Elliott Hughesfc861622011-10-17 17:57:47 -0700458 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700459}
460
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800461static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
462 __attribute__((format(printf, 1, 2)));
463
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700464static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700465 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800466 va_list args;
467 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800468 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000469 self->ThrowNewExceptionV("Ljava/lang/IllegalMonitorStateException;", fmt, args);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700470 if (!Runtime::Current()->IsStarted() || VLOG_IS_ON(monitor)) {
Brian Carlstrom64277f32012-03-26 23:53:34 -0700471 std::ostringstream ss;
Ian Rogers62d6c772013-02-27 08:32:07 -0800472 self->Dump(ss);
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700473 LOG(Runtime::Current()->IsStarted() ? ::android::base::INFO : ::android::base::ERROR)
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000474 << self->GetException()->Dump() << "\n" << ss.str();
Brian Carlstrom64277f32012-03-26 23:53:34 -0700475 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800476 va_end(args);
477}
478
Elliott Hughesd4237412012-02-21 11:24:45 -0800479static std::string ThreadToString(Thread* thread) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700480 if (thread == nullptr) {
481 return "nullptr";
Elliott Hughesd4237412012-02-21 11:24:45 -0800482 }
483 std::ostringstream oss;
484 // TODO: alternatively, we could just return the thread's name.
485 oss << *thread;
486 return oss.str();
487}
488
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700489void Monitor::FailedUnlock(mirror::Object* o,
490 uint32_t expected_owner_thread_id,
491 uint32_t found_owner_thread_id,
Elliott Hughesffb465f2012-03-01 18:46:05 -0800492 Monitor* monitor) {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700493 // Acquire thread list lock so threads won't disappear from under us.
Elliott Hughesffb465f2012-03-01 18:46:05 -0800494 std::string current_owner_string;
495 std::string expected_owner_string;
496 std::string found_owner_string;
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700497 uint32_t current_owner_thread_id = 0u;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800498 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700499 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700500 ThreadList* const thread_list = Runtime::Current()->GetThreadList();
501 Thread* expected_owner = thread_list->FindThreadByThreadId(expected_owner_thread_id);
502 Thread* found_owner = thread_list->FindThreadByThreadId(found_owner_thread_id);
503
Elliott Hughesffb465f2012-03-01 18:46:05 -0800504 // Re-read owner now that we hold lock.
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700505 Thread* current_owner = (monitor != nullptr) ? monitor->GetOwner() : nullptr;
506 if (current_owner != nullptr) {
507 current_owner_thread_id = current_owner->GetThreadId();
508 }
Elliott Hughesffb465f2012-03-01 18:46:05 -0800509 // Get short descriptions of the threads involved.
510 current_owner_string = ThreadToString(current_owner);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700511 expected_owner_string = expected_owner != nullptr ? ThreadToString(expected_owner) : "unnamed";
512 found_owner_string = found_owner != nullptr ? ThreadToString(found_owner) : "unnamed";
Elliott Hughesffb465f2012-03-01 18:46:05 -0800513 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700514
515 if (current_owner_thread_id == 0u) {
516 if (found_owner_thread_id == 0u) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800517 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
518 " on thread '%s'",
David Sehr709b0702016-10-13 09:12:37 -0700519 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800520 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800521 } else {
522 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800523 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
524 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800525 found_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700526 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800527 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800528 }
529 } else {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700530 if (found_owner_thread_id == 0u) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800531 // Race: originally there was no owner, there is now
532 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
533 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800534 current_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700535 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800536 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800537 } else {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700538 if (found_owner_thread_id != current_owner_thread_id) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800539 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800540 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
541 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800542 found_owner_string.c_str(),
543 current_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700544 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800545 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800546 } else {
547 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
548 " on thread '%s",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800549 current_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700550 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800551 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800552 }
553 }
554 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700555}
556
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700557bool Monitor::Unlock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700558 DCHECK(self != nullptr);
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700559 uint32_t owner_thread_id = 0u;
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700560 {
561 MutexLock mu(self, monitor_lock_);
562 Thread* owner = owner_;
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700563 if (owner != nullptr) {
564 owner_thread_id = owner->GetThreadId();
565 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700566 if (owner == self) {
567 // We own the monitor, so nobody else can be in here.
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700568 AtraceMonitorUnlock();
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700569 if (lock_count_ == 0) {
570 owner_ = nullptr;
571 locking_method_ = nullptr;
572 locking_dex_pc_ = 0;
573 // Wake a contender.
574 monitor_contenders_.Signal(self);
575 } else {
576 --lock_count_;
577 }
578 return true;
Elliott Hughes5f791332011-09-15 17:45:30 -0700579 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700580 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700581 // We don't own this, so we're not allowed to unlock it.
582 // The JNI spec says that we should throw IllegalMonitorStateException in this case.
583 FailedUnlock(GetObject(), self->GetThreadId(), owner_thread_id, this);
584 return false;
Elliott Hughes5f791332011-09-15 17:45:30 -0700585}
586
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800587void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
588 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700589 DCHECK(self != nullptr);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800590 DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
Elliott Hughes5f791332011-09-15 17:45:30 -0700591
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700592 monitor_lock_.Lock(self);
593
Elliott Hughes5f791332011-09-15 17:45:30 -0700594 // Make sure that we hold the lock.
595 if (owner_ != self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700596 monitor_lock_.Unlock(self);
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700597 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700598 return;
599 }
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800600
Elliott Hughesdf42c482013-01-09 12:49:02 -0800601 // We need to turn a zero-length timed wait into a regular wait because
602 // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
603 if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
604 why = kWaiting;
605 }
606
Elliott Hughes5f791332011-09-15 17:45:30 -0700607 // Enforce the timeout range.
608 if (ms < 0 || ns < 0 || ns > 999999) {
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700609 monitor_lock_.Unlock(self);
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000610 self->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
Ian Rogersef7d42f2014-01-06 12:55:46 -0800611 "timeout arguments out of range: ms=%" PRId64 " ns=%d", ms, ns);
Elliott Hughes5f791332011-09-15 17:45:30 -0700612 return;
613 }
614
Elliott Hughes5f791332011-09-15 17:45:30 -0700615 /*
616 * Add ourselves to the set of threads waiting on this monitor, and
617 * release our hold. We need to let it go even if we're a few levels
618 * deep in a recursive lock, and we need to restore that later.
619 *
620 * We append to the wait set ahead of clearing the count and owner
621 * fields so the subroutine can check that the calling thread owns
622 * the monitor. Aside from that, the order of member updates is
623 * not order sensitive as we hold the pthread mutex.
624 */
625 AppendToWaitSet(self);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700626 ++num_waiters_;
Ian Rogers0399dde2012-06-06 17:09:28 -0700627 int prev_lock_count = lock_count_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700628 lock_count_ = 0;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700629 owner_ = nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700630 ArtMethod* saved_method = locking_method_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700631 locking_method_ = nullptr;
Ian Rogers0399dde2012-06-06 17:09:28 -0700632 uintptr_t saved_dex_pc = locking_dex_pc_;
633 locking_dex_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700634
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700635 AtraceMonitorUnlock(); // For the implict Unlock() just above. This will only end the deepest
636 // nesting, but that is enough for the visualization, and corresponds to
637 // the single Lock() we do afterwards.
638 AtraceMonitorLock(self, GetObject(), true /* is_wait */);
639
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800640 bool was_interrupted = false;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700641 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700642 // Update thread state. If the GC wakes up, it'll ignore us, knowing
643 // that we won't touch any references in this state, and we'll check
644 // our suspend mode before we transition out.
645 ScopedThreadSuspension sts(self, why);
646
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700647 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700648 MutexLock mu(self, *self->GetWaitMutex());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700649
650 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700651 // non-null a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700652 // up.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700653 DCHECK(self->GetWaitMonitor() == nullptr);
654 self->SetWaitMonitor(this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700655
656 // Release the monitor lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700657 monitor_contenders_.Signal(self);
658 monitor_lock_.Unlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700659
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800660 // Handle the case where the thread was interrupted before we called wait().
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000661 if (self->IsInterrupted()) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800662 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700663 } else {
664 // Wait for a notification or a timeout to occur.
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800665 if (why == kWaiting) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700666 self->GetWaitConditionVariable()->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700667 } else {
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800668 DCHECK(why == kTimedWaiting || why == kSleeping) << why;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700669 self->GetWaitConditionVariable()->TimedWait(self, ms, ns);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700670 }
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000671 was_interrupted = self->IsInterrupted();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700672 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700673 }
674
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800675 {
676 // We reset the thread's wait_monitor_ field after transitioning back to runnable so
677 // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
678 // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
679 // are waiting on "null".)
Ian Rogersdd7624d2014-03-14 17:43:00 -0700680 MutexLock mu(self, *self->GetWaitMutex());
681 DCHECK(self->GetWaitMonitor() != nullptr);
682 self->SetWaitMonitor(nullptr);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800683 }
684
Mathieu Chartierdaed5d82016-03-10 10:49:35 -0800685 // Allocate the interrupted exception not holding the monitor lock since it may cause a GC.
686 // If the GC requires acquiring the monitor for enqueuing cleared references, this would
687 // cause a deadlock if the monitor is held.
688 if (was_interrupted && interruptShouldThrow) {
689 /*
690 * We were interrupted while waiting, or somebody interrupted an
691 * un-interruptible thread earlier and we're bailing out immediately.
692 *
693 * The doc sayeth: "The interrupted status of the current thread is
694 * cleared when this exception is thrown."
695 */
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000696 self->SetInterrupted(false);
Mathieu Chartierdaed5d82016-03-10 10:49:35 -0800697 self->ThrowNewException("Ljava/lang/InterruptedException;", nullptr);
698 }
699
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700700 AtraceMonitorUnlock(); // End Wait().
701
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700702 // Re-acquire the monitor and lock.
Elliott Hughes5f791332011-09-15 17:45:30 -0700703 Lock(self);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700704 monitor_lock_.Lock(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700705 self->GetWaitMutex()->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700706
Elliott Hughes5f791332011-09-15 17:45:30 -0700707 /*
708 * We remove our thread from wait set after restoring the count
709 * and owner fields so the subroutine can check that the calling
710 * thread owns the monitor. Aside from that, the order of member
711 * updates is not order sensitive as we hold the pthread mutex.
712 */
713 owner_ = self;
Ian Rogers0399dde2012-06-06 17:09:28 -0700714 lock_count_ = prev_lock_count;
715 locking_method_ = saved_method;
716 locking_dex_pc_ = saved_dex_pc;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700717 --num_waiters_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700718 RemoveFromWaitSet(self);
719
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700720 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700721}
722
723void Monitor::Notify(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700724 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700725 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700726 // Make sure that we hold the lock.
727 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800728 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700729 return;
730 }
731 // Signal the first waiting thread in the wait set.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700732 while (wait_set_ != nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700733 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700734 wait_set_ = thread->GetWaitNext();
735 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700736
737 // Check to see if the thread is still waiting.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800738 MutexLock wait_mu(self, *thread->GetWaitMutex());
Ian Rogersdd7624d2014-03-14 17:43:00 -0700739 if (thread->GetWaitMonitor() != nullptr) {
740 thread->GetWaitConditionVariable()->Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700741 return;
742 }
743 }
744}
745
746void Monitor::NotifyAll(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700747 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700748 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700749 // Make sure that we hold the lock.
750 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800751 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700752 return;
753 }
754 // Signal all threads in the wait set.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700755 while (wait_set_ != nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700756 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700757 wait_set_ = thread->GetWaitNext();
758 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700759 thread->Notify();
760 }
761}
762
Mathieu Chartier590fee92013-09-13 13:46:47 -0700763bool Monitor::Deflate(Thread* self, mirror::Object* obj) {
764 DCHECK(obj != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700765 // Don't need volatile since we only deflate with mutators suspended.
766 LockWord lw(obj->GetLockWord(false));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700767 // If the lock isn't an inflated monitor, then we don't need to deflate anything.
768 if (lw.GetState() == LockWord::kFatLocked) {
769 Monitor* monitor = lw.FatLockMonitor();
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700770 DCHECK(monitor != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700771 MutexLock mu(self, monitor->monitor_lock_);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700772 // Can't deflate if we have anybody waiting on the CV.
773 if (monitor->num_waiters_ > 0) {
774 return false;
775 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700776 Thread* owner = monitor->owner_;
777 if (owner != nullptr) {
778 // Can't deflate if we are locked and have a hash code.
779 if (monitor->HasHashCode()) {
780 return false;
781 }
782 // Can't deflate if our lock count is too high.
Mathieu Chartier1cf194f2016-11-01 20:13:24 -0700783 if (static_cast<uint32_t>(monitor->lock_count_) > LockWord::kThinLockMaxCount) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700784 return false;
785 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700786 // Deflate to a thin lock.
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700787 LockWord new_lw = LockWord::FromThinLockId(owner->GetThreadId(),
788 monitor->lock_count_,
789 lw.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800790 // Assume no concurrent read barrier state changes as mutators are suspended.
791 obj->SetLockWord(new_lw, false);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700792 VLOG(monitor) << "Deflated " << obj << " to thin lock " << owner->GetTid() << " / "
793 << monitor->lock_count_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700794 } else if (monitor->HasHashCode()) {
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700795 LockWord new_lw = LockWord::FromHashCode(monitor->GetHashCode(), lw.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800796 // Assume no concurrent read barrier state changes as mutators are suspended.
797 obj->SetLockWord(new_lw, false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700798 VLOG(monitor) << "Deflated " << obj << " to hash monitor " << monitor->GetHashCode();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700799 } else {
800 // No lock and no hash, just put an empty lock word inside the object.
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700801 LockWord new_lw = LockWord::FromDefault(lw.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800802 // Assume no concurrent read barrier state changes as mutators are suspended.
803 obj->SetLockWord(new_lw, false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700804 VLOG(monitor) << "Deflated" << obj << " to empty lock word";
Mathieu Chartier590fee92013-09-13 13:46:47 -0700805 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700806 // 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 -0700807 // next GC.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700808 monitor->obj_ = GcRoot<mirror::Object>(nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700809 }
810 return true;
811}
812
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700813void Monitor::Inflate(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code) {
Andreas Gampe74240812014-04-17 10:35:09 -0700814 DCHECK(self != nullptr);
815 DCHECK(obj != nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700816 // Allocate and acquire a new monitor.
Andreas Gampe74240812014-04-17 10:35:09 -0700817 Monitor* m = MonitorPool::CreateMonitor(self, owner, obj, hash_code);
818 DCHECK(m != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700819 if (m->Install(self)) {
Haifeng Li86ab7912014-05-16 10:47:59 +0800820 if (owner != nullptr) {
821 VLOG(monitor) << "monitor: thread" << owner->GetThreadId()
Andreas Gampe74240812014-04-17 10:35:09 -0700822 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800823 } else {
824 VLOG(monitor) << "monitor: Inflate with hashcode " << hash_code
Andreas Gampe74240812014-04-17 10:35:09 -0700825 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800826 }
Andreas Gampe74240812014-04-17 10:35:09 -0700827 Runtime::Current()->GetMonitorList()->Add(m);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700828 CHECK_EQ(obj->GetLockWord(true).GetState(), LockWord::kFatLocked);
Andreas Gampe74240812014-04-17 10:35:09 -0700829 } else {
830 MonitorPool::ReleaseMonitor(self, m);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700831 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700832}
833
Mathieu Chartier0cd81352014-05-22 16:48:55 -0700834void Monitor::InflateThinLocked(Thread* self, Handle<mirror::Object> obj, LockWord lock_word,
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700835 uint32_t hash_code) {
836 DCHECK_EQ(lock_word.GetState(), LockWord::kThinLocked);
837 uint32_t owner_thread_id = lock_word.ThinLockOwner();
838 if (owner_thread_id == self->GetThreadId()) {
839 // We own the monitor, we can easily inflate it.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700840 Inflate(self, self, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700841 } else {
842 ThreadList* thread_list = Runtime::Current()->GetThreadList();
843 // Suspend the owner, inflate. First change to blocked and give up mutator_lock_.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700844 self->SetMonitorEnterObject(obj.Get());
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700845 bool timed_out;
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700846 Thread* owner;
847 {
848 ScopedThreadSuspension sts(self, kBlocked);
849 owner = thread_list->SuspendThreadByThreadId(owner_thread_id, false, &timed_out);
850 }
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700851 if (owner != nullptr) {
852 // We succeeded in suspending the thread, check the lock's status didn't change.
853 lock_word = obj->GetLockWord(true);
854 if (lock_word.GetState() == LockWord::kThinLocked &&
855 lock_word.ThinLockOwner() == owner_thread_id) {
856 // Go ahead and inflate the lock.
857 Inflate(self, owner, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700858 }
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700859 thread_list->Resume(owner, false);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700860 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700861 self->SetMonitorEnterObject(nullptr);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700862 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700863}
864
Ian Rogers719d1a32014-03-06 12:13:39 -0800865// Fool annotalysis into thinking that the lock on obj is acquired.
866static mirror::Object* FakeLock(mirror::Object* obj)
867 EXCLUSIVE_LOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
868 return obj;
869}
870
871// Fool annotalysis into thinking that the lock on obj is release.
872static mirror::Object* FakeUnlock(mirror::Object* obj)
873 UNLOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
874 return obj;
875}
876
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700877mirror::Object* Monitor::MonitorEnter(Thread* self, mirror::Object* obj, bool trylock) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700878 DCHECK(self != nullptr);
879 DCHECK(obj != nullptr);
Mathieu Chartier2d096c92015-10-12 16:18:20 -0700880 self->AssertThreadSuspensionIsAllowable();
Ian Rogers719d1a32014-03-06 12:13:39 -0800881 obj = FakeLock(obj);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700882 uint32_t thread_id = self->GetThreadId();
883 size_t contention_count = 0;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700884 StackHandleScope<1> hs(self);
885 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700886 while (true) {
Hans Boehmb3da36c2016-12-15 13:12:59 -0800887 // We initially read the lockword with ordinary Java/relaxed semantics. When stronger
888 // semantics are needed, we address it below. Since GetLockWord bottoms out to a relaxed load,
889 // we can fix it later, in an infrequently executed case, with a fence.
890 LockWord lock_word = h_obj->GetLockWord(false);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700891 switch (lock_word.GetState()) {
892 case LockWord::kUnlocked: {
Hans Boehmb3da36c2016-12-15 13:12:59 -0800893 // No ordering required for preceding lockword read, since we retest.
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700894 LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0, lock_word.GCState()));
Hans Boehmb3da36c2016-12-15 13:12:59 -0800895 if (h_obj->CasLockWordWeakAcquire(lock_word, thin_locked)) {
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700896 AtraceMonitorLock(self, h_obj.Get(), false /* is_wait */);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700897 return h_obj.Get(); // Success!
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700898 }
899 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -0700900 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700901 case LockWord::kThinLocked: {
902 uint32_t owner_thread_id = lock_word.ThinLockOwner();
903 if (owner_thread_id == thread_id) {
Hans Boehmb3da36c2016-12-15 13:12:59 -0800904 // No ordering required for initial lockword read.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700905 // We own the lock, increase the recursion count.
906 uint32_t new_count = lock_word.ThinLockCount() + 1;
907 if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700908 LockWord thin_locked(LockWord::FromThinLockId(thread_id,
909 new_count,
910 lock_word.GCState()));
Hans Boehmb3da36c2016-12-15 13:12:59 -0800911 // Only this thread pays attention to the count. Thus there is no need for stronger
912 // than relaxed memory ordering.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800913 if (!kUseReadBarrier) {
Hans Boehmb3da36c2016-12-15 13:12:59 -0800914 h_obj->SetLockWord(thin_locked, false /* volatile */);
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700915 AtraceMonitorLock(self, h_obj.Get(), false /* is_wait */);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800916 return h_obj.Get(); // Success!
917 } else {
918 // Use CAS to preserve the read barrier state.
Hans Boehmb3da36c2016-12-15 13:12:59 -0800919 if (h_obj->CasLockWordWeakRelaxed(lock_word, thin_locked)) {
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 }
923 }
924 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -0700925 } else {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700926 // We'd overflow the recursion count, so inflate the monitor.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700927 InflateThinLocked(self, h_obj, lock_word, 0);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700928 }
929 } else {
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700930 if (trylock) {
931 return nullptr;
932 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700933 // Contention.
934 contention_count++;
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700935 Runtime* runtime = Runtime::Current();
Hans Boehmb3da36c2016-12-15 13:12:59 -0800936 if (contention_count <= runtime->GetMaxSpinsBeforeThinLockInflation()) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700937 // TODO: Consider switching the thread state to kBlocked when we are yielding.
Mathieu Chartier251755c2014-07-15 18:10:25 -0700938 // Use sched_yield instead of NanoSleep since NanoSleep can wait much longer than the
939 // parameter you pass in. This can cause thread suspension to take excessively long
Mathieu Chartierb363f662014-07-16 13:28:58 -0700940 // and make long pauses. See b/16307460.
Hans Boehmb3da36c2016-12-15 13:12:59 -0800941 // TODO: We should literally spin first, without sched_yield. Sched_yield either does
942 // nothing (at significant expense), or guarantees that we wait at least microseconds.
943 // If the owner is running, I would expect the median lock hold time to be hundreds
944 // of nanoseconds or less.
Mathieu Chartier251755c2014-07-15 18:10:25 -0700945 sched_yield();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700946 } else {
947 contention_count = 0;
Hans Boehmb3da36c2016-12-15 13:12:59 -0800948 // No ordering required for initial lockword read. Install rereads it anyway.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700949 InflateThinLocked(self, h_obj, lock_word, 0);
Elliott Hughes5f791332011-09-15 17:45:30 -0700950 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700951 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700952 continue; // Start from the beginning.
Elliott Hughes5f791332011-09-15 17:45:30 -0700953 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700954 case LockWord::kFatLocked: {
Hans Boehmb3da36c2016-12-15 13:12:59 -0800955 // We should have done an acquire read of the lockword initially, to ensure
956 // visibility of the monitor data structure. Use an explicit fence instead.
957 QuasiAtomic::ThreadFenceAcquire();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700958 Monitor* mon = lock_word.FatLockMonitor();
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700959 if (trylock) {
960 return mon->TryLock(self) ? h_obj.Get() : nullptr;
961 } else {
962 mon->Lock(self);
963 return h_obj.Get(); // Success!
964 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700965 }
Ian Rogers719d1a32014-03-06 12:13:39 -0800966 case LockWord::kHashCode:
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700967 // Inflate with the existing hashcode.
Hans Boehmb3da36c2016-12-15 13:12:59 -0800968 // Again no ordering required for initial lockword read, since we don't rely
969 // on the visibility of any prior computation.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700970 Inflate(self, nullptr, h_obj.Get(), lock_word.GetHashCode());
Ian Rogers719d1a32014-03-06 12:13:39 -0800971 continue; // Start from the beginning.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700972 default: {
973 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700974 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700975 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700976 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700977 }
978}
979
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800980bool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700981 DCHECK(self != nullptr);
982 DCHECK(obj != nullptr);
Mathieu Chartier2d096c92015-10-12 16:18:20 -0700983 self->AssertThreadSuspensionIsAllowable();
Ian Rogers719d1a32014-03-06 12:13:39 -0800984 obj = FakeUnlock(obj);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700985 StackHandleScope<1> hs(self);
986 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800987 while (true) {
988 LockWord lock_word = obj->GetLockWord(true);
989 switch (lock_word.GetState()) {
990 case LockWord::kHashCode:
991 // Fall-through.
992 case LockWord::kUnlocked:
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700993 FailedUnlock(h_obj.Get(), self->GetThreadId(), 0u, nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700994 return false; // Failure.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800995 case LockWord::kThinLocked: {
996 uint32_t thread_id = self->GetThreadId();
997 uint32_t owner_thread_id = lock_word.ThinLockOwner();
998 if (owner_thread_id != thread_id) {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700999 FailedUnlock(h_obj.Get(), thread_id, owner_thread_id, nullptr);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001000 return false; // Failure.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001001 } else {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001002 // We own the lock, decrease the recursion count.
1003 LockWord new_lw = LockWord::Default();
1004 if (lock_word.ThinLockCount() != 0) {
1005 uint32_t new_count = lock_word.ThinLockCount() - 1;
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001006 new_lw = LockWord::FromThinLockId(thread_id, new_count, lock_word.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001007 } else {
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001008 new_lw = LockWord::FromDefault(lock_word.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001009 }
1010 if (!kUseReadBarrier) {
1011 DCHECK_EQ(new_lw.ReadBarrierState(), 0U);
Hans Boehmb3da36c2016-12-15 13:12:59 -08001012 // TODO: This really only needs memory_order_release, but we currently have
1013 // no way to specify that. In fact there seem to be no legitimate uses of SetLockWord
1014 // with a final argument of true. This slows down x86 and ARMv7, but probably not v8.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001015 h_obj->SetLockWord(new_lw, true);
Andreas Gampe6e759ad2016-05-17 10:13:10 -07001016 AtraceMonitorUnlock();
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001017 // Success!
1018 return true;
1019 } else {
1020 // Use CAS to preserve the read barrier state.
Hans Boehmb3da36c2016-12-15 13:12:59 -08001021 if (h_obj->CasLockWordWeakRelease(lock_word, new_lw)) {
Andreas Gampe6e759ad2016-05-17 10:13:10 -07001022 AtraceMonitorUnlock();
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001023 // Success!
1024 return true;
1025 }
1026 }
1027 continue; // Go again.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001028 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001029 }
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001030 case LockWord::kFatLocked: {
1031 Monitor* mon = lock_word.FatLockMonitor();
1032 return mon->Unlock(self);
1033 }
1034 default: {
1035 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1036 return false;
1037 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001038 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001039 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001040}
1041
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001042void Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
Elliott Hughes4cd121e2013-01-07 17:35:41 -08001043 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001044 DCHECK(self != nullptr);
1045 DCHECK(obj != nullptr);
1046 LockWord lock_word = obj->GetLockWord(true);
Ian Rogers43c69cc2014-08-15 11:09:28 -07001047 while (lock_word.GetState() != LockWord::kFatLocked) {
1048 switch (lock_word.GetState()) {
1049 case LockWord::kHashCode:
1050 // Fall-through.
1051 case LockWord::kUnlocked:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001052 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
1053 return; // Failure.
Ian Rogers43c69cc2014-08-15 11:09:28 -07001054 case LockWord::kThinLocked: {
1055 uint32_t thread_id = self->GetThreadId();
1056 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1057 if (owner_thread_id != thread_id) {
1058 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
1059 return; // Failure.
1060 } else {
1061 // We own the lock, inflate to enqueue ourself on the Monitor. May fail spuriously so
1062 // re-load.
1063 Inflate(self, self, obj, 0);
1064 lock_word = obj->GetLockWord(true);
1065 }
1066 break;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001067 }
Ian Rogers43c69cc2014-08-15 11:09:28 -07001068 case LockWord::kFatLocked: // Unreachable given the loop condition above. Fall-through.
1069 default: {
1070 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1071 return;
1072 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001073 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001074 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001075 Monitor* mon = lock_word.FatLockMonitor();
1076 mon->Wait(self, ms, ns, interruptShouldThrow, why);
Elliott Hughes5f791332011-09-15 17:45:30 -07001077}
1078
Ian Rogers13c479e2013-10-11 07:59:01 -07001079void Monitor::DoNotify(Thread* self, mirror::Object* obj, bool notify_all) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001080 DCHECK(self != nullptr);
1081 DCHECK(obj != nullptr);
1082 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001083 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001084 case LockWord::kHashCode:
1085 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001086 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -08001087 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001088 return; // Failure.
1089 case LockWord::kThinLocked: {
1090 uint32_t thread_id = self->GetThreadId();
1091 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1092 if (owner_thread_id != thread_id) {
1093 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
1094 return; // Failure.
1095 } else {
1096 // We own the lock but there's no Monitor and therefore no waiters.
1097 return; // Success.
1098 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001099 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001100 case LockWord::kFatLocked: {
1101 Monitor* mon = lock_word.FatLockMonitor();
1102 if (notify_all) {
1103 mon->NotifyAll(self);
1104 } else {
1105 mon->Notify(self);
1106 }
1107 return; // Success.
1108 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001109 default: {
1110 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1111 return;
1112 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001113 }
1114}
1115
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001116uint32_t Monitor::GetLockOwnerThreadId(mirror::Object* obj) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001117 DCHECK(obj != nullptr);
1118 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001119 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001120 case LockWord::kHashCode:
1121 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001122 case LockWord::kUnlocked:
1123 return ThreadList::kInvalidThreadId;
1124 case LockWord::kThinLocked:
1125 return lock_word.ThinLockOwner();
1126 case LockWord::kFatLocked: {
1127 Monitor* mon = lock_word.FatLockMonitor();
1128 return mon->GetOwnerThreadId();
Elliott Hughes5f791332011-09-15 17:45:30 -07001129 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001130 default: {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001131 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001132 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001133 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001134 }
1135}
1136
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001137void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
Ian Rogersd803bc72014-04-01 15:33:03 -07001138 // Determine the wait message and object we're waiting or blocked upon.
1139 mirror::Object* pretty_object = nullptr;
1140 const char* wait_message = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001141 uint32_t lock_owner = ThreadList::kInvalidThreadId;
Ian Rogersd803bc72014-04-01 15:33:03 -07001142 ThreadState state = thread->GetState();
Elliott Hughesb4e94fd2013-01-08 14:41:26 -08001143 if (state == kWaiting || state == kTimedWaiting || state == kSleeping) {
Ian Rogersd803bc72014-04-01 15:33:03 -07001144 wait_message = (state == kSleeping) ? " - sleeping on " : " - waiting on ";
1145 Thread* self = Thread::Current();
1146 MutexLock mu(self, *thread->GetWaitMutex());
1147 Monitor* monitor = thread->GetWaitMonitor();
1148 if (monitor != nullptr) {
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001149 pretty_object = monitor->GetObject();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001150 }
Elliott Hughes34e06962012-04-09 13:55:55 -07001151 } else if (state == kBlocked) {
Ian Rogersd803bc72014-04-01 15:33:03 -07001152 wait_message = " - waiting to lock ";
1153 pretty_object = thread->GetMonitorEnterObject();
1154 if (pretty_object != nullptr) {
Hiroshi Yamauchi7b08ae42016-10-04 15:20:36 -07001155 if (kUseReadBarrier && Thread::Current()->GetIsGcMarking()) {
1156 // We may call Thread::Dump() in the middle of the CC thread flip and this thread's stack
1157 // may have not been flipped yet and "pretty_object" may be a from-space (stale) ref, in
1158 // which case the GetLockOwnerThreadId() call below will crash. So explicitly mark/forward
1159 // it here.
1160 pretty_object = ReadBarrier::Mark(pretty_object);
1161 }
Ian Rogersd803bc72014-04-01 15:33:03 -07001162 lock_owner = pretty_object->GetLockOwnerThreadId();
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001163 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001164 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001165
Ian Rogersd803bc72014-04-01 15:33:03 -07001166 if (wait_message != nullptr) {
1167 if (pretty_object == nullptr) {
1168 os << wait_message << "an unknown object";
1169 } else {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001170 if ((pretty_object->GetLockWord(true).GetState() == LockWord::kThinLocked) &&
Ian Rogersd803bc72014-04-01 15:33:03 -07001171 Locks::mutator_lock_->IsExclusiveHeld(Thread::Current())) {
1172 // Getting the identity hashcode here would result in lock inflation and suspension of the
1173 // current thread, which isn't safe if this is the only runnable thread.
1174 os << wait_message << StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)",
1175 reinterpret_cast<intptr_t>(pretty_object),
David Sehr709b0702016-10-13 09:12:37 -07001176 pretty_object->PrettyTypeOf().c_str());
Ian Rogersd803bc72014-04-01 15:33:03 -07001177 } else {
1178 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
Mathieu Chartier49361592015-01-22 16:36:10 -08001179 // Call PrettyTypeOf before IdentityHashCode since IdentityHashCode can cause thread
1180 // suspension and move pretty_object.
David Sehr709b0702016-10-13 09:12:37 -07001181 const std::string pretty_type(pretty_object->PrettyTypeOf());
Ian Rogersd803bc72014-04-01 15:33:03 -07001182 os << wait_message << StringPrintf("<0x%08x> (a %s)", pretty_object->IdentityHashCode(),
Mathieu Chartier49361592015-01-22 16:36:10 -08001183 pretty_type.c_str());
Ian Rogersd803bc72014-04-01 15:33:03 -07001184 }
1185 }
1186 // - waiting to lock <0x613f83d8> (a java.lang.Object) held by thread 5
1187 if (lock_owner != ThreadList::kInvalidThreadId) {
1188 os << " held by thread " << lock_owner;
1189 }
1190 os << "\n";
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001191 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001192}
1193
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001194mirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -08001195 // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
1196 // definition of contended that includes a monitor a thread is trying to enter...
Ian Rogersdd7624d2014-03-14 17:43:00 -07001197 mirror::Object* result = thread->GetMonitorEnterObject();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001198 if (result == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001199 // ...but also a monitor that the thread is waiting on.
Ian Rogersdd7624d2014-03-14 17:43:00 -07001200 MutexLock mu(Thread::Current(), *thread->GetWaitMutex());
1201 Monitor* monitor = thread->GetWaitMonitor();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001202 if (monitor != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001203 result = monitor->GetObject();
Elliott Hughesf9501702013-01-11 11:22:27 -08001204 }
1205 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001206 return result;
Elliott Hughesf9501702013-01-11 11:22:27 -08001207}
1208
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001209void Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
Andreas Gampe760172c2014-08-16 13:41:10 -07001210 void* callback_context, bool abort_on_failure) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001211 ArtMethod* m = stack_visitor->GetMethod();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001212 CHECK(m != nullptr);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001213
1214 // Native methods are an easy special case.
1215 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
1216 if (m->IsNative()) {
1217 if (m->IsSynchronized()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001218 mirror::Object* jni_this =
1219 stack_visitor->GetCurrentHandleScope(sizeof(void*))->GetReference(0);
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001220 callback(jni_this, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001221 }
1222 return;
1223 }
1224
jeffhao61f916c2012-10-25 17:48:51 -07001225 // Proxy methods should not be synchronized.
1226 if (m->IsProxyMethod()) {
1227 CHECK(!m->IsSynchronized());
1228 return;
1229 }
1230
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001231 // Is there any reason to believe there's any synchronization in this method?
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001232 const DexFile::CodeItem* code_item = m->GetCodeItem();
David Sehr709b0702016-10-13 09:12:37 -07001233 CHECK(code_item != nullptr) << m->PrettyMethod();
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001234 if (code_item->tries_size_ == 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001235 return; // No "tries" implies no synchronization, so no held locks to report.
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001236 }
1237
Andreas Gampe760172c2014-08-16 13:41:10 -07001238 // Get the dex pc. If abort_on_failure is false, GetDexPc will not abort in the case it cannot
1239 // find the dex pc, and instead return kDexNoIndex. Then bail out, as it indicates we have an
1240 // inconsistent stack anyways.
1241 uint32_t dex_pc = stack_visitor->GetDexPc(abort_on_failure);
1242 if (!abort_on_failure && dex_pc == DexFile::kDexNoIndex) {
David Sehr709b0702016-10-13 09:12:37 -07001243 LOG(ERROR) << "Could not find dex_pc for " << m->PrettyMethod();
Andreas Gampe760172c2014-08-16 13:41:10 -07001244 return;
1245 }
1246
Elliott Hughes80537bb2013-01-04 16:37:26 -08001247 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
1248 // the locks held in this stack frame.
1249 std::vector<uint32_t> monitor_enter_dex_pcs;
Andreas Gampe760172c2014-08-16 13:41:10 -07001250 verifier::MethodVerifier::FindLocksAtDexPc(m, dex_pc, &monitor_enter_dex_pcs);
Mathieu Chartiere6a8eec2015-01-06 14:17:57 -08001251 for (uint32_t monitor_dex_pc : monitor_enter_dex_pcs) {
Elliott Hughes80537bb2013-01-04 16:37:26 -08001252 // The verifier works in terms of the dex pcs of the monitor-enter instructions.
1253 // We want the registers used by those instructions (so we can read the values out of them).
Sebastien Hertz0f7c9332015-11-05 15:57:30 +01001254 const Instruction* monitor_enter_instruction =
1255 Instruction::At(&code_item->insns_[monitor_dex_pc]);
Elliott Hughes80537bb2013-01-04 16:37:26 -08001256
1257 // Quick sanity check.
Sebastien Hertz0f7c9332015-11-05 15:57:30 +01001258 CHECK_EQ(monitor_enter_instruction->Opcode(), Instruction::MONITOR_ENTER)
1259 << "expected monitor-enter @" << monitor_dex_pc << "; was "
1260 << reinterpret_cast<const void*>(monitor_enter_instruction);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001261
Sebastien Hertz0f7c9332015-11-05 15:57:30 +01001262 uint16_t monitor_register = monitor_enter_instruction->VRegA();
Nicolas Geoffray15b9d522015-03-12 15:05:13 +00001263 uint32_t value;
1264 bool success = stack_visitor->GetVReg(m, monitor_register, kReferenceVReg, &value);
1265 CHECK(success) << "Failed to read v" << monitor_register << " of kind "
David Sehr709b0702016-10-13 09:12:37 -07001266 << kReferenceVReg << " in method " << m->PrettyMethod();
Nicolas Geoffray15b9d522015-03-12 15:05:13 +00001267 mirror::Object* o = reinterpret_cast<mirror::Object*>(value);
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001268 callback(o, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001269 }
1270}
1271
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001272bool Monitor::IsValidLockWord(LockWord lock_word) {
1273 switch (lock_word.GetState()) {
1274 case LockWord::kUnlocked:
1275 // Nothing to check.
1276 return true;
1277 case LockWord::kThinLocked:
1278 // Basic sanity check of owner.
1279 return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
1280 case LockWord::kFatLocked: {
1281 // Check the monitor appears in the monitor list.
1282 Monitor* mon = lock_word.FatLockMonitor();
1283 MonitorList* list = Runtime::Current()->GetMonitorList();
1284 MutexLock mu(Thread::Current(), list->monitor_list_lock_);
1285 for (Monitor* list_mon : list->list_) {
1286 if (mon == list_mon) {
1287 return true; // Found our monitor.
1288 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001289 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001290 return false; // Fail - unowned monitor in an object.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001291 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001292 case LockWord::kHashCode:
1293 return true;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001294 default:
1295 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001296 UNREACHABLE();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001297 }
1298}
1299
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001300bool Monitor::IsLocked() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001301 MutexLock mu(Thread::Current(), monitor_lock_);
1302 return owner_ != nullptr;
1303}
1304
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -07001305void Monitor::TranslateLocation(ArtMethod* method,
1306 uint32_t dex_pc,
1307 const char** source_file,
1308 int32_t* line_number) {
jeffhao33dc7712011-11-09 17:54:24 -08001309 // If method is null, location is unknown
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001310 if (method == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001311 *source_file = "";
1312 *line_number = 0;
jeffhao33dc7712011-11-09 17:54:24 -08001313 return;
1314 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001315 *source_file = method->GetDeclaringClassSourceFile();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001316 if (*source_file == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001317 *source_file = "";
Elliott Hughes12c51e32012-01-17 20:25:05 -08001318 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001319 *line_number = method->GetLineNumFromDexPC(dex_pc);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001320}
1321
1322uint32_t Monitor::GetOwnerThreadId() {
1323 MutexLock mu(Thread::Current(), monitor_lock_);
1324 Thread* owner = owner_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001325 if (owner != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001326 return owner->GetThreadId();
1327 } else {
1328 return ThreadList::kInvalidThreadId;
1329 }
jeffhao33dc7712011-11-09 17:54:24 -08001330}
1331
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001332MonitorList::MonitorList()
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001333 : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock", kMonitorListLock),
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001334 monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001335}
1336
1337MonitorList::~MonitorList() {
Andreas Gampe74240812014-04-17 10:35:09 -07001338 Thread* self = Thread::Current();
1339 MutexLock mu(self, monitor_list_lock_);
1340 // Release all monitors to the pool.
1341 // TODO: Is it an invariant that *all* open monitors are in the list? Then we could
1342 // clear faster in the pool.
1343 MonitorPool::ReleaseMonitors(self, &list_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001344}
1345
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001346void MonitorList::DisallowNewMonitors() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001347 CHECK(!kUseReadBarrier);
Ian Rogers50b35e22012-10-04 10:09:15 -07001348 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001349 allow_new_monitors_ = false;
1350}
1351
1352void MonitorList::AllowNewMonitors() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001353 CHECK(!kUseReadBarrier);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001354 Thread* self = Thread::Current();
1355 MutexLock mu(self, monitor_list_lock_);
1356 allow_new_monitors_ = true;
1357 monitor_add_condition_.Broadcast(self);
1358}
1359
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001360void MonitorList::BroadcastForNewMonitors() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001361 Thread* self = Thread::Current();
1362 MutexLock mu(self, monitor_list_lock_);
1363 monitor_add_condition_.Broadcast(self);
1364}
1365
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001366void MonitorList::Add(Monitor* m) {
1367 Thread* self = Thread::Current();
1368 MutexLock mu(self, monitor_list_lock_);
Hiroshi Yamauchif1c6f872017-01-06 12:23:47 -08001369 // CMS needs this to block for concurrent reference processing because an object allocated during
1370 // the GC won't be marked and concurrent reference processing would incorrectly clear the JNI weak
1371 // ref. But CC (kUseReadBarrier == true) doesn't because of the to-space invariant.
1372 while (!kUseReadBarrier && UNLIKELY(!allow_new_monitors_)) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -07001373 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
1374 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -08001375 self->CheckEmptyCheckpointFromWeakRefAccess(&monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001376 monitor_add_condition_.WaitHoldingLocks(self);
1377 }
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001378 list_.push_front(m);
1379}
1380
Mathieu Chartier97509952015-07-13 14:35:43 -07001381void MonitorList::SweepMonitorList(IsMarkedVisitor* visitor) {
Andreas Gampe74240812014-04-17 10:35:09 -07001382 Thread* self = Thread::Current();
1383 MutexLock mu(self, monitor_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001384 for (auto it = list_.begin(); it != list_.end(); ) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001385 Monitor* m = *it;
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001386 // Disable the read barrier in GetObject() as this is called by GC.
1387 mirror::Object* obj = m->GetObject<kWithoutReadBarrier>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001388 // The object of a monitor can be null if we have deflated it.
Mathieu Chartier97509952015-07-13 14:35:43 -07001389 mirror::Object* new_obj = obj != nullptr ? visitor->IsMarked(obj) : nullptr;
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001390 if (new_obj == nullptr) {
1391 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001392 << obj;
Andreas Gampe74240812014-04-17 10:35:09 -07001393 MonitorPool::ReleaseMonitor(self, m);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001394 it = list_.erase(it);
1395 } else {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001396 m->SetObject(new_obj);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001397 ++it;
1398 }
1399 }
1400}
1401
Hans Boehm6fe97e02016-05-04 18:35:57 -07001402size_t MonitorList::Size() {
1403 Thread* self = Thread::Current();
1404 MutexLock mu(self, monitor_list_lock_);
1405 return list_.size();
1406}
1407
Mathieu Chartier97509952015-07-13 14:35:43 -07001408class MonitorDeflateVisitor : public IsMarkedVisitor {
1409 public:
1410 MonitorDeflateVisitor() : self_(Thread::Current()), deflate_count_(0) {}
1411
1412 virtual mirror::Object* IsMarked(mirror::Object* object) OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001413 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001414 if (Monitor::Deflate(self_, object)) {
1415 DCHECK_NE(object->GetLockWord(true).GetState(), LockWord::kFatLocked);
1416 ++deflate_count_;
1417 // If we deflated, return null so that the monitor gets removed from the array.
1418 return nullptr;
1419 }
1420 return object; // Monitor was not deflated.
1421 }
1422
1423 Thread* const self_;
1424 size_t deflate_count_;
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001425};
1426
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001427size_t MonitorList::DeflateMonitors() {
Mathieu Chartier97509952015-07-13 14:35:43 -07001428 MonitorDeflateVisitor visitor;
1429 Locks::mutator_lock_->AssertExclusiveHeld(visitor.self_);
1430 SweepMonitorList(&visitor);
1431 return visitor.deflate_count_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001432}
1433
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001434MonitorInfo::MonitorInfo(mirror::Object* obj) : owner_(nullptr), entry_count_(0) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001435 DCHECK(obj != nullptr);
1436 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001437 switch (lock_word.GetState()) {
1438 case LockWord::kUnlocked:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001439 // Fall-through.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001440 case LockWord::kForwardingAddress:
1441 // Fall-through.
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001442 case LockWord::kHashCode:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001443 break;
1444 case LockWord::kThinLocked:
1445 owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
1446 entry_count_ = 1 + lock_word.ThinLockCount();
1447 // Thin locks have no waiters.
1448 break;
1449 case LockWord::kFatLocked: {
1450 Monitor* mon = lock_word.FatLockMonitor();
1451 owner_ = mon->owner_;
1452 entry_count_ = 1 + mon->lock_count_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001453 for (Thread* waiter = mon->wait_set_; waiter != nullptr; waiter = waiter->GetWaitNext()) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001454 waiters_.push_back(waiter);
1455 }
1456 break;
Elliott Hughesf327e072013-01-09 16:01:26 -08001457 }
1458 }
1459}
1460
Elliott Hughes5f791332011-09-15 17:45:30 -07001461} // namespace art