blob: e43f1744487c8c8db40fa7383f7b453164dfbbe0 [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"
Andreas Gampee2abbc62017-09-15 11:59:26 -070030#include "dex_file_types.h"
Sebastien Hertz0f7c9332015-11-05 15:57:30 +010031#include "dex_instruction-inl.h"
Ian Rogersd9c4fc92013-10-01 19:45:43 -070032#include "lock_word-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070033#include "mirror/class-inl.h"
Ian Rogers05f30572013-02-20 12:13:11 -080034#include "mirror/object-inl.h"
Andreas Gampe5d08fcc2017-06-05 17:56:46 -070035#include "object_callbacks.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070036#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070037#include "stack.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070038#include "thread.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070039#include "thread_list.h"
Elliott Hughes08fc03a2012-06-26 17:34:00 -070040#include "verifier/method_verifier.h"
Elliott Hughes044288f2012-06-25 14:46:39 -070041#include "well_known_classes.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070042
43namespace art {
44
Andreas Gampe46ee31b2016-12-14 10:11:49 -080045using android::base::StringPrintf;
46
Mathieu Chartierb9001ab2014-10-03 13:28:46 -070047static constexpr uint64_t kLongWaitMs = 100;
48
Elliott Hughes5f791332011-09-15 17:45:30 -070049/*
Ian Rogersd9c4fc92013-10-01 19:45:43 -070050 * Every Object has a monitor associated with it, but not every Object is actually locked. Even
51 * the ones that are locked do not need a full-fledged monitor until a) there is actual contention
52 * or b) wait() is called on the Object.
Elliott Hughes5f791332011-09-15 17:45:30 -070053 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070054 * For Android, we have implemented a scheme similar to the one described in Bacon et al.'s
55 * "Thin locks: featherweight synchronization for Java" (ACM 1998). Things are even easier for us,
56 * though, because we have a full 32 bits to work with.
Elliott Hughes5f791332011-09-15 17:45:30 -070057 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070058 * The two states of an Object's lock are referred to as "thin" and "fat". A lock may transition
59 * from the "thin" state to the "fat" state and this transition is referred to as inflation. Once
60 * a lock has been inflated it remains in the "fat" state indefinitely.
Elliott Hughes5f791332011-09-15 17:45:30 -070061 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070062 * The lock value itself is stored in mirror::Object::monitor_ and the representation is described
63 * in the LockWord value type.
Elliott Hughes54e7df12011-09-16 11:47:04 -070064 *
Elliott Hughes5f791332011-09-15 17:45:30 -070065 * Monitors provide:
66 * - mutually exclusive access to resources
67 * - a way for multiple threads to wait for notification
68 *
69 * In effect, they fill the role of both mutexes and condition variables.
70 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070071 * Only one thread can own the monitor at any time. There may be several threads waiting on it
72 * (the wait call unlocks it). One or more waiting threads may be getting interrupted or notified
73 * at any given time.
Elliott Hughes5f791332011-09-15 17:45:30 -070074 */
Elliott Hughes54e7df12011-09-16 11:47:04 -070075
Elliott Hughesfc861622011-10-17 17:57:47 -070076uint32_t Monitor::lock_profiling_threshold_ = 0;
Andreas Gamped0210e52017-06-23 13:38:09 -070077uint32_t Monitor::stack_dump_lock_profiling_threshold_ = 0;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070078
Andreas Gamped0210e52017-06-23 13:38:09 -070079void Monitor::Init(uint32_t lock_profiling_threshold,
80 uint32_t stack_dump_lock_profiling_threshold) {
Elliott Hughesfc861622011-10-17 17:57:47 -070081 lock_profiling_threshold_ = lock_profiling_threshold;
Andreas Gamped0210e52017-06-23 13:38:09 -070082 stack_dump_lock_profiling_threshold_ = stack_dump_lock_profiling_threshold;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070083}
84
Ian Rogersef7d42f2014-01-06 12:55:46 -080085Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code)
Ian Rogers00f7d0e2012-07-19 15:28:27 -070086 : monitor_lock_("a monitor lock", kMonitorLock),
Ian Rogersd9c4fc92013-10-01 19:45:43 -070087 monitor_contenders_("monitor contenders", monitor_lock_),
Mathieu Chartier46bc7782013-11-12 17:03:02 -080088 num_waiters_(0),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070089 owner_(owner),
Elliott Hughes5f791332011-09-15 17:45:30 -070090 lock_count_(0),
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070091 obj_(GcRoot<mirror::Object>(obj)),
Mathieu Chartier2cebb242015-04-21 16:50:40 -070092 wait_set_(nullptr),
Mathieu Chartierad2541a2013-10-25 10:05:23 -070093 hash_code_(hash_code),
Mathieu Chartier2cebb242015-04-21 16:50:40 -070094 locking_method_(nullptr),
Ian Rogersef7d42f2014-01-06 12:55:46 -080095 locking_dex_pc_(0),
Andreas Gampe74240812014-04-17 10:35:09 -070096 monitor_id_(MonitorPool::ComputeMonitorId(this, self)) {
97#ifdef __LP64__
98 DCHECK(false) << "Should not be reached in 64b";
99 next_free_ = nullptr;
100#endif
101 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
102 // with the owner unlocking the thin-lock.
103 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
104 // The identity hash code is set for the life time of the monitor.
105}
106
107Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code,
108 MonitorId id)
109 : monitor_lock_("a monitor lock", kMonitorLock),
110 monitor_contenders_("monitor contenders", monitor_lock_),
111 num_waiters_(0),
112 owner_(owner),
113 lock_count_(0),
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700114 obj_(GcRoot<mirror::Object>(obj)),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700115 wait_set_(nullptr),
Andreas Gampe74240812014-04-17 10:35:09 -0700116 hash_code_(hash_code),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700117 locking_method_(nullptr),
Andreas Gampe74240812014-04-17 10:35:09 -0700118 locking_dex_pc_(0),
119 monitor_id_(id) {
120#ifdef __LP64__
121 next_free_ = nullptr;
122#endif
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700123 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
124 // with the owner unlocking the thin-lock.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800125 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700126 // The identity hash code is set for the life time of the monitor.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700127}
128
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700129int32_t Monitor::GetHashCode() {
130 while (!HasHashCode()) {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700131 if (hash_code_.CompareExchangeWeakRelaxed(0, mirror::Object::GenerateIdentityHashCode())) {
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700132 break;
133 }
134 }
135 DCHECK(HasHashCode());
Ian Rogers3e5cf302014-05-20 16:40:37 -0700136 return hash_code_.LoadRelaxed();
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700137}
138
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700139bool Monitor::Install(Thread* self) {
140 MutexLock mu(self, monitor_lock_); // Uncontended mutex acquisition as monitor isn't yet public.
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700141 CHECK(owner_ == nullptr || owner_ == self || owner_->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700142 // Propagate the lock state.
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700143 LockWord lw(GetObject()->GetLockWord(false));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700144 switch (lw.GetState()) {
145 case LockWord::kThinLocked: {
146 CHECK_EQ(owner_->GetThreadId(), lw.ThinLockOwner());
147 lock_count_ = lw.ThinLockCount();
148 break;
149 }
150 case LockWord::kHashCode: {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700151 CHECK_EQ(hash_code_.LoadRelaxed(), static_cast<int32_t>(lw.GetHashCode()));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700152 break;
153 }
154 case LockWord::kFatLocked: {
155 // The owner_ is suspended but another thread beat us to install a monitor.
156 return false;
157 }
158 case LockWord::kUnlocked: {
159 LOG(FATAL) << "Inflating unlocked lock word";
160 break;
161 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700162 default: {
163 LOG(FATAL) << "Invalid monitor state " << lw.GetState();
164 return false;
165 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700166 }
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700167 LockWord fat(this, lw.GCState());
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700168 // Publish the updated lock word, which may race with other threads.
Hans Boehmb3da36c2016-12-15 13:12:59 -0800169 bool success = GetObject()->CasLockWordWeakRelease(lw, fat);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700170 // Lock profiling.
Mathieu Chartier9728f912013-10-30 09:45:13 -0700171 if (success && owner_ != nullptr && lock_profiling_threshold_ != 0) {
Andreas Gampe6ec8ebd2014-07-25 13:36:56 -0700172 // Do not abort on dex pc errors. This can easily happen when we want to dump a stack trace on
173 // abort.
174 locking_method_ = owner_->GetCurrentMethod(&locking_dex_pc_, false);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700175 }
176 return success;
Elliott Hughes5f791332011-09-15 17:45:30 -0700177}
178
179Monitor::~Monitor() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700180 // Deflated monitors have a null object.
Elliott Hughes5f791332011-09-15 17:45:30 -0700181}
182
Elliott Hughes5f791332011-09-15 17:45:30 -0700183void Monitor::AppendToWaitSet(Thread* thread) {
184 DCHECK(owner_ == Thread::Current());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700185 DCHECK(thread != nullptr);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700186 DCHECK(thread->GetWaitNext() == nullptr) << thread->GetWaitNext();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700187 if (wait_set_ == nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700188 wait_set_ = thread;
189 return;
190 }
191
192 // push_back.
193 Thread* t = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700194 while (t->GetWaitNext() != nullptr) {
195 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700196 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700197 t->SetWaitNext(thread);
Elliott Hughes5f791332011-09-15 17:45:30 -0700198}
199
Elliott Hughes5f791332011-09-15 17:45:30 -0700200void Monitor::RemoveFromWaitSet(Thread *thread) {
201 DCHECK(owner_ == Thread::Current());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700202 DCHECK(thread != nullptr);
203 if (wait_set_ == nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700204 return;
205 }
206 if (wait_set_ == thread) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700207 wait_set_ = thread->GetWaitNext();
208 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700209 return;
210 }
211
212 Thread* t = wait_set_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700213 while (t->GetWaitNext() != nullptr) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700214 if (t->GetWaitNext() == thread) {
215 t->SetWaitNext(thread->GetWaitNext());
216 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700217 return;
218 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700219 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700220 }
221}
222
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700223void Monitor::SetObject(mirror::Object* object) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700224 obj_ = GcRoot<mirror::Object>(object);
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700225}
226
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700227// Note: Adapted from CurrentMethodVisitor in thread.cc. We must not resolve here.
228
229struct NthCallerWithDexPcVisitor FINAL : public StackVisitor {
230 explicit NthCallerWithDexPcVisitor(Thread* thread, size_t frame)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700231 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +0100232 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700233 method_(nullptr),
234 dex_pc_(0),
235 current_frame_number_(0),
236 wanted_frame_number_(frame) {}
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700237 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700238 ArtMethod* m = GetMethod();
239 if (m == nullptr || m->IsRuntimeMethod()) {
240 // Runtime method, upcall, or resolution issue. Skip.
241 return true;
242 }
243
244 // Is this the requested frame?
245 if (current_frame_number_ == wanted_frame_number_) {
246 method_ = m;
247 dex_pc_ = GetDexPc(false /* abort_on_error*/);
248 return false;
249 }
250
251 // Look for more.
252 current_frame_number_++;
253 return true;
254 }
255
256 ArtMethod* method_;
257 uint32_t dex_pc_;
258
259 private:
260 size_t current_frame_number_;
261 const size_t wanted_frame_number_;
262};
263
264// This function is inlined and just helps to not have the VLOG and ATRACE check at all the
265// potential tracing points.
266void Monitor::AtraceMonitorLock(Thread* self, mirror::Object* obj, bool is_wait) {
267 if (UNLIKELY(VLOG_IS_ON(systrace_lock_logging) && ATRACE_ENABLED())) {
268 AtraceMonitorLockImpl(self, obj, is_wait);
269 }
270}
271
272void Monitor::AtraceMonitorLockImpl(Thread* self, mirror::Object* obj, bool is_wait) {
273 // Wait() requires a deeper call stack to be useful. Otherwise you'll see "Waiting at
274 // Object.java". Assume that we'll wait a nontrivial amount, so it's OK to do a longer
275 // stack walk than if !is_wait.
276 NthCallerWithDexPcVisitor visitor(self, is_wait ? 1U : 0U);
277 visitor.WalkStack(false);
278 const char* prefix = is_wait ? "Waiting on " : "Locking ";
279
280 const char* filename;
281 int32_t line_number;
282 TranslateLocation(visitor.method_, visitor.dex_pc_, &filename, &line_number);
283
284 // It would be nice to have a stable "ID" for the object here. However, the only stable thing
285 // would be the identity hashcode. But we cannot use IdentityHashcode here: For one, there are
286 // times when it is unsafe to make that call (see stack dumping for an explanation). More
287 // importantly, we would have to give up on thin-locking when adding systrace locks, as the
288 // identity hashcode is stored in the lockword normally (so can't be used with thin-locks).
289 //
290 // Because of thin-locks we also cannot use the monitor id (as there is no monitor). Monitor ids
291 // also do not have to be stable, as the monitor may be deflated.
292 std::string tmp = StringPrintf("%s %d at %s:%d",
293 prefix,
294 (obj == nullptr ? -1 : static_cast<int32_t>(reinterpret_cast<uintptr_t>(obj))),
295 (filename != nullptr ? filename : "null"),
296 line_number);
297 ATRACE_BEGIN(tmp.c_str());
298}
299
300void Monitor::AtraceMonitorUnlock() {
301 if (UNLIKELY(VLOG_IS_ON(systrace_lock_logging))) {
302 ATRACE_END();
303 }
304}
305
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700306std::string Monitor::PrettyContentionInfo(const std::string& owner_name,
307 pid_t owner_tid,
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700308 ArtMethod* owners_method,
309 uint32_t owners_dex_pc,
310 size_t num_waiters) {
Hiroshi Yamauchi71cd68d2017-01-25 18:28:12 -0800311 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700312 const char* owners_filename;
Goran Jakovljevic49c882b2016-04-19 10:27:21 +0200313 int32_t owners_line_number = 0;
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700314 if (owners_method != nullptr) {
315 TranslateLocation(owners_method, owners_dex_pc, &owners_filename, &owners_line_number);
316 }
317 std::ostringstream oss;
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700318 oss << "monitor contention with owner " << owner_name << " (" << owner_tid << ")";
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700319 if (owners_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700320 oss << " at " << owners_method->PrettyMethod();
Mathieu Chartier36891fe2016-04-28 17:21:08 -0700321 oss << "(" << owners_filename << ":" << owners_line_number << ")";
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700322 }
323 oss << " waiters=" << num_waiters;
324 return oss.str();
325}
326
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700327bool Monitor::TryLockLocked(Thread* self) {
328 if (owner_ == nullptr) { // Unowned.
329 owner_ = self;
330 CHECK_EQ(lock_count_, 0);
331 // When debugging, save the current monitor holder for future
332 // acquisition failures to use in sampled logging.
333 if (lock_profiling_threshold_ != 0) {
334 locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
335 }
336 } else if (owner_ == self) { // Recursive.
337 lock_count_++;
338 } else {
339 return false;
340 }
341 AtraceMonitorLock(self, GetObject(), false /* is_wait */);
342 return true;
343}
344
345bool Monitor::TryLock(Thread* self) {
346 MutexLock mu(self, monitor_lock_);
347 return TryLockLocked(self);
348}
349
Alex Light77fee872017-09-05 14:51:49 -0700350// Asserts that a mutex isn't held when the class comes into and out of scope.
351class ScopedAssertNotHeld {
352 public:
353 ScopedAssertNotHeld(Thread* self, Mutex& mu) : self_(self), mu_(mu) {
354 mu_.AssertNotHeld(self_);
355 }
356
357 ~ScopedAssertNotHeld() {
358 mu_.AssertNotHeld(self_);
359 }
360
361 private:
362 Thread* const self_;
363 Mutex& mu_;
364 DISALLOW_COPY_AND_ASSIGN(ScopedAssertNotHeld);
365};
366
367template <LockReason reason>
Elliott Hughes5f791332011-09-15 17:45:30 -0700368void Monitor::Lock(Thread* self) {
Alex Light77fee872017-09-05 14:51:49 -0700369 ScopedAssertNotHeld sanh(self, monitor_lock_);
370 bool called_monitors_callback = false;
371 monitor_lock_.Lock(self);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700372 while (true) {
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700373 if (TryLockLocked(self)) {
Alex Light77fee872017-09-05 14:51:49 -0700374 break;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700375 }
376 // Contended.
377 const bool log_contention = (lock_profiling_threshold_ != 0);
Xin Guanb894a192014-08-22 11:55:37 -0500378 uint64_t wait_start_ms = log_contention ? MilliTime() : 0;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700379 ArtMethod* owners_method = locking_method_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700380 uint32_t owners_dex_pc = locking_dex_pc_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700381 // Do this before releasing the lock so that we don't get deflated.
Mathieu Chartierb9001ab2014-10-03 13:28:46 -0700382 size_t num_waiters = num_waiters_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700383 ++num_waiters_;
Andreas Gampe2702d562017-02-06 09:48:00 -0800384
385 // If systrace logging is enabled, first look at the lock owner. Acquiring the monitor's
386 // lock and then re-acquiring the mutator lock can deadlock.
387 bool started_trace = false;
388 if (ATRACE_ENABLED()) {
389 if (owner_ != nullptr) { // Did the owner_ give the lock up?
390 std::ostringstream oss;
391 std::string name;
392 owner_->GetThreadName(name);
393 oss << PrettyContentionInfo(name,
394 owner_->GetTid(),
395 owners_method,
396 owners_dex_pc,
397 num_waiters);
398 // Add info for contending thread.
399 uint32_t pc;
400 ArtMethod* m = self->GetCurrentMethod(&pc);
401 const char* filename;
402 int32_t line_number;
403 TranslateLocation(m, pc, &filename, &line_number);
404 oss << " blocking from "
405 << ArtMethod::PrettyMethod(m) << "(" << (filename != nullptr ? filename : "null")
406 << ":" << line_number << ")";
407 ATRACE_BEGIN(oss.str().c_str());
408 started_trace = true;
409 }
410 }
411
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700412 monitor_lock_.Unlock(self); // Let go of locks in order.
Alex Light77fee872017-09-05 14:51:49 -0700413 // Call the contended locking cb once and only once. Also only call it if we are locking for
414 // the first time, not during a Wait wakeup.
415 if (reason == LockReason::kForLock && !called_monitors_callback) {
416 called_monitors_callback = true;
417 Runtime::Current()->GetRuntimeCallbacks()->MonitorContendedLocking(this);
418 }
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700419 self->SetMonitorEnterObject(GetObject());
Elliott Hughes5f791332011-09-15 17:45:30 -0700420 {
Hiroshi Yamauchi71cd68d2017-01-25 18:28:12 -0800421 ScopedThreadSuspension tsc(self, kBlocked); // Change to blocked and give up mutator_lock_.
Andreas Gampe2702d562017-02-06 09:48:00 -0800422 uint32_t original_owner_thread_id = 0u;
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700423 {
424 // Reacquire monitor_lock_ without mutator_lock_ for Wait.
425 MutexLock mu2(self, monitor_lock_);
426 if (owner_ != nullptr) { // Did the owner_ give the lock up?
427 original_owner_thread_id = owner_->GetThreadId();
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700428 monitor_contenders_.Wait(self); // Still contended so wait.
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800429 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700430 }
431 if (original_owner_thread_id != 0u) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700432 // Woken from contention.
433 if (log_contention) {
Andreas Gampe111b1092017-06-22 20:28:23 -0700434 uint64_t wait_ms = MilliTime() - wait_start_ms;
435 uint32_t sample_percent;
436 if (wait_ms >= lock_profiling_threshold_) {
437 sample_percent = 100;
438 } else {
439 sample_percent = 100 * wait_ms / lock_profiling_threshold_;
440 }
441 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
442 // Reacquire mutator_lock_ for logging.
443 ScopedObjectAccess soa(self);
Andreas Gampe111b1092017-06-22 20:28:23 -0700444
Andreas Gamped0210e52017-06-23 13:38:09 -0700445 bool owner_alive = false;
446 pid_t original_owner_tid = 0;
447 std::string original_owner_name;
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700448
Andreas Gamped0210e52017-06-23 13:38:09 -0700449 const bool should_dump_stacks = stack_dump_lock_profiling_threshold_ > 0 &&
450 wait_ms > stack_dump_lock_profiling_threshold_;
451 std::string owner_stack_dump;
Andreas Gampe111b1092017-06-22 20:28:23 -0700452
Andreas Gamped0210e52017-06-23 13:38:09 -0700453 // Acquire thread-list lock to find thread and keep it from dying until we've got all
454 // the info we need.
455 {
Alex Lightb1e31a82017-10-04 16:57:36 -0700456 Locks::thread_list_lock_->ExclusiveLock(Thread::Current());
Andreas Gamped0210e52017-06-23 13:38:09 -0700457
458 // Re-find the owner in case the thread got killed.
459 Thread* original_owner = Runtime::Current()->GetThreadList()->FindThreadByThreadId(
460 original_owner_thread_id);
461
462 if (original_owner != nullptr) {
463 owner_alive = true;
464 original_owner_tid = original_owner->GetTid();
465 original_owner->GetThreadName(original_owner_name);
466
467 if (should_dump_stacks) {
468 // Very long contention. Dump stacks.
469 struct CollectStackTrace : public Closure {
470 void Run(art::Thread* thread) OVERRIDE
471 REQUIRES_SHARED(art::Locks::mutator_lock_) {
472 thread->DumpJavaStack(oss);
473 }
474
475 std::ostringstream oss;
476 };
477 CollectStackTrace owner_trace;
Alex Lightb1e31a82017-10-04 16:57:36 -0700478 // RequestSynchronousCheckpoint releases the thread_list_lock_ as a part of its
479 // execution.
Andreas Gamped0210e52017-06-23 13:38:09 -0700480 original_owner->RequestSynchronousCheckpoint(&owner_trace);
481 owner_stack_dump = owner_trace.oss.str();
Alex Lightb1e31a82017-10-04 16:57:36 -0700482 } else {
483 Locks::thread_list_lock_->ExclusiveUnlock(Thread::Current());
Andreas Gamped0210e52017-06-23 13:38:09 -0700484 }
Alex Lightb1e31a82017-10-04 16:57:36 -0700485 } else {
486 Locks::thread_list_lock_->ExclusiveUnlock(Thread::Current());
Andreas Gamped0210e52017-06-23 13:38:09 -0700487 }
488 // This is all the data we need. Now drop the thread-list lock, it's OK for the
489 // owner to go away now.
490 }
491
492 // If we found the owner (and thus have owner data), go and log now.
493 if (owner_alive) {
494 // Give the detailed traces for really long contention.
495 if (should_dump_stacks) {
496 // This must be here (and not above) because we cannot hold the thread-list lock
497 // while running the checkpoint.
498 std::ostringstream self_trace_oss;
499 self->DumpJavaStack(self_trace_oss);
500
501 uint32_t pc;
502 ArtMethod* m = self->GetCurrentMethod(&pc);
503
504 LOG(WARNING) << "Long "
505 << PrettyContentionInfo(original_owner_name,
506 original_owner_tid,
507 owners_method,
508 owners_dex_pc,
509 num_waiters)
510 << " in " << ArtMethod::PrettyMethod(m) << " for "
511 << PrettyDuration(MsToNs(wait_ms)) << "\n"
512 << "Current owner stack:\n" << owner_stack_dump
513 << "Contender stack:\n" << self_trace_oss.str();
514 } else if (wait_ms > kLongWaitMs && owners_method != nullptr) {
Mathieu Chartier36891fe2016-04-28 17:21:08 -0700515 uint32_t pc;
516 ArtMethod* m = self->GetCurrentMethod(&pc);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700517 // TODO: We should maybe check that original_owner is still a live thread.
518 LOG(WARNING) << "Long "
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700519 << PrettyContentionInfo(original_owner_name,
520 original_owner_tid,
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700521 owners_method,
522 owners_dex_pc,
523 num_waiters)
David Sehr709b0702016-10-13 09:12:37 -0700524 << " in " << ArtMethod::PrettyMethod(m) << " for "
525 << PrettyDuration(MsToNs(wait_ms));
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700526 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700527 LogContentionEvent(self,
Alex Light77fee872017-09-05 14:51:49 -0700528 wait_ms,
529 sample_percent,
530 owners_method,
531 owners_dex_pc);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700532 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700533 }
534 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700535 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700536 }
Andreas Gampe2702d562017-02-06 09:48:00 -0800537 if (started_trace) {
538 ATRACE_END();
539 }
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700540 self->SetMonitorEnterObject(nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700541 monitor_lock_.Lock(self); // Reacquire locks in order.
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700542 --num_waiters_;
Elliott Hughesfc861622011-10-17 17:57:47 -0700543 }
Alex Light77fee872017-09-05 14:51:49 -0700544 monitor_lock_.Unlock(self);
545 // We need to pair this with a single contended locking call. NB we match the RI behavior and call
546 // this even if MonitorEnter failed.
547 if (called_monitors_callback) {
548 CHECK(reason == LockReason::kForLock);
549 Runtime::Current()->GetRuntimeCallbacks()->MonitorContendedLocked(this);
550 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700551}
552
Alex Light77fee872017-09-05 14:51:49 -0700553template void Monitor::Lock<LockReason::kForLock>(Thread* self);
554template void Monitor::Lock<LockReason::kForWait>(Thread* self);
555
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800556static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
557 __attribute__((format(printf, 1, 2)));
558
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700559static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700560 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800561 va_list args;
562 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800563 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000564 self->ThrowNewExceptionV("Ljava/lang/IllegalMonitorStateException;", fmt, args);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700565 if (!Runtime::Current()->IsStarted() || VLOG_IS_ON(monitor)) {
Brian Carlstrom64277f32012-03-26 23:53:34 -0700566 std::ostringstream ss;
Ian Rogers62d6c772013-02-27 08:32:07 -0800567 self->Dump(ss);
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700568 LOG(Runtime::Current()->IsStarted() ? ::android::base::INFO : ::android::base::ERROR)
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000569 << self->GetException()->Dump() << "\n" << ss.str();
Brian Carlstrom64277f32012-03-26 23:53:34 -0700570 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800571 va_end(args);
572}
573
Elliott Hughesd4237412012-02-21 11:24:45 -0800574static std::string ThreadToString(Thread* thread) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700575 if (thread == nullptr) {
576 return "nullptr";
Elliott Hughesd4237412012-02-21 11:24:45 -0800577 }
578 std::ostringstream oss;
579 // TODO: alternatively, we could just return the thread's name.
580 oss << *thread;
581 return oss.str();
582}
583
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700584void Monitor::FailedUnlock(mirror::Object* o,
585 uint32_t expected_owner_thread_id,
586 uint32_t found_owner_thread_id,
Elliott Hughesffb465f2012-03-01 18:46:05 -0800587 Monitor* monitor) {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700588 // Acquire thread list lock so threads won't disappear from under us.
Elliott Hughesffb465f2012-03-01 18:46:05 -0800589 std::string current_owner_string;
590 std::string expected_owner_string;
591 std::string found_owner_string;
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700592 uint32_t current_owner_thread_id = 0u;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800593 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700594 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700595 ThreadList* const thread_list = Runtime::Current()->GetThreadList();
596 Thread* expected_owner = thread_list->FindThreadByThreadId(expected_owner_thread_id);
597 Thread* found_owner = thread_list->FindThreadByThreadId(found_owner_thread_id);
598
Elliott Hughesffb465f2012-03-01 18:46:05 -0800599 // Re-read owner now that we hold lock.
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700600 Thread* current_owner = (monitor != nullptr) ? monitor->GetOwner() : nullptr;
601 if (current_owner != nullptr) {
602 current_owner_thread_id = current_owner->GetThreadId();
603 }
Elliott Hughesffb465f2012-03-01 18:46:05 -0800604 // Get short descriptions of the threads involved.
605 current_owner_string = ThreadToString(current_owner);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700606 expected_owner_string = expected_owner != nullptr ? ThreadToString(expected_owner) : "unnamed";
607 found_owner_string = found_owner != nullptr ? ThreadToString(found_owner) : "unnamed";
Elliott Hughesffb465f2012-03-01 18:46:05 -0800608 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700609
610 if (current_owner_thread_id == 0u) {
611 if (found_owner_thread_id == 0u) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800612 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
613 " on thread '%s'",
David Sehr709b0702016-10-13 09:12:37 -0700614 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800615 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800616 } else {
617 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800618 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
619 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800620 found_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700621 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800622 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800623 }
624 } else {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700625 if (found_owner_thread_id == 0u) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800626 // Race: originally there was no owner, there is now
627 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
628 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800629 current_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700630 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800631 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800632 } else {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700633 if (found_owner_thread_id != current_owner_thread_id) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800634 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800635 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
636 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800637 found_owner_string.c_str(),
638 current_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700639 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800640 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800641 } else {
642 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
643 " on thread '%s",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800644 current_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700645 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800646 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800647 }
648 }
649 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700650}
651
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700652bool Monitor::Unlock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700653 DCHECK(self != nullptr);
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700654 uint32_t owner_thread_id = 0u;
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700655 {
656 MutexLock mu(self, monitor_lock_);
657 Thread* owner = owner_;
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700658 if (owner != nullptr) {
659 owner_thread_id = owner->GetThreadId();
660 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700661 if (owner == self) {
662 // We own the monitor, so nobody else can be in here.
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700663 AtraceMonitorUnlock();
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700664 if (lock_count_ == 0) {
665 owner_ = nullptr;
666 locking_method_ = nullptr;
667 locking_dex_pc_ = 0;
668 // Wake a contender.
669 monitor_contenders_.Signal(self);
670 } else {
671 --lock_count_;
672 }
673 return true;
Elliott Hughes5f791332011-09-15 17:45:30 -0700674 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700675 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700676 // We don't own this, so we're not allowed to unlock it.
677 // The JNI spec says that we should throw IllegalMonitorStateException in this case.
678 FailedUnlock(GetObject(), self->GetThreadId(), owner_thread_id, this);
679 return false;
Elliott Hughes5f791332011-09-15 17:45:30 -0700680}
681
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800682void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
683 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700684 DCHECK(self != nullptr);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800685 DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
Elliott Hughes5f791332011-09-15 17:45:30 -0700686
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700687 monitor_lock_.Lock(self);
688
Elliott Hughes5f791332011-09-15 17:45:30 -0700689 // Make sure that we hold the lock.
690 if (owner_ != self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700691 monitor_lock_.Unlock(self);
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700692 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700693 return;
694 }
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800695
Elliott Hughesdf42c482013-01-09 12:49:02 -0800696 // We need to turn a zero-length timed wait into a regular wait because
697 // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
698 if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
699 why = kWaiting;
700 }
701
Elliott Hughes5f791332011-09-15 17:45:30 -0700702 // Enforce the timeout range.
703 if (ms < 0 || ns < 0 || ns > 999999) {
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700704 monitor_lock_.Unlock(self);
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000705 self->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
Ian Rogersef7d42f2014-01-06 12:55:46 -0800706 "timeout arguments out of range: ms=%" PRId64 " ns=%d", ms, ns);
Elliott Hughes5f791332011-09-15 17:45:30 -0700707 return;
708 }
709
Elliott Hughes5f791332011-09-15 17:45:30 -0700710 /*
711 * Add ourselves to the set of threads waiting on this monitor, and
712 * release our hold. We need to let it go even if we're a few levels
713 * deep in a recursive lock, and we need to restore that later.
714 *
715 * We append to the wait set ahead of clearing the count and owner
716 * fields so the subroutine can check that the calling thread owns
717 * the monitor. Aside from that, the order of member updates is
718 * not order sensitive as we hold the pthread mutex.
719 */
720 AppendToWaitSet(self);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700721 ++num_waiters_;
Ian Rogers0399dde2012-06-06 17:09:28 -0700722 int prev_lock_count = lock_count_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700723 lock_count_ = 0;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700724 owner_ = nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700725 ArtMethod* saved_method = locking_method_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700726 locking_method_ = nullptr;
Ian Rogers0399dde2012-06-06 17:09:28 -0700727 uintptr_t saved_dex_pc = locking_dex_pc_;
728 locking_dex_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700729
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700730 AtraceMonitorUnlock(); // For the implict Unlock() just above. This will only end the deepest
731 // nesting, but that is enough for the visualization, and corresponds to
732 // the single Lock() we do afterwards.
733 AtraceMonitorLock(self, GetObject(), true /* is_wait */);
734
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800735 bool was_interrupted = false;
Alex Light77fee872017-09-05 14:51:49 -0700736 bool timed_out = false;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700737 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700738 // Update thread state. If the GC wakes up, it'll ignore us, knowing
739 // that we won't touch any references in this state, and we'll check
740 // our suspend mode before we transition out.
741 ScopedThreadSuspension sts(self, why);
742
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700743 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700744 MutexLock mu(self, *self->GetWaitMutex());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700745
746 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700747 // non-null a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700748 // up.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700749 DCHECK(self->GetWaitMonitor() == nullptr);
750 self->SetWaitMonitor(this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700751
752 // Release the monitor lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700753 monitor_contenders_.Signal(self);
754 monitor_lock_.Unlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700755
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800756 // Handle the case where the thread was interrupted before we called wait().
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000757 if (self->IsInterrupted()) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800758 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700759 } else {
760 // Wait for a notification or a timeout to occur.
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800761 if (why == kWaiting) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700762 self->GetWaitConditionVariable()->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700763 } else {
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800764 DCHECK(why == kTimedWaiting || why == kSleeping) << why;
Alex Light77fee872017-09-05 14:51:49 -0700765 timed_out = self->GetWaitConditionVariable()->TimedWait(self, ms, ns);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700766 }
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000767 was_interrupted = self->IsInterrupted();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700768 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700769 }
770
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800771 {
772 // We reset the thread's wait_monitor_ field after transitioning back to runnable so
773 // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
774 // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
775 // are waiting on "null".)
Ian Rogersdd7624d2014-03-14 17:43:00 -0700776 MutexLock mu(self, *self->GetWaitMutex());
777 DCHECK(self->GetWaitMonitor() != nullptr);
778 self->SetWaitMonitor(nullptr);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800779 }
780
Mathieu Chartierdaed5d82016-03-10 10:49:35 -0800781 // Allocate the interrupted exception not holding the monitor lock since it may cause a GC.
782 // If the GC requires acquiring the monitor for enqueuing cleared references, this would
783 // cause a deadlock if the monitor is held.
784 if (was_interrupted && interruptShouldThrow) {
785 /*
786 * We were interrupted while waiting, or somebody interrupted an
787 * un-interruptible thread earlier and we're bailing out immediately.
788 *
789 * The doc sayeth: "The interrupted status of the current thread is
790 * cleared when this exception is thrown."
791 */
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000792 self->SetInterrupted(false);
Mathieu Chartierdaed5d82016-03-10 10:49:35 -0800793 self->ThrowNewException("Ljava/lang/InterruptedException;", nullptr);
794 }
795
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700796 AtraceMonitorUnlock(); // End Wait().
797
Alex Light77fee872017-09-05 14:51:49 -0700798 // We just slept, tell the runtime callbacks about this.
799 Runtime::Current()->GetRuntimeCallbacks()->MonitorWaitFinished(this, timed_out);
800
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700801 // Re-acquire the monitor and lock.
Alex Light77fee872017-09-05 14:51:49 -0700802 Lock<LockReason::kForWait>(self);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700803 monitor_lock_.Lock(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700804 self->GetWaitMutex()->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700805
Elliott Hughes5f791332011-09-15 17:45:30 -0700806 /*
807 * We remove our thread from wait set after restoring the count
808 * and owner fields so the subroutine can check that the calling
809 * thread owns the monitor. Aside from that, the order of member
810 * updates is not order sensitive as we hold the pthread mutex.
811 */
812 owner_ = self;
Ian Rogers0399dde2012-06-06 17:09:28 -0700813 lock_count_ = prev_lock_count;
814 locking_method_ = saved_method;
815 locking_dex_pc_ = saved_dex_pc;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700816 --num_waiters_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700817 RemoveFromWaitSet(self);
818
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700819 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700820}
821
822void Monitor::Notify(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700823 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700824 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700825 // Make sure that we hold the lock.
826 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800827 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700828 return;
829 }
830 // Signal the first waiting thread in the wait set.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700831 while (wait_set_ != nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700832 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700833 wait_set_ = thread->GetWaitNext();
834 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700835
836 // Check to see if the thread is still waiting.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800837 MutexLock wait_mu(self, *thread->GetWaitMutex());
Ian Rogersdd7624d2014-03-14 17:43:00 -0700838 if (thread->GetWaitMonitor() != nullptr) {
839 thread->GetWaitConditionVariable()->Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700840 return;
841 }
842 }
843}
844
845void Monitor::NotifyAll(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700846 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700847 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700848 // Make sure that we hold the lock.
849 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800850 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700851 return;
852 }
853 // Signal all threads in the wait set.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700854 while (wait_set_ != nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700855 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700856 wait_set_ = thread->GetWaitNext();
857 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700858 thread->Notify();
859 }
860}
861
Mathieu Chartier590fee92013-09-13 13:46:47 -0700862bool Monitor::Deflate(Thread* self, mirror::Object* obj) {
863 DCHECK(obj != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700864 // Don't need volatile since we only deflate with mutators suspended.
865 LockWord lw(obj->GetLockWord(false));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700866 // If the lock isn't an inflated monitor, then we don't need to deflate anything.
867 if (lw.GetState() == LockWord::kFatLocked) {
868 Monitor* monitor = lw.FatLockMonitor();
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700869 DCHECK(monitor != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700870 MutexLock mu(self, monitor->monitor_lock_);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700871 // Can't deflate if we have anybody waiting on the CV.
872 if (monitor->num_waiters_ > 0) {
873 return false;
874 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700875 Thread* owner = monitor->owner_;
876 if (owner != nullptr) {
877 // Can't deflate if we are locked and have a hash code.
878 if (monitor->HasHashCode()) {
879 return false;
880 }
881 // Can't deflate if our lock count is too high.
Mathieu Chartier1cf194f2016-11-01 20:13:24 -0700882 if (static_cast<uint32_t>(monitor->lock_count_) > LockWord::kThinLockMaxCount) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700883 return false;
884 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700885 // Deflate to a thin lock.
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700886 LockWord new_lw = LockWord::FromThinLockId(owner->GetThreadId(),
887 monitor->lock_count_,
888 lw.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800889 // Assume no concurrent read barrier state changes as mutators are suspended.
890 obj->SetLockWord(new_lw, false);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700891 VLOG(monitor) << "Deflated " << obj << " to thin lock " << owner->GetTid() << " / "
892 << monitor->lock_count_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700893 } else if (monitor->HasHashCode()) {
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700894 LockWord new_lw = LockWord::FromHashCode(monitor->GetHashCode(), lw.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800895 // Assume no concurrent read barrier state changes as mutators are suspended.
896 obj->SetLockWord(new_lw, false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700897 VLOG(monitor) << "Deflated " << obj << " to hash monitor " << monitor->GetHashCode();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700898 } else {
899 // No lock and no hash, just put an empty lock word inside the object.
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700900 LockWord new_lw = LockWord::FromDefault(lw.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800901 // Assume no concurrent read barrier state changes as mutators are suspended.
902 obj->SetLockWord(new_lw, false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700903 VLOG(monitor) << "Deflated" << obj << " to empty lock word";
Mathieu Chartier590fee92013-09-13 13:46:47 -0700904 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700905 // 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 -0700906 // next GC.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700907 monitor->obj_ = GcRoot<mirror::Object>(nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700908 }
909 return true;
910}
911
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700912void Monitor::Inflate(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code) {
Andreas Gampe74240812014-04-17 10:35:09 -0700913 DCHECK(self != nullptr);
914 DCHECK(obj != nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700915 // Allocate and acquire a new monitor.
Andreas Gampe74240812014-04-17 10:35:09 -0700916 Monitor* m = MonitorPool::CreateMonitor(self, owner, obj, hash_code);
917 DCHECK(m != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700918 if (m->Install(self)) {
Haifeng Li86ab7912014-05-16 10:47:59 +0800919 if (owner != nullptr) {
920 VLOG(monitor) << "monitor: thread" << owner->GetThreadId()
Andreas Gampe74240812014-04-17 10:35:09 -0700921 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800922 } else {
923 VLOG(monitor) << "monitor: Inflate with hashcode " << hash_code
Andreas Gampe74240812014-04-17 10:35:09 -0700924 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800925 }
Andreas Gampe74240812014-04-17 10:35:09 -0700926 Runtime::Current()->GetMonitorList()->Add(m);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700927 CHECK_EQ(obj->GetLockWord(true).GetState(), LockWord::kFatLocked);
Andreas Gampe74240812014-04-17 10:35:09 -0700928 } else {
929 MonitorPool::ReleaseMonitor(self, m);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700930 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700931}
932
Mathieu Chartier0cd81352014-05-22 16:48:55 -0700933void Monitor::InflateThinLocked(Thread* self, Handle<mirror::Object> obj, LockWord lock_word,
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700934 uint32_t hash_code) {
935 DCHECK_EQ(lock_word.GetState(), LockWord::kThinLocked);
936 uint32_t owner_thread_id = lock_word.ThinLockOwner();
937 if (owner_thread_id == self->GetThreadId()) {
938 // We own the monitor, we can easily inflate it.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700939 Inflate(self, self, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700940 } else {
941 ThreadList* thread_list = Runtime::Current()->GetThreadList();
942 // Suspend the owner, inflate. First change to blocked and give up mutator_lock_.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700943 self->SetMonitorEnterObject(obj.Get());
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700944 bool timed_out;
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700945 Thread* owner;
946 {
Alex Light77fee872017-09-05 14:51:49 -0700947 ScopedThreadSuspension sts(self, kWaitingForLockInflation);
Alex Light46f93402017-06-29 11:59:50 -0700948 owner = thread_list->SuspendThreadByThreadId(owner_thread_id,
949 SuspendReason::kInternal,
950 &timed_out);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700951 }
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700952 if (owner != nullptr) {
953 // We succeeded in suspending the thread, check the lock's status didn't change.
954 lock_word = obj->GetLockWord(true);
955 if (lock_word.GetState() == LockWord::kThinLocked &&
956 lock_word.ThinLockOwner() == owner_thread_id) {
957 // Go ahead and inflate the lock.
958 Inflate(self, owner, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700959 }
Alex Light88fd7202017-06-30 08:31:59 -0700960 bool resumed = thread_list->Resume(owner, SuspendReason::kInternal);
961 DCHECK(resumed);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700962 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700963 self->SetMonitorEnterObject(nullptr);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700964 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700965}
966
Ian Rogers719d1a32014-03-06 12:13:39 -0800967// Fool annotalysis into thinking that the lock on obj is acquired.
968static mirror::Object* FakeLock(mirror::Object* obj)
969 EXCLUSIVE_LOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
970 return obj;
971}
972
973// Fool annotalysis into thinking that the lock on obj is release.
974static mirror::Object* FakeUnlock(mirror::Object* obj)
975 UNLOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
976 return obj;
977}
978
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700979mirror::Object* Monitor::MonitorEnter(Thread* self, mirror::Object* obj, bool trylock) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700980 DCHECK(self != nullptr);
981 DCHECK(obj != nullptr);
Mathieu Chartier2d096c92015-10-12 16:18:20 -0700982 self->AssertThreadSuspensionIsAllowable();
Ian Rogers719d1a32014-03-06 12:13:39 -0800983 obj = FakeLock(obj);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700984 uint32_t thread_id = self->GetThreadId();
985 size_t contention_count = 0;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700986 StackHandleScope<1> hs(self);
987 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700988 while (true) {
Hans Boehmb3da36c2016-12-15 13:12:59 -0800989 // We initially read the lockword with ordinary Java/relaxed semantics. When stronger
990 // semantics are needed, we address it below. Since GetLockWord bottoms out to a relaxed load,
991 // we can fix it later, in an infrequently executed case, with a fence.
992 LockWord lock_word = h_obj->GetLockWord(false);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700993 switch (lock_word.GetState()) {
994 case LockWord::kUnlocked: {
Hans Boehmb3da36c2016-12-15 13:12:59 -0800995 // No ordering required for preceding lockword read, since we retest.
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700996 LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0, lock_word.GCState()));
Hans Boehmb3da36c2016-12-15 13:12:59 -0800997 if (h_obj->CasLockWordWeakAcquire(lock_word, thin_locked)) {
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700998 AtraceMonitorLock(self, h_obj.Get(), false /* is_wait */);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700999 return h_obj.Get(); // Success!
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001000 }
1001 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -07001002 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001003 case LockWord::kThinLocked: {
1004 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1005 if (owner_thread_id == thread_id) {
Hans Boehmb3da36c2016-12-15 13:12:59 -08001006 // No ordering required for initial lockword read.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001007 // We own the lock, increase the recursion count.
1008 uint32_t new_count = lock_word.ThinLockCount() + 1;
1009 if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001010 LockWord thin_locked(LockWord::FromThinLockId(thread_id,
1011 new_count,
1012 lock_word.GCState()));
Hans Boehmb3da36c2016-12-15 13:12:59 -08001013 // Only this thread pays attention to the count. Thus there is no need for stronger
1014 // than relaxed memory ordering.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001015 if (!kUseReadBarrier) {
Hans Boehmb3da36c2016-12-15 13:12:59 -08001016 h_obj->SetLockWord(thin_locked, false /* volatile */);
Andreas Gampec7ed09b2016-04-25 20:08:55 -07001017 AtraceMonitorLock(self, h_obj.Get(), false /* is_wait */);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001018 return h_obj.Get(); // Success!
1019 } else {
1020 // Use CAS to preserve the read barrier state.
Hans Boehmb3da36c2016-12-15 13:12:59 -08001021 if (h_obj->CasLockWordWeakRelaxed(lock_word, thin_locked)) {
Andreas Gampec7ed09b2016-04-25 20:08:55 -07001022 AtraceMonitorLock(self, h_obj.Get(), false /* is_wait */);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001023 return h_obj.Get(); // Success!
1024 }
1025 }
1026 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -07001027 } else {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001028 // We'd overflow the recursion count, so inflate the monitor.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001029 InflateThinLocked(self, h_obj, lock_word, 0);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001030 }
1031 } else {
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07001032 if (trylock) {
1033 return nullptr;
1034 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001035 // Contention.
1036 contention_count++;
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001037 Runtime* runtime = Runtime::Current();
Hans Boehmb3da36c2016-12-15 13:12:59 -08001038 if (contention_count <= runtime->GetMaxSpinsBeforeThinLockInflation()) {
Alex Light77fee872017-09-05 14:51:49 -07001039 // TODO: Consider switching the thread state to kWaitingForLockInflation when we are
1040 // yielding. Use sched_yield instead of NanoSleep since NanoSleep can wait much longer
1041 // than the parameter you pass in. This can cause thread suspension to take excessively
1042 // long and make long pauses. See b/16307460.
Hans Boehmb3da36c2016-12-15 13:12:59 -08001043 // TODO: We should literally spin first, without sched_yield. Sched_yield either does
1044 // nothing (at significant expense), or guarantees that we wait at least microseconds.
1045 // If the owner is running, I would expect the median lock hold time to be hundreds
1046 // of nanoseconds or less.
Mathieu Chartier251755c2014-07-15 18:10:25 -07001047 sched_yield();
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001048 } else {
1049 contention_count = 0;
Hans Boehmb3da36c2016-12-15 13:12:59 -08001050 // No ordering required for initial lockword read. Install rereads it anyway.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001051 InflateThinLocked(self, h_obj, lock_word, 0);
Elliott Hughes5f791332011-09-15 17:45:30 -07001052 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001053 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001054 continue; // Start from the beginning.
Elliott Hughes5f791332011-09-15 17:45:30 -07001055 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001056 case LockWord::kFatLocked: {
Hans Boehmb3da36c2016-12-15 13:12:59 -08001057 // We should have done an acquire read of the lockword initially, to ensure
1058 // visibility of the monitor data structure. Use an explicit fence instead.
1059 QuasiAtomic::ThreadFenceAcquire();
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001060 Monitor* mon = lock_word.FatLockMonitor();
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07001061 if (trylock) {
1062 return mon->TryLock(self) ? h_obj.Get() : nullptr;
1063 } else {
1064 mon->Lock(self);
1065 return h_obj.Get(); // Success!
1066 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001067 }
Ian Rogers719d1a32014-03-06 12:13:39 -08001068 case LockWord::kHashCode:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001069 // Inflate with the existing hashcode.
Hans Boehmb3da36c2016-12-15 13:12:59 -08001070 // Again no ordering required for initial lockword read, since we don't rely
1071 // on the visibility of any prior computation.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001072 Inflate(self, nullptr, h_obj.Get(), lock_word.GetHashCode());
Ian Rogers719d1a32014-03-06 12:13:39 -08001073 continue; // Start from the beginning.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001074 default: {
1075 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Andreas Gampec7ed09b2016-04-25 20:08:55 -07001076 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001077 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001078 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001079 }
1080}
1081
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001082bool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001083 DCHECK(self != nullptr);
1084 DCHECK(obj != nullptr);
Mathieu Chartier2d096c92015-10-12 16:18:20 -07001085 self->AssertThreadSuspensionIsAllowable();
Ian Rogers719d1a32014-03-06 12:13:39 -08001086 obj = FakeUnlock(obj);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001087 StackHandleScope<1> hs(self);
1088 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001089 while (true) {
1090 LockWord lock_word = obj->GetLockWord(true);
1091 switch (lock_word.GetState()) {
1092 case LockWord::kHashCode:
1093 // Fall-through.
1094 case LockWord::kUnlocked:
Mathieu Chartier61b3cd42016-04-18 11:43:29 -07001095 FailedUnlock(h_obj.Get(), self->GetThreadId(), 0u, nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001096 return false; // Failure.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001097 case LockWord::kThinLocked: {
1098 uint32_t thread_id = self->GetThreadId();
1099 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1100 if (owner_thread_id != thread_id) {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -07001101 FailedUnlock(h_obj.Get(), thread_id, owner_thread_id, nullptr);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001102 return false; // Failure.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001103 } else {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001104 // We own the lock, decrease the recursion count.
1105 LockWord new_lw = LockWord::Default();
1106 if (lock_word.ThinLockCount() != 0) {
1107 uint32_t new_count = lock_word.ThinLockCount() - 1;
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001108 new_lw = LockWord::FromThinLockId(thread_id, new_count, lock_word.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001109 } else {
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001110 new_lw = LockWord::FromDefault(lock_word.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001111 }
1112 if (!kUseReadBarrier) {
1113 DCHECK_EQ(new_lw.ReadBarrierState(), 0U);
Hans Boehmb3da36c2016-12-15 13:12:59 -08001114 // TODO: This really only needs memory_order_release, but we currently have
1115 // no way to specify that. In fact there seem to be no legitimate uses of SetLockWord
1116 // with a final argument of true. This slows down x86 and ARMv7, but probably not v8.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001117 h_obj->SetLockWord(new_lw, true);
Andreas Gampe6e759ad2016-05-17 10:13:10 -07001118 AtraceMonitorUnlock();
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001119 // Success!
1120 return true;
1121 } else {
1122 // Use CAS to preserve the read barrier state.
Hans Boehmb3da36c2016-12-15 13:12:59 -08001123 if (h_obj->CasLockWordWeakRelease(lock_word, new_lw)) {
Andreas Gampe6e759ad2016-05-17 10:13:10 -07001124 AtraceMonitorUnlock();
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001125 // Success!
1126 return true;
1127 }
1128 }
1129 continue; // Go again.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001130 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001131 }
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001132 case LockWord::kFatLocked: {
1133 Monitor* mon = lock_word.FatLockMonitor();
1134 return mon->Unlock(self);
1135 }
1136 default: {
1137 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1138 return false;
1139 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001140 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001141 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001142}
1143
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001144void Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
Elliott Hughes4cd121e2013-01-07 17:35:41 -08001145 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001146 DCHECK(self != nullptr);
1147 DCHECK(obj != nullptr);
Alex Light77fee872017-09-05 14:51:49 -07001148 StackHandleScope<1> hs(self);
1149 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
1150
1151 Runtime::Current()->GetRuntimeCallbacks()->ObjectWaitStart(h_obj, ms);
Alex Light848574c2017-09-25 16:59:39 -07001152 if (UNLIKELY(self->ObserveAsyncException() || self->IsExceptionPending())) {
Alex Light77fee872017-09-05 14:51:49 -07001153 // See b/65558434 for information on handling of exceptions here.
1154 return;
1155 }
1156
1157 LockWord lock_word = h_obj->GetLockWord(true);
Ian Rogers43c69cc2014-08-15 11:09:28 -07001158 while (lock_word.GetState() != LockWord::kFatLocked) {
1159 switch (lock_word.GetState()) {
1160 case LockWord::kHashCode:
1161 // Fall-through.
1162 case LockWord::kUnlocked:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001163 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
1164 return; // Failure.
Ian Rogers43c69cc2014-08-15 11:09:28 -07001165 case LockWord::kThinLocked: {
1166 uint32_t thread_id = self->GetThreadId();
1167 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1168 if (owner_thread_id != thread_id) {
1169 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
1170 return; // Failure.
1171 } else {
1172 // We own the lock, inflate to enqueue ourself on the Monitor. May fail spuriously so
1173 // re-load.
Alex Light77fee872017-09-05 14:51:49 -07001174 Inflate(self, self, h_obj.Get(), 0);
1175 lock_word = h_obj->GetLockWord(true);
Ian Rogers43c69cc2014-08-15 11:09:28 -07001176 }
1177 break;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001178 }
Ian Rogers43c69cc2014-08-15 11:09:28 -07001179 case LockWord::kFatLocked: // Unreachable given the loop condition above. Fall-through.
1180 default: {
1181 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1182 return;
1183 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001184 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001185 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001186 Monitor* mon = lock_word.FatLockMonitor();
1187 mon->Wait(self, ms, ns, interruptShouldThrow, why);
Elliott Hughes5f791332011-09-15 17:45:30 -07001188}
1189
Ian Rogers13c479e2013-10-11 07:59:01 -07001190void Monitor::DoNotify(Thread* self, mirror::Object* obj, bool notify_all) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001191 DCHECK(self != nullptr);
1192 DCHECK(obj != nullptr);
1193 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001194 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001195 case LockWord::kHashCode:
1196 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001197 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -08001198 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001199 return; // Failure.
1200 case LockWord::kThinLocked: {
1201 uint32_t thread_id = self->GetThreadId();
1202 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1203 if (owner_thread_id != thread_id) {
1204 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
1205 return; // Failure.
1206 } else {
1207 // We own the lock but there's no Monitor and therefore no waiters.
1208 return; // Success.
1209 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001210 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001211 case LockWord::kFatLocked: {
1212 Monitor* mon = lock_word.FatLockMonitor();
1213 if (notify_all) {
1214 mon->NotifyAll(self);
1215 } else {
1216 mon->Notify(self);
1217 }
1218 return; // Success.
1219 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001220 default: {
1221 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1222 return;
1223 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001224 }
1225}
1226
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001227uint32_t Monitor::GetLockOwnerThreadId(mirror::Object* obj) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001228 DCHECK(obj != nullptr);
1229 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001230 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001231 case LockWord::kHashCode:
1232 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001233 case LockWord::kUnlocked:
1234 return ThreadList::kInvalidThreadId;
1235 case LockWord::kThinLocked:
1236 return lock_word.ThinLockOwner();
1237 case LockWord::kFatLocked: {
1238 Monitor* mon = lock_word.FatLockMonitor();
1239 return mon->GetOwnerThreadId();
Elliott Hughes5f791332011-09-15 17:45:30 -07001240 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001241 default: {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001242 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001243 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001244 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001245 }
1246}
1247
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001248void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
Ian Rogersd803bc72014-04-01 15:33:03 -07001249 // Determine the wait message and object we're waiting or blocked upon.
1250 mirror::Object* pretty_object = nullptr;
1251 const char* wait_message = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001252 uint32_t lock_owner = ThreadList::kInvalidThreadId;
Ian Rogersd803bc72014-04-01 15:33:03 -07001253 ThreadState state = thread->GetState();
Elliott Hughesb4e94fd2013-01-08 14:41:26 -08001254 if (state == kWaiting || state == kTimedWaiting || state == kSleeping) {
Ian Rogersd803bc72014-04-01 15:33:03 -07001255 wait_message = (state == kSleeping) ? " - sleeping on " : " - waiting on ";
1256 Thread* self = Thread::Current();
1257 MutexLock mu(self, *thread->GetWaitMutex());
1258 Monitor* monitor = thread->GetWaitMonitor();
1259 if (monitor != nullptr) {
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001260 pretty_object = monitor->GetObject();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001261 }
Alex Light77fee872017-09-05 14:51:49 -07001262 } else if (state == kBlocked || state == kWaitingForLockInflation) {
1263 wait_message = (state == kBlocked) ? " - waiting to lock "
1264 : " - waiting for lock inflation of ";
Ian Rogersd803bc72014-04-01 15:33:03 -07001265 pretty_object = thread->GetMonitorEnterObject();
1266 if (pretty_object != nullptr) {
Hiroshi Yamauchi7b08ae42016-10-04 15:20:36 -07001267 if (kUseReadBarrier && Thread::Current()->GetIsGcMarking()) {
1268 // We may call Thread::Dump() in the middle of the CC thread flip and this thread's stack
1269 // may have not been flipped yet and "pretty_object" may be a from-space (stale) ref, in
1270 // which case the GetLockOwnerThreadId() call below will crash. So explicitly mark/forward
1271 // it here.
1272 pretty_object = ReadBarrier::Mark(pretty_object);
1273 }
Ian Rogersd803bc72014-04-01 15:33:03 -07001274 lock_owner = pretty_object->GetLockOwnerThreadId();
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001275 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001276 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001277
Ian Rogersd803bc72014-04-01 15:33:03 -07001278 if (wait_message != nullptr) {
1279 if (pretty_object == nullptr) {
1280 os << wait_message << "an unknown object";
1281 } else {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001282 if ((pretty_object->GetLockWord(true).GetState() == LockWord::kThinLocked) &&
Ian Rogersd803bc72014-04-01 15:33:03 -07001283 Locks::mutator_lock_->IsExclusiveHeld(Thread::Current())) {
1284 // Getting the identity hashcode here would result in lock inflation and suspension of the
1285 // current thread, which isn't safe if this is the only runnable thread.
1286 os << wait_message << StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)",
1287 reinterpret_cast<intptr_t>(pretty_object),
David Sehr709b0702016-10-13 09:12:37 -07001288 pretty_object->PrettyTypeOf().c_str());
Ian Rogersd803bc72014-04-01 15:33:03 -07001289 } else {
1290 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
Mathieu Chartier49361592015-01-22 16:36:10 -08001291 // Call PrettyTypeOf before IdentityHashCode since IdentityHashCode can cause thread
1292 // suspension and move pretty_object.
David Sehr709b0702016-10-13 09:12:37 -07001293 const std::string pretty_type(pretty_object->PrettyTypeOf());
Ian Rogersd803bc72014-04-01 15:33:03 -07001294 os << wait_message << StringPrintf("<0x%08x> (a %s)", pretty_object->IdentityHashCode(),
Mathieu Chartier49361592015-01-22 16:36:10 -08001295 pretty_type.c_str());
Ian Rogersd803bc72014-04-01 15:33:03 -07001296 }
1297 }
1298 // - waiting to lock <0x613f83d8> (a java.lang.Object) held by thread 5
1299 if (lock_owner != ThreadList::kInvalidThreadId) {
1300 os << " held by thread " << lock_owner;
1301 }
1302 os << "\n";
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001303 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001304}
1305
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001306mirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -08001307 // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
1308 // definition of contended that includes a monitor a thread is trying to enter...
Ian Rogersdd7624d2014-03-14 17:43:00 -07001309 mirror::Object* result = thread->GetMonitorEnterObject();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001310 if (result == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001311 // ...but also a monitor that the thread is waiting on.
Ian Rogersdd7624d2014-03-14 17:43:00 -07001312 MutexLock mu(Thread::Current(), *thread->GetWaitMutex());
1313 Monitor* monitor = thread->GetWaitMonitor();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001314 if (monitor != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001315 result = monitor->GetObject();
Elliott Hughesf9501702013-01-11 11:22:27 -08001316 }
1317 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001318 return result;
Elliott Hughesf9501702013-01-11 11:22:27 -08001319}
1320
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001321void Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
Andreas Gampe760172c2014-08-16 13:41:10 -07001322 void* callback_context, bool abort_on_failure) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001323 ArtMethod* m = stack_visitor->GetMethod();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001324 CHECK(m != nullptr);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001325
1326 // Native methods are an easy special case.
1327 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
1328 if (m->IsNative()) {
1329 if (m->IsSynchronized()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001330 mirror::Object* jni_this =
1331 stack_visitor->GetCurrentHandleScope(sizeof(void*))->GetReference(0);
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001332 callback(jni_this, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001333 }
1334 return;
1335 }
1336
jeffhao61f916c2012-10-25 17:48:51 -07001337 // Proxy methods should not be synchronized.
1338 if (m->IsProxyMethod()) {
1339 CHECK(!m->IsSynchronized());
1340 return;
1341 }
1342
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001343 // Is there any reason to believe there's any synchronization in this method?
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001344 const DexFile::CodeItem* code_item = m->GetCodeItem();
David Sehr709b0702016-10-13 09:12:37 -07001345 CHECK(code_item != nullptr) << m->PrettyMethod();
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001346 if (code_item->tries_size_ == 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001347 return; // No "tries" implies no synchronization, so no held locks to report.
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001348 }
1349
Andreas Gampe760172c2014-08-16 13:41:10 -07001350 // Get the dex pc. If abort_on_failure is false, GetDexPc will not abort in the case it cannot
1351 // find the dex pc, and instead return kDexNoIndex. Then bail out, as it indicates we have an
1352 // inconsistent stack anyways.
1353 uint32_t dex_pc = stack_visitor->GetDexPc(abort_on_failure);
Andreas Gampee2abbc62017-09-15 11:59:26 -07001354 if (!abort_on_failure && dex_pc == dex::kDexNoIndex) {
David Sehr709b0702016-10-13 09:12:37 -07001355 LOG(ERROR) << "Could not find dex_pc for " << m->PrettyMethod();
Andreas Gampe760172c2014-08-16 13:41:10 -07001356 return;
1357 }
1358
Elliott Hughes80537bb2013-01-04 16:37:26 -08001359 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
1360 // the locks held in this stack frame.
1361 std::vector<uint32_t> monitor_enter_dex_pcs;
Andreas Gampe760172c2014-08-16 13:41:10 -07001362 verifier::MethodVerifier::FindLocksAtDexPc(m, dex_pc, &monitor_enter_dex_pcs);
Mathieu Chartiere6a8eec2015-01-06 14:17:57 -08001363 for (uint32_t monitor_dex_pc : monitor_enter_dex_pcs) {
Elliott Hughes80537bb2013-01-04 16:37:26 -08001364 // The verifier works in terms of the dex pcs of the monitor-enter instructions.
1365 // We want the registers used by those instructions (so we can read the values out of them).
Sebastien Hertz0f7c9332015-11-05 15:57:30 +01001366 const Instruction* monitor_enter_instruction =
1367 Instruction::At(&code_item->insns_[monitor_dex_pc]);
Elliott Hughes80537bb2013-01-04 16:37:26 -08001368
1369 // Quick sanity check.
Sebastien Hertz0f7c9332015-11-05 15:57:30 +01001370 CHECK_EQ(monitor_enter_instruction->Opcode(), Instruction::MONITOR_ENTER)
1371 << "expected monitor-enter @" << monitor_dex_pc << "; was "
1372 << reinterpret_cast<const void*>(monitor_enter_instruction);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001373
Sebastien Hertz0f7c9332015-11-05 15:57:30 +01001374 uint16_t monitor_register = monitor_enter_instruction->VRegA();
Nicolas Geoffray15b9d522015-03-12 15:05:13 +00001375 uint32_t value;
1376 bool success = stack_visitor->GetVReg(m, monitor_register, kReferenceVReg, &value);
1377 CHECK(success) << "Failed to read v" << monitor_register << " of kind "
David Sehr709b0702016-10-13 09:12:37 -07001378 << kReferenceVReg << " in method " << m->PrettyMethod();
Nicolas Geoffray15b9d522015-03-12 15:05:13 +00001379 mirror::Object* o = reinterpret_cast<mirror::Object*>(value);
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001380 callback(o, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001381 }
1382}
1383
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001384bool Monitor::IsValidLockWord(LockWord lock_word) {
1385 switch (lock_word.GetState()) {
1386 case LockWord::kUnlocked:
1387 // Nothing to check.
1388 return true;
1389 case LockWord::kThinLocked:
1390 // Basic sanity check of owner.
1391 return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
1392 case LockWord::kFatLocked: {
1393 // Check the monitor appears in the monitor list.
1394 Monitor* mon = lock_word.FatLockMonitor();
1395 MonitorList* list = Runtime::Current()->GetMonitorList();
1396 MutexLock mu(Thread::Current(), list->monitor_list_lock_);
1397 for (Monitor* list_mon : list->list_) {
1398 if (mon == list_mon) {
1399 return true; // Found our monitor.
1400 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001401 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001402 return false; // Fail - unowned monitor in an object.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001403 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001404 case LockWord::kHashCode:
1405 return true;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001406 default:
1407 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001408 UNREACHABLE();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001409 }
1410}
1411
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001412bool Monitor::IsLocked() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001413 MutexLock mu(Thread::Current(), monitor_lock_);
1414 return owner_ != nullptr;
1415}
1416
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -07001417void Monitor::TranslateLocation(ArtMethod* method,
1418 uint32_t dex_pc,
1419 const char** source_file,
1420 int32_t* line_number) {
jeffhao33dc7712011-11-09 17:54:24 -08001421 // If method is null, location is unknown
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001422 if (method == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001423 *source_file = "";
1424 *line_number = 0;
jeffhao33dc7712011-11-09 17:54:24 -08001425 return;
1426 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001427 *source_file = method->GetDeclaringClassSourceFile();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001428 if (*source_file == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001429 *source_file = "";
Elliott Hughes12c51e32012-01-17 20:25:05 -08001430 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001431 *line_number = method->GetLineNumFromDexPC(dex_pc);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001432}
1433
1434uint32_t Monitor::GetOwnerThreadId() {
1435 MutexLock mu(Thread::Current(), monitor_lock_);
1436 Thread* owner = owner_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001437 if (owner != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001438 return owner->GetThreadId();
1439 } else {
1440 return ThreadList::kInvalidThreadId;
1441 }
jeffhao33dc7712011-11-09 17:54:24 -08001442}
1443
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001444MonitorList::MonitorList()
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001445 : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock", kMonitorListLock),
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001446 monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001447}
1448
1449MonitorList::~MonitorList() {
Andreas Gampe74240812014-04-17 10:35:09 -07001450 Thread* self = Thread::Current();
1451 MutexLock mu(self, monitor_list_lock_);
1452 // Release all monitors to the pool.
1453 // TODO: Is it an invariant that *all* open monitors are in the list? Then we could
1454 // clear faster in the pool.
1455 MonitorPool::ReleaseMonitors(self, &list_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001456}
1457
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001458void MonitorList::DisallowNewMonitors() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001459 CHECK(!kUseReadBarrier);
Ian Rogers50b35e22012-10-04 10:09:15 -07001460 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001461 allow_new_monitors_ = false;
1462}
1463
1464void MonitorList::AllowNewMonitors() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001465 CHECK(!kUseReadBarrier);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001466 Thread* self = Thread::Current();
1467 MutexLock mu(self, monitor_list_lock_);
1468 allow_new_monitors_ = true;
1469 monitor_add_condition_.Broadcast(self);
1470}
1471
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001472void MonitorList::BroadcastForNewMonitors() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001473 Thread* self = Thread::Current();
1474 MutexLock mu(self, monitor_list_lock_);
1475 monitor_add_condition_.Broadcast(self);
1476}
1477
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001478void MonitorList::Add(Monitor* m) {
1479 Thread* self = Thread::Current();
1480 MutexLock mu(self, monitor_list_lock_);
Hiroshi Yamauchif1c6f872017-01-06 12:23:47 -08001481 // CMS needs this to block for concurrent reference processing because an object allocated during
1482 // the GC won't be marked and concurrent reference processing would incorrectly clear the JNI weak
1483 // ref. But CC (kUseReadBarrier == true) doesn't because of the to-space invariant.
1484 while (!kUseReadBarrier && UNLIKELY(!allow_new_monitors_)) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -07001485 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
1486 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -08001487 self->CheckEmptyCheckpointFromWeakRefAccess(&monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001488 monitor_add_condition_.WaitHoldingLocks(self);
1489 }
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001490 list_.push_front(m);
1491}
1492
Mathieu Chartier97509952015-07-13 14:35:43 -07001493void MonitorList::SweepMonitorList(IsMarkedVisitor* visitor) {
Andreas Gampe74240812014-04-17 10:35:09 -07001494 Thread* self = Thread::Current();
1495 MutexLock mu(self, monitor_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001496 for (auto it = list_.begin(); it != list_.end(); ) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001497 Monitor* m = *it;
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001498 // Disable the read barrier in GetObject() as this is called by GC.
1499 mirror::Object* obj = m->GetObject<kWithoutReadBarrier>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001500 // The object of a monitor can be null if we have deflated it.
Mathieu Chartier97509952015-07-13 14:35:43 -07001501 mirror::Object* new_obj = obj != nullptr ? visitor->IsMarked(obj) : nullptr;
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001502 if (new_obj == nullptr) {
1503 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001504 << obj;
Andreas Gampe74240812014-04-17 10:35:09 -07001505 MonitorPool::ReleaseMonitor(self, m);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001506 it = list_.erase(it);
1507 } else {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001508 m->SetObject(new_obj);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001509 ++it;
1510 }
1511 }
1512}
1513
Hans Boehm6fe97e02016-05-04 18:35:57 -07001514size_t MonitorList::Size() {
1515 Thread* self = Thread::Current();
1516 MutexLock mu(self, monitor_list_lock_);
1517 return list_.size();
1518}
1519
Mathieu Chartier97509952015-07-13 14:35:43 -07001520class MonitorDeflateVisitor : public IsMarkedVisitor {
1521 public:
1522 MonitorDeflateVisitor() : self_(Thread::Current()), deflate_count_(0) {}
1523
1524 virtual mirror::Object* IsMarked(mirror::Object* object) OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001525 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001526 if (Monitor::Deflate(self_, object)) {
1527 DCHECK_NE(object->GetLockWord(true).GetState(), LockWord::kFatLocked);
1528 ++deflate_count_;
1529 // If we deflated, return null so that the monitor gets removed from the array.
1530 return nullptr;
1531 }
1532 return object; // Monitor was not deflated.
1533 }
1534
1535 Thread* const self_;
1536 size_t deflate_count_;
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001537};
1538
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001539size_t MonitorList::DeflateMonitors() {
Mathieu Chartier97509952015-07-13 14:35:43 -07001540 MonitorDeflateVisitor visitor;
1541 Locks::mutator_lock_->AssertExclusiveHeld(visitor.self_);
1542 SweepMonitorList(&visitor);
1543 return visitor.deflate_count_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001544}
1545
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001546MonitorInfo::MonitorInfo(mirror::Object* obj) : owner_(nullptr), entry_count_(0) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001547 DCHECK(obj != nullptr);
1548 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001549 switch (lock_word.GetState()) {
1550 case LockWord::kUnlocked:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001551 // Fall-through.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001552 case LockWord::kForwardingAddress:
1553 // Fall-through.
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001554 case LockWord::kHashCode:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001555 break;
1556 case LockWord::kThinLocked:
1557 owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
Alex Lightce568642017-09-05 16:54:25 -07001558 DCHECK(owner_ != nullptr) << "Thin-locked without owner!";
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001559 entry_count_ = 1 + lock_word.ThinLockCount();
1560 // Thin locks have no waiters.
1561 break;
1562 case LockWord::kFatLocked: {
1563 Monitor* mon = lock_word.FatLockMonitor();
1564 owner_ = mon->owner_;
Alex Lightce568642017-09-05 16:54:25 -07001565 // Here it is okay for the owner to be null since we don't reset the LockWord back to
1566 // kUnlocked until we get a GC. In cases where this hasn't happened yet we will have a fat
1567 // lock without an owner.
1568 if (owner_ != nullptr) {
1569 entry_count_ = 1 + mon->lock_count_;
1570 } else {
1571 DCHECK_EQ(mon->lock_count_, 0) << "Monitor is fat-locked without any owner!";
1572 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001573 for (Thread* waiter = mon->wait_set_; waiter != nullptr; waiter = waiter->GetWaitNext()) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001574 waiters_.push_back(waiter);
1575 }
1576 break;
Elliott Hughesf327e072013-01-09 16:01:26 -08001577 }
1578 }
1579}
1580
Elliott Hughes5f791332011-09-15 17:45:30 -07001581} // namespace art