1 /*
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
17 #include "monitor.h"
18
19 #include <vector>
20
21 #include "art_method-inl.h"
22 #include "base/mutex.h"
23 #include "base/stl_util.h"
24 #include "base/systrace.h"
25 #include "base/time_utils.h"
26 #include "class_linker.h"
27 #include "dex_file-inl.h"
28 #include "dex_instruction-inl.h"
29 #include "lock_word-inl.h"
30 #include "mirror/class-inl.h"
31 #include "mirror/object-inl.h"
32 #include "mirror/object_array-inl.h"
33 #include "scoped_thread_state_change.h"
34 #include "thread.h"
35 #include "thread_list.h"
36 #include "verifier/method_verifier.h"
37 #include "well_known_classes.h"
38
39 namespace art {
40
41 static constexpr uint64_t kLongWaitMs = 100;
42
43 /*
44 * Every Object has a monitor associated with it, but not every Object is actually locked. Even
45 * the ones that are locked do not need a full-fledged monitor until a) there is actual contention
46 * or b) wait() is called on the Object.
47 *
48 * For Android, we have implemented a scheme similar to the one described in Bacon et al.'s
49 * "Thin locks: featherweight synchronization for Java" (ACM 1998). Things are even easier for us,
50 * though, because we have a full 32 bits to work with.
51 *
52 * The two states of an Object's lock are referred to as "thin" and "fat". A lock may transition
53 * from the "thin" state to the "fat" state and this transition is referred to as inflation. Once
54 * a lock has been inflated it remains in the "fat" state indefinitely.
55 *
56 * The lock value itself is stored in mirror::Object::monitor_ and the representation is described
57 * in the LockWord value type.
58 *
59 * Monitors provide:
60 * - mutually exclusive access to resources
61 * - a way for multiple threads to wait for notification
62 *
63 * In effect, they fill the role of both mutexes and condition variables.
64 *
65 * Only one thread can own the monitor at any time. There may be several threads waiting on it
66 * (the wait call unlocks it). One or more waiting threads may be getting interrupted or notified
67 * at any given time.
68 */
69
70 uint32_t Monitor::lock_profiling_threshold_ = 0;
71
Init(uint32_t lock_profiling_threshold)72 void Monitor::Init(uint32_t lock_profiling_threshold) {
73 lock_profiling_threshold_ = lock_profiling_threshold;
74 }
75
Monitor(Thread * self,Thread * owner,mirror::Object * obj,int32_t hash_code)76 Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code)
77 : monitor_lock_("a monitor lock", kMonitorLock),
78 monitor_contenders_("monitor contenders", monitor_lock_),
79 num_waiters_(0),
80 owner_(owner),
81 lock_count_(0),
82 obj_(GcRoot<mirror::Object>(obj)),
83 wait_set_(nullptr),
84 hash_code_(hash_code),
85 locking_method_(nullptr),
86 locking_dex_pc_(0),
87 monitor_id_(MonitorPool::ComputeMonitorId(this, self)) {
88 #ifdef __LP64__
89 DCHECK(false) << "Should not be reached in 64b";
90 next_free_ = nullptr;
91 #endif
92 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
93 // with the owner unlocking the thin-lock.
94 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
95 // The identity hash code is set for the life time of the monitor.
96 }
97
Monitor(Thread * self,Thread * owner,mirror::Object * obj,int32_t hash_code,MonitorId id)98 Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code,
99 MonitorId id)
100 : monitor_lock_("a monitor lock", kMonitorLock),
101 monitor_contenders_("monitor contenders", monitor_lock_),
102 num_waiters_(0),
103 owner_(owner),
104 lock_count_(0),
105 obj_(GcRoot<mirror::Object>(obj)),
106 wait_set_(nullptr),
107 hash_code_(hash_code),
108 locking_method_(nullptr),
109 locking_dex_pc_(0),
110 monitor_id_(id) {
111 #ifdef __LP64__
112 next_free_ = nullptr;
113 #endif
114 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
115 // with the owner unlocking the thin-lock.
116 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
117 // The identity hash code is set for the life time of the monitor.
118 }
119
GetHashCode()120 int32_t Monitor::GetHashCode() {
121 while (!HasHashCode()) {
122 if (hash_code_.CompareExchangeWeakRelaxed(0, mirror::Object::GenerateIdentityHashCode())) {
123 break;
124 }
125 }
126 DCHECK(HasHashCode());
127 return hash_code_.LoadRelaxed();
128 }
129
Install(Thread * self)130 bool Monitor::Install(Thread* self) {
131 MutexLock mu(self, monitor_lock_); // Uncontended mutex acquisition as monitor isn't yet public.
132 CHECK(owner_ == nullptr || owner_ == self || owner_->IsSuspended());
133 // Propagate the lock state.
134 LockWord lw(GetObject()->GetLockWord(false));
135 switch (lw.GetState()) {
136 case LockWord::kThinLocked: {
137 CHECK_EQ(owner_->GetThreadId(), lw.ThinLockOwner());
138 lock_count_ = lw.ThinLockCount();
139 break;
140 }
141 case LockWord::kHashCode: {
142 CHECK_EQ(hash_code_.LoadRelaxed(), static_cast<int32_t>(lw.GetHashCode()));
143 break;
144 }
145 case LockWord::kFatLocked: {
146 // The owner_ is suspended but another thread beat us to install a monitor.
147 return false;
148 }
149 case LockWord::kUnlocked: {
150 LOG(FATAL) << "Inflating unlocked lock word";
151 break;
152 }
153 default: {
154 LOG(FATAL) << "Invalid monitor state " << lw.GetState();
155 return false;
156 }
157 }
158 LockWord fat(this, lw.ReadBarrierState());
159 // Publish the updated lock word, which may race with other threads.
160 bool success = GetObject()->CasLockWordWeakSequentiallyConsistent(lw, fat);
161 // Lock profiling.
162 if (success && owner_ != nullptr && lock_profiling_threshold_ != 0) {
163 // Do not abort on dex pc errors. This can easily happen when we want to dump a stack trace on
164 // abort.
165 locking_method_ = owner_->GetCurrentMethod(&locking_dex_pc_, false);
166 }
167 return success;
168 }
169
~Monitor()170 Monitor::~Monitor() {
171 // Deflated monitors have a null object.
172 }
173
AppendToWaitSet(Thread * thread)174 void Monitor::AppendToWaitSet(Thread* thread) {
175 DCHECK(owner_ == Thread::Current());
176 DCHECK(thread != nullptr);
177 DCHECK(thread->GetWaitNext() == nullptr) << thread->GetWaitNext();
178 if (wait_set_ == nullptr) {
179 wait_set_ = thread;
180 return;
181 }
182
183 // push_back.
184 Thread* t = wait_set_;
185 while (t->GetWaitNext() != nullptr) {
186 t = t->GetWaitNext();
187 }
188 t->SetWaitNext(thread);
189 }
190
RemoveFromWaitSet(Thread * thread)191 void Monitor::RemoveFromWaitSet(Thread *thread) {
192 DCHECK(owner_ == Thread::Current());
193 DCHECK(thread != nullptr);
194 if (wait_set_ == nullptr) {
195 return;
196 }
197 if (wait_set_ == thread) {
198 wait_set_ = thread->GetWaitNext();
199 thread->SetWaitNext(nullptr);
200 return;
201 }
202
203 Thread* t = wait_set_;
204 while (t->GetWaitNext() != nullptr) {
205 if (t->GetWaitNext() == thread) {
206 t->SetWaitNext(thread->GetWaitNext());
207 thread->SetWaitNext(nullptr);
208 return;
209 }
210 t = t->GetWaitNext();
211 }
212 }
213
SetObject(mirror::Object * object)214 void Monitor::SetObject(mirror::Object* object) {
215 obj_ = GcRoot<mirror::Object>(object);
216 }
217
218 // Note: Adapted from CurrentMethodVisitor in thread.cc. We must not resolve here.
219
220 struct NthCallerWithDexPcVisitor FINAL : public StackVisitor {
NthCallerWithDexPcVisitorart::FINAL221 explicit NthCallerWithDexPcVisitor(Thread* thread, size_t frame)
222 SHARED_REQUIRES(Locks::mutator_lock_)
223 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFramesNoResolve),
224 method_(nullptr),
225 dex_pc_(0),
226 current_frame_number_(0),
227 wanted_frame_number_(frame) {}
VisitFrameart::FINAL228 bool VisitFrame() OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
229 ArtMethod* m = GetMethod();
230 if (m == nullptr || m->IsRuntimeMethod()) {
231 // Runtime method, upcall, or resolution issue. Skip.
232 return true;
233 }
234
235 // Is this the requested frame?
236 if (current_frame_number_ == wanted_frame_number_) {
237 method_ = m;
238 dex_pc_ = GetDexPc(false /* abort_on_error*/);
239 return false;
240 }
241
242 // Look for more.
243 current_frame_number_++;
244 return true;
245 }
246
247 ArtMethod* method_;
248 uint32_t dex_pc_;
249
250 private:
251 size_t current_frame_number_;
252 const size_t wanted_frame_number_;
253 };
254
255 // This function is inlined and just helps to not have the VLOG and ATRACE check at all the
256 // potential tracing points.
AtraceMonitorLock(Thread * self,mirror::Object * obj,bool is_wait)257 void Monitor::AtraceMonitorLock(Thread* self, mirror::Object* obj, bool is_wait) {
258 if (UNLIKELY(VLOG_IS_ON(systrace_lock_logging) && ATRACE_ENABLED())) {
259 AtraceMonitorLockImpl(self, obj, is_wait);
260 }
261 }
262
AtraceMonitorLockImpl(Thread * self,mirror::Object * obj,bool is_wait)263 void Monitor::AtraceMonitorLockImpl(Thread* self, mirror::Object* obj, bool is_wait) {
264 // Wait() requires a deeper call stack to be useful. Otherwise you'll see "Waiting at
265 // Object.java". Assume that we'll wait a nontrivial amount, so it's OK to do a longer
266 // stack walk than if !is_wait.
267 NthCallerWithDexPcVisitor visitor(self, is_wait ? 1U : 0U);
268 visitor.WalkStack(false);
269 const char* prefix = is_wait ? "Waiting on " : "Locking ";
270
271 const char* filename;
272 int32_t line_number;
273 TranslateLocation(visitor.method_, visitor.dex_pc_, &filename, &line_number);
274
275 // It would be nice to have a stable "ID" for the object here. However, the only stable thing
276 // would be the identity hashcode. But we cannot use IdentityHashcode here: For one, there are
277 // times when it is unsafe to make that call (see stack dumping for an explanation). More
278 // importantly, we would have to give up on thin-locking when adding systrace locks, as the
279 // identity hashcode is stored in the lockword normally (so can't be used with thin-locks).
280 //
281 // Because of thin-locks we also cannot use the monitor id (as there is no monitor). Monitor ids
282 // also do not have to be stable, as the monitor may be deflated.
283 std::string tmp = StringPrintf("%s %d at %s:%d",
284 prefix,
285 (obj == nullptr ? -1 : static_cast<int32_t>(reinterpret_cast<uintptr_t>(obj))),
286 (filename != nullptr ? filename : "null"),
287 line_number);
288 ATRACE_BEGIN(tmp.c_str());
289 }
290
AtraceMonitorUnlock()291 void Monitor::AtraceMonitorUnlock() {
292 if (UNLIKELY(VLOG_IS_ON(systrace_lock_logging))) {
293 ATRACE_END();
294 }
295 }
296
PrettyContentionInfo(const std::string & owner_name,pid_t owner_tid,ArtMethod * owners_method,uint32_t owners_dex_pc,size_t num_waiters)297 std::string Monitor::PrettyContentionInfo(const std::string& owner_name,
298 pid_t owner_tid,
299 ArtMethod* owners_method,
300 uint32_t owners_dex_pc,
301 size_t num_waiters) {
302 const char* owners_filename;
303 int32_t owners_line_number;
304 if (owners_method != nullptr) {
305 TranslateLocation(owners_method, owners_dex_pc, &owners_filename, &owners_line_number);
306 }
307 std::ostringstream oss;
308 oss << "monitor contention with owner " << owner_name << " (" << owner_tid << ")";
309 if (owners_method != nullptr) {
310 oss << " at " << PrettyMethod(owners_method);
311 oss << "(" << owners_filename << ":" << owners_line_number << ")";
312 }
313 oss << " waiters=" << num_waiters;
314 return oss.str();
315 }
316
Lock(Thread * self)317 void Monitor::Lock(Thread* self) {
318 MutexLock mu(self, monitor_lock_);
319 while (true) {
320 if (owner_ == nullptr) { // Unowned.
321 owner_ = self;
322 CHECK_EQ(lock_count_, 0);
323 // When debugging, save the current monitor holder for future
324 // acquisition failures to use in sampled logging.
325 if (lock_profiling_threshold_ != 0) {
326 locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
327 }
328 break;
329 } else if (owner_ == self) { // Recursive.
330 lock_count_++;
331 break;
332 }
333 // Contended.
334 const bool log_contention = (lock_profiling_threshold_ != 0);
335 uint64_t wait_start_ms = log_contention ? MilliTime() : 0;
336 ArtMethod* owners_method = locking_method_;
337 uint32_t owners_dex_pc = locking_dex_pc_;
338 // Do this before releasing the lock so that we don't get deflated.
339 size_t num_waiters = num_waiters_;
340 ++num_waiters_;
341 monitor_lock_.Unlock(self); // Let go of locks in order.
342 self->SetMonitorEnterObject(GetObject());
343 {
344 uint32_t original_owner_thread_id = 0u;
345 ScopedThreadStateChange tsc(self, kBlocked); // Change to blocked and give up mutator_lock_.
346 {
347 // Reacquire monitor_lock_ without mutator_lock_ for Wait.
348 MutexLock mu2(self, monitor_lock_);
349 if (owner_ != nullptr) { // Did the owner_ give the lock up?
350 original_owner_thread_id = owner_->GetThreadId();
351 if (ATRACE_ENABLED()) {
352 std::ostringstream oss;
353 std::string name;
354 owner_->GetThreadName(name);
355 oss << PrettyContentionInfo(name,
356 owner_->GetTid(),
357 owners_method,
358 owners_dex_pc,
359 num_waiters);
360 // Add info for contending thread.
361 uint32_t pc;
362 ArtMethod* m = self->GetCurrentMethod(&pc);
363 const char* filename;
364 int32_t line_number;
365 TranslateLocation(m, pc, &filename, &line_number);
366 oss << " blocking from "
367 << PrettyMethod(m) << "(" << (filename != nullptr ? filename : "null") << ":"
368 << line_number << ")";
369 ATRACE_BEGIN(oss.str().c_str());
370 }
371 monitor_contenders_.Wait(self); // Still contended so wait.
372 }
373 }
374 if (original_owner_thread_id != 0u) {
375 // Woken from contention.
376 if (log_contention) {
377 uint32_t original_owner_tid = 0;
378 std::string original_owner_name;
379 {
380 MutexLock mu2(Thread::Current(), *Locks::thread_list_lock_);
381 // Re-find the owner in case the thread got killed.
382 Thread* original_owner = Runtime::Current()->GetThreadList()->FindThreadByThreadId(
383 original_owner_thread_id);
384 // Do not do any work that requires the mutator lock.
385 if (original_owner != nullptr) {
386 original_owner_tid = original_owner->GetTid();
387 original_owner->GetThreadName(original_owner_name);
388 }
389 }
390
391 if (original_owner_tid != 0u) {
392 uint64_t wait_ms = MilliTime() - wait_start_ms;
393 uint32_t sample_percent;
394 if (wait_ms >= lock_profiling_threshold_) {
395 sample_percent = 100;
396 } else {
397 sample_percent = 100 * wait_ms / lock_profiling_threshold_;
398 }
399 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
400 if (wait_ms > kLongWaitMs && owners_method != nullptr) {
401 uint32_t pc;
402 ArtMethod* m = self->GetCurrentMethod(&pc);
403 // TODO: We should maybe check that original_owner is still a live thread.
404 LOG(WARNING) << "Long "
405 << PrettyContentionInfo(original_owner_name,
406 original_owner_tid,
407 owners_method,
408 owners_dex_pc,
409 num_waiters)
410 << " in " << PrettyMethod(m) << " for " << PrettyDuration(MsToNs(wait_ms));
411 }
412 const char* owners_filename;
413 int32_t owners_line_number;
414 TranslateLocation(owners_method,
415 owners_dex_pc,
416 &owners_filename,
417 &owners_line_number);
418 LogContentionEvent(self,
419 wait_ms,
420 sample_percent,
421 owners_filename,
422 owners_line_number);
423 }
424 }
425 }
426 ATRACE_END();
427 }
428 }
429 self->SetMonitorEnterObject(nullptr);
430 monitor_lock_.Lock(self); // Reacquire locks in order.
431 --num_waiters_;
432 }
433
434 AtraceMonitorLock(self, GetObject(), false /* is_wait */);
435 }
436
437 static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
438 __attribute__((format(printf, 1, 2)));
439
ThrowIllegalMonitorStateExceptionF(const char * fmt,...)440 static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
441 SHARED_REQUIRES(Locks::mutator_lock_) {
442 va_list args;
443 va_start(args, fmt);
444 Thread* self = Thread::Current();
445 self->ThrowNewExceptionV("Ljava/lang/IllegalMonitorStateException;", fmt, args);
446 if (!Runtime::Current()->IsStarted() || VLOG_IS_ON(monitor)) {
447 std::ostringstream ss;
448 self->Dump(ss);
449 LOG(Runtime::Current()->IsStarted() ? INFO : ERROR)
450 << self->GetException()->Dump() << "\n" << ss.str();
451 }
452 va_end(args);
453 }
454
ThreadToString(Thread * thread)455 static std::string ThreadToString(Thread* thread) {
456 if (thread == nullptr) {
457 return "nullptr";
458 }
459 std::ostringstream oss;
460 // TODO: alternatively, we could just return the thread's name.
461 oss << *thread;
462 return oss.str();
463 }
464
FailedUnlock(mirror::Object * o,uint32_t expected_owner_thread_id,uint32_t found_owner_thread_id,Monitor * monitor)465 void Monitor::FailedUnlock(mirror::Object* o,
466 uint32_t expected_owner_thread_id,
467 uint32_t found_owner_thread_id,
468 Monitor* monitor) {
469 // Acquire thread list lock so threads won't disappear from under us.
470 std::string current_owner_string;
471 std::string expected_owner_string;
472 std::string found_owner_string;
473 uint32_t current_owner_thread_id = 0u;
474 {
475 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
476 ThreadList* const thread_list = Runtime::Current()->GetThreadList();
477 Thread* expected_owner = thread_list->FindThreadByThreadId(expected_owner_thread_id);
478 Thread* found_owner = thread_list->FindThreadByThreadId(found_owner_thread_id);
479
480 // Re-read owner now that we hold lock.
481 Thread* current_owner = (monitor != nullptr) ? monitor->GetOwner() : nullptr;
482 if (current_owner != nullptr) {
483 current_owner_thread_id = current_owner->GetThreadId();
484 }
485 // Get short descriptions of the threads involved.
486 current_owner_string = ThreadToString(current_owner);
487 expected_owner_string = expected_owner != nullptr ? ThreadToString(expected_owner) : "unnamed";
488 found_owner_string = found_owner != nullptr ? ThreadToString(found_owner) : "unnamed";
489 }
490
491 if (current_owner_thread_id == 0u) {
492 if (found_owner_thread_id == 0u) {
493 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
494 " on thread '%s'",
495 PrettyTypeOf(o).c_str(),
496 expected_owner_string.c_str());
497 } else {
498 // Race: the original read found an owner but now there is none
499 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
500 " (where now the monitor appears unowned) on thread '%s'",
501 found_owner_string.c_str(),
502 PrettyTypeOf(o).c_str(),
503 expected_owner_string.c_str());
504 }
505 } else {
506 if (found_owner_thread_id == 0u) {
507 // Race: originally there was no owner, there is now
508 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
509 " (originally believed to be unowned) on thread '%s'",
510 current_owner_string.c_str(),
511 PrettyTypeOf(o).c_str(),
512 expected_owner_string.c_str());
513 } else {
514 if (found_owner_thread_id != current_owner_thread_id) {
515 // Race: originally found and current owner have changed
516 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
517 " owned by '%s') on object of type '%s' on thread '%s'",
518 found_owner_string.c_str(),
519 current_owner_string.c_str(),
520 PrettyTypeOf(o).c_str(),
521 expected_owner_string.c_str());
522 } else {
523 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
524 " on thread '%s",
525 current_owner_string.c_str(),
526 PrettyTypeOf(o).c_str(),
527 expected_owner_string.c_str());
528 }
529 }
530 }
531 }
532
Unlock(Thread * self)533 bool Monitor::Unlock(Thread* self) {
534 DCHECK(self != nullptr);
535 uint32_t owner_thread_id = 0u;
536 {
537 MutexLock mu(self, monitor_lock_);
538 Thread* owner = owner_;
539 if (owner != nullptr) {
540 owner_thread_id = owner->GetThreadId();
541 }
542 if (owner == self) {
543 // We own the monitor, so nobody else can be in here.
544 AtraceMonitorUnlock();
545 if (lock_count_ == 0) {
546 owner_ = nullptr;
547 locking_method_ = nullptr;
548 locking_dex_pc_ = 0;
549 // Wake a contender.
550 monitor_contenders_.Signal(self);
551 } else {
552 --lock_count_;
553 }
554 return true;
555 }
556 }
557 // We don't own this, so we're not allowed to unlock it.
558 // The JNI spec says that we should throw IllegalMonitorStateException in this case.
559 FailedUnlock(GetObject(), self->GetThreadId(), owner_thread_id, this);
560 return false;
561 }
562
Wait(Thread * self,int64_t ms,int32_t ns,bool interruptShouldThrow,ThreadState why)563 void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
564 bool interruptShouldThrow, ThreadState why) {
565 DCHECK(self != nullptr);
566 DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
567
568 monitor_lock_.Lock(self);
569
570 // Make sure that we hold the lock.
571 if (owner_ != self) {
572 monitor_lock_.Unlock(self);
573 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
574 return;
575 }
576
577 // We need to turn a zero-length timed wait into a regular wait because
578 // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
579 if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
580 why = kWaiting;
581 }
582
583 // Enforce the timeout range.
584 if (ms < 0 || ns < 0 || ns > 999999) {
585 monitor_lock_.Unlock(self);
586 self->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
587 "timeout arguments out of range: ms=%" PRId64 " ns=%d", ms, ns);
588 return;
589 }
590
591 /*
592 * Add ourselves to the set of threads waiting on this monitor, and
593 * release our hold. We need to let it go even if we're a few levels
594 * deep in a recursive lock, and we need to restore that later.
595 *
596 * We append to the wait set ahead of clearing the count and owner
597 * fields so the subroutine can check that the calling thread owns
598 * the monitor. Aside from that, the order of member updates is
599 * not order sensitive as we hold the pthread mutex.
600 */
601 AppendToWaitSet(self);
602 ++num_waiters_;
603 int prev_lock_count = lock_count_;
604 lock_count_ = 0;
605 owner_ = nullptr;
606 ArtMethod* saved_method = locking_method_;
607 locking_method_ = nullptr;
608 uintptr_t saved_dex_pc = locking_dex_pc_;
609 locking_dex_pc_ = 0;
610
611 AtraceMonitorUnlock(); // For the implict Unlock() just above. This will only end the deepest
612 // nesting, but that is enough for the visualization, and corresponds to
613 // the single Lock() we do afterwards.
614 AtraceMonitorLock(self, GetObject(), true /* is_wait */);
615
616 bool was_interrupted = false;
617 {
618 // Update thread state. If the GC wakes up, it'll ignore us, knowing
619 // that we won't touch any references in this state, and we'll check
620 // our suspend mode before we transition out.
621 ScopedThreadSuspension sts(self, why);
622
623 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
624 MutexLock mu(self, *self->GetWaitMutex());
625
626 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
627 // non-null a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
628 // up.
629 DCHECK(self->GetWaitMonitor() == nullptr);
630 self->SetWaitMonitor(this);
631
632 // Release the monitor lock.
633 monitor_contenders_.Signal(self);
634 monitor_lock_.Unlock(self);
635
636 // Handle the case where the thread was interrupted before we called wait().
637 if (self->IsInterruptedLocked()) {
638 was_interrupted = true;
639 } else {
640 // Wait for a notification or a timeout to occur.
641 if (why == kWaiting) {
642 self->GetWaitConditionVariable()->Wait(self);
643 } else {
644 DCHECK(why == kTimedWaiting || why == kSleeping) << why;
645 self->GetWaitConditionVariable()->TimedWait(self, ms, ns);
646 }
647 was_interrupted = self->IsInterruptedLocked();
648 }
649 }
650
651 {
652 // We reset the thread's wait_monitor_ field after transitioning back to runnable so
653 // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
654 // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
655 // are waiting on "null".)
656 MutexLock mu(self, *self->GetWaitMutex());
657 DCHECK(self->GetWaitMonitor() != nullptr);
658 self->SetWaitMonitor(nullptr);
659 }
660
661 // Allocate the interrupted exception not holding the monitor lock since it may cause a GC.
662 // If the GC requires acquiring the monitor for enqueuing cleared references, this would
663 // cause a deadlock if the monitor is held.
664 if (was_interrupted && interruptShouldThrow) {
665 /*
666 * We were interrupted while waiting, or somebody interrupted an
667 * un-interruptible thread earlier and we're bailing out immediately.
668 *
669 * The doc sayeth: "The interrupted status of the current thread is
670 * cleared when this exception is thrown."
671 */
672 {
673 MutexLock mu(self, *self->GetWaitMutex());
674 self->SetInterruptedLocked(false);
675 }
676 self->ThrowNewException("Ljava/lang/InterruptedException;", nullptr);
677 }
678
679 AtraceMonitorUnlock(); // End Wait().
680
681 // Re-acquire the monitor and lock.
682 Lock(self);
683 monitor_lock_.Lock(self);
684 self->GetWaitMutex()->AssertNotHeld(self);
685
686 /*
687 * We remove our thread from wait set after restoring the count
688 * and owner fields so the subroutine can check that the calling
689 * thread owns the monitor. Aside from that, the order of member
690 * updates is not order sensitive as we hold the pthread mutex.
691 */
692 owner_ = self;
693 lock_count_ = prev_lock_count;
694 locking_method_ = saved_method;
695 locking_dex_pc_ = saved_dex_pc;
696 --num_waiters_;
697 RemoveFromWaitSet(self);
698
699 monitor_lock_.Unlock(self);
700 }
701
Notify(Thread * self)702 void Monitor::Notify(Thread* self) {
703 DCHECK(self != nullptr);
704 MutexLock mu(self, monitor_lock_);
705 // Make sure that we hold the lock.
706 if (owner_ != self) {
707 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
708 return;
709 }
710 // Signal the first waiting thread in the wait set.
711 while (wait_set_ != nullptr) {
712 Thread* thread = wait_set_;
713 wait_set_ = thread->GetWaitNext();
714 thread->SetWaitNext(nullptr);
715
716 // Check to see if the thread is still waiting.
717 MutexLock wait_mu(self, *thread->GetWaitMutex());
718 if (thread->GetWaitMonitor() != nullptr) {
719 thread->GetWaitConditionVariable()->Signal(self);
720 return;
721 }
722 }
723 }
724
NotifyAll(Thread * self)725 void Monitor::NotifyAll(Thread* self) {
726 DCHECK(self != nullptr);
727 MutexLock mu(self, monitor_lock_);
728 // Make sure that we hold the lock.
729 if (owner_ != self) {
730 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
731 return;
732 }
733 // Signal all threads in the wait set.
734 while (wait_set_ != nullptr) {
735 Thread* thread = wait_set_;
736 wait_set_ = thread->GetWaitNext();
737 thread->SetWaitNext(nullptr);
738 thread->Notify();
739 }
740 }
741
Deflate(Thread * self,mirror::Object * obj)742 bool Monitor::Deflate(Thread* self, mirror::Object* obj) {
743 DCHECK(obj != nullptr);
744 // Don't need volatile since we only deflate with mutators suspended.
745 LockWord lw(obj->GetLockWord(false));
746 // If the lock isn't an inflated monitor, then we don't need to deflate anything.
747 if (lw.GetState() == LockWord::kFatLocked) {
748 Monitor* monitor = lw.FatLockMonitor();
749 DCHECK(monitor != nullptr);
750 MutexLock mu(self, monitor->monitor_lock_);
751 // Can't deflate if we have anybody waiting on the CV.
752 if (monitor->num_waiters_ > 0) {
753 return false;
754 }
755 Thread* owner = monitor->owner_;
756 if (owner != nullptr) {
757 // Can't deflate if we are locked and have a hash code.
758 if (monitor->HasHashCode()) {
759 return false;
760 }
761 // Can't deflate if our lock count is too high.
762 if (monitor->lock_count_ > LockWord::kThinLockMaxCount) {
763 return false;
764 }
765 // Deflate to a thin lock.
766 LockWord new_lw = LockWord::FromThinLockId(owner->GetThreadId(), monitor->lock_count_,
767 lw.ReadBarrierState());
768 // Assume no concurrent read barrier state changes as mutators are suspended.
769 obj->SetLockWord(new_lw, false);
770 VLOG(monitor) << "Deflated " << obj << " to thin lock " << owner->GetTid() << " / "
771 << monitor->lock_count_;
772 } else if (monitor->HasHashCode()) {
773 LockWord new_lw = LockWord::FromHashCode(monitor->GetHashCode(), lw.ReadBarrierState());
774 // Assume no concurrent read barrier state changes as mutators are suspended.
775 obj->SetLockWord(new_lw, false);
776 VLOG(monitor) << "Deflated " << obj << " to hash monitor " << monitor->GetHashCode();
777 } else {
778 // No lock and no hash, just put an empty lock word inside the object.
779 LockWord new_lw = LockWord::FromDefault(lw.ReadBarrierState());
780 // Assume no concurrent read barrier state changes as mutators are suspended.
781 obj->SetLockWord(new_lw, false);
782 VLOG(monitor) << "Deflated" << obj << " to empty lock word";
783 }
784 // The monitor is deflated, mark the object as null so that we know to delete it during the
785 // next GC.
786 monitor->obj_ = GcRoot<mirror::Object>(nullptr);
787 }
788 return true;
789 }
790
Inflate(Thread * self,Thread * owner,mirror::Object * obj,int32_t hash_code)791 void Monitor::Inflate(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code) {
792 DCHECK(self != nullptr);
793 DCHECK(obj != nullptr);
794 // Allocate and acquire a new monitor.
795 Monitor* m = MonitorPool::CreateMonitor(self, owner, obj, hash_code);
796 DCHECK(m != nullptr);
797 if (m->Install(self)) {
798 if (owner != nullptr) {
799 VLOG(monitor) << "monitor: thread" << owner->GetThreadId()
800 << " created monitor " << m << " for object " << obj;
801 } else {
802 VLOG(monitor) << "monitor: Inflate with hashcode " << hash_code
803 << " created monitor " << m << " for object " << obj;
804 }
805 Runtime::Current()->GetMonitorList()->Add(m);
806 CHECK_EQ(obj->GetLockWord(true).GetState(), LockWord::kFatLocked);
807 } else {
808 MonitorPool::ReleaseMonitor(self, m);
809 }
810 }
811
InflateThinLocked(Thread * self,Handle<mirror::Object> obj,LockWord lock_word,uint32_t hash_code)812 void Monitor::InflateThinLocked(Thread* self, Handle<mirror::Object> obj, LockWord lock_word,
813 uint32_t hash_code) {
814 DCHECK_EQ(lock_word.GetState(), LockWord::kThinLocked);
815 uint32_t owner_thread_id = lock_word.ThinLockOwner();
816 if (owner_thread_id == self->GetThreadId()) {
817 // We own the monitor, we can easily inflate it.
818 Inflate(self, self, obj.Get(), hash_code);
819 } else {
820 ThreadList* thread_list = Runtime::Current()->GetThreadList();
821 // Suspend the owner, inflate. First change to blocked and give up mutator_lock_.
822 self->SetMonitorEnterObject(obj.Get());
823 bool timed_out;
824 Thread* owner;
825 {
826 ScopedThreadSuspension sts(self, kBlocked);
827 owner = thread_list->SuspendThreadByThreadId(owner_thread_id, false, &timed_out);
828 }
829 if (owner != nullptr) {
830 // We succeeded in suspending the thread, check the lock's status didn't change.
831 lock_word = obj->GetLockWord(true);
832 if (lock_word.GetState() == LockWord::kThinLocked &&
833 lock_word.ThinLockOwner() == owner_thread_id) {
834 // Go ahead and inflate the lock.
835 Inflate(self, owner, obj.Get(), hash_code);
836 }
837 thread_list->Resume(owner, false);
838 }
839 self->SetMonitorEnterObject(nullptr);
840 }
841 }
842
843 // Fool annotalysis into thinking that the lock on obj is acquired.
FakeLock(mirror::Object * obj)844 static mirror::Object* FakeLock(mirror::Object* obj)
845 EXCLUSIVE_LOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
846 return obj;
847 }
848
849 // Fool annotalysis into thinking that the lock on obj is release.
FakeUnlock(mirror::Object * obj)850 static mirror::Object* FakeUnlock(mirror::Object* obj)
851 UNLOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
852 return obj;
853 }
854
MonitorEnter(Thread * self,mirror::Object * obj)855 mirror::Object* Monitor::MonitorEnter(Thread* self, mirror::Object* obj) {
856 DCHECK(self != nullptr);
857 DCHECK(obj != nullptr);
858 self->AssertThreadSuspensionIsAllowable();
859 obj = FakeLock(obj);
860 uint32_t thread_id = self->GetThreadId();
861 size_t contention_count = 0;
862 StackHandleScope<1> hs(self);
863 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
864 while (true) {
865 LockWord lock_word = h_obj->GetLockWord(true);
866 switch (lock_word.GetState()) {
867 case LockWord::kUnlocked: {
868 LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0, lock_word.ReadBarrierState()));
869 if (h_obj->CasLockWordWeakSequentiallyConsistent(lock_word, thin_locked)) {
870 AtraceMonitorLock(self, h_obj.Get(), false /* is_wait */);
871 // CasLockWord enforces more than the acquire ordering we need here.
872 return h_obj.Get(); // Success!
873 }
874 continue; // Go again.
875 }
876 case LockWord::kThinLocked: {
877 uint32_t owner_thread_id = lock_word.ThinLockOwner();
878 if (owner_thread_id == thread_id) {
879 // We own the lock, increase the recursion count.
880 uint32_t new_count = lock_word.ThinLockCount() + 1;
881 if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
882 LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count,
883 lock_word.ReadBarrierState()));
884 if (!kUseReadBarrier) {
885 h_obj->SetLockWord(thin_locked, true);
886 AtraceMonitorLock(self, h_obj.Get(), false /* is_wait */);
887 return h_obj.Get(); // Success!
888 } else {
889 // Use CAS to preserve the read barrier state.
890 if (h_obj->CasLockWordWeakSequentiallyConsistent(lock_word, thin_locked)) {
891 AtraceMonitorLock(self, h_obj.Get(), false /* is_wait */);
892 return h_obj.Get(); // Success!
893 }
894 }
895 continue; // Go again.
896 } else {
897 // We'd overflow the recursion count, so inflate the monitor.
898 InflateThinLocked(self, h_obj, lock_word, 0);
899 }
900 } else {
901 // Contention.
902 contention_count++;
903 Runtime* runtime = Runtime::Current();
904 if (contention_count <= runtime->GetMaxSpinsBeforeThinkLockInflation()) {
905 // TODO: Consider switching the thread state to kBlocked when we are yielding.
906 // Use sched_yield instead of NanoSleep since NanoSleep can wait much longer than the
907 // parameter you pass in. This can cause thread suspension to take excessively long
908 // and make long pauses. See b/16307460.
909 sched_yield();
910 } else {
911 contention_count = 0;
912 InflateThinLocked(self, h_obj, lock_word, 0);
913 }
914 }
915 continue; // Start from the beginning.
916 }
917 case LockWord::kFatLocked: {
918 Monitor* mon = lock_word.FatLockMonitor();
919 mon->Lock(self);
920 return h_obj.Get(); // Success!
921 }
922 case LockWord::kHashCode:
923 // Inflate with the existing hashcode.
924 Inflate(self, nullptr, h_obj.Get(), lock_word.GetHashCode());
925 continue; // Start from the beginning.
926 default: {
927 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
928 UNREACHABLE();
929 }
930 }
931 }
932 }
933
MonitorExit(Thread * self,mirror::Object * obj)934 bool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
935 DCHECK(self != nullptr);
936 DCHECK(obj != nullptr);
937 self->AssertThreadSuspensionIsAllowable();
938 obj = FakeUnlock(obj);
939 StackHandleScope<1> hs(self);
940 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
941 while (true) {
942 LockWord lock_word = obj->GetLockWord(true);
943 switch (lock_word.GetState()) {
944 case LockWord::kHashCode:
945 // Fall-through.
946 case LockWord::kUnlocked:
947 FailedUnlock(h_obj.Get(), self->GetThreadId(), 0u, nullptr);
948 return false; // Failure.
949 case LockWord::kThinLocked: {
950 uint32_t thread_id = self->GetThreadId();
951 uint32_t owner_thread_id = lock_word.ThinLockOwner();
952 if (owner_thread_id != thread_id) {
953 FailedUnlock(h_obj.Get(), thread_id, owner_thread_id, nullptr);
954 return false; // Failure.
955 } else {
956 // We own the lock, decrease the recursion count.
957 LockWord new_lw = LockWord::Default();
958 if (lock_word.ThinLockCount() != 0) {
959 uint32_t new_count = lock_word.ThinLockCount() - 1;
960 new_lw = LockWord::FromThinLockId(thread_id, new_count, lock_word.ReadBarrierState());
961 } else {
962 new_lw = LockWord::FromDefault(lock_word.ReadBarrierState());
963 }
964 if (!kUseReadBarrier) {
965 DCHECK_EQ(new_lw.ReadBarrierState(), 0U);
966 h_obj->SetLockWord(new_lw, true);
967 AtraceMonitorUnlock();
968 // Success!
969 return true;
970 } else {
971 // Use CAS to preserve the read barrier state.
972 if (h_obj->CasLockWordWeakSequentiallyConsistent(lock_word, new_lw)) {
973 AtraceMonitorUnlock();
974 // Success!
975 return true;
976 }
977 }
978 continue; // Go again.
979 }
980 }
981 case LockWord::kFatLocked: {
982 Monitor* mon = lock_word.FatLockMonitor();
983 return mon->Unlock(self);
984 }
985 default: {
986 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
987 return false;
988 }
989 }
990 }
991 }
992
Wait(Thread * self,mirror::Object * obj,int64_t ms,int32_t ns,bool interruptShouldThrow,ThreadState why)993 void Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
994 bool interruptShouldThrow, ThreadState why) {
995 DCHECK(self != nullptr);
996 DCHECK(obj != nullptr);
997 LockWord lock_word = obj->GetLockWord(true);
998 while (lock_word.GetState() != LockWord::kFatLocked) {
999 switch (lock_word.GetState()) {
1000 case LockWord::kHashCode:
1001 // Fall-through.
1002 case LockWord::kUnlocked:
1003 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
1004 return; // Failure.
1005 case LockWord::kThinLocked: {
1006 uint32_t thread_id = self->GetThreadId();
1007 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1008 if (owner_thread_id != thread_id) {
1009 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
1010 return; // Failure.
1011 } else {
1012 // We own the lock, inflate to enqueue ourself on the Monitor. May fail spuriously so
1013 // re-load.
1014 Inflate(self, self, obj, 0);
1015 lock_word = obj->GetLockWord(true);
1016 }
1017 break;
1018 }
1019 case LockWord::kFatLocked: // Unreachable given the loop condition above. Fall-through.
1020 default: {
1021 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1022 return;
1023 }
1024 }
1025 }
1026 Monitor* mon = lock_word.FatLockMonitor();
1027 mon->Wait(self, ms, ns, interruptShouldThrow, why);
1028 }
1029
DoNotify(Thread * self,mirror::Object * obj,bool notify_all)1030 void Monitor::DoNotify(Thread* self, mirror::Object* obj, bool notify_all) {
1031 DCHECK(self != nullptr);
1032 DCHECK(obj != nullptr);
1033 LockWord lock_word = obj->GetLockWord(true);
1034 switch (lock_word.GetState()) {
1035 case LockWord::kHashCode:
1036 // Fall-through.
1037 case LockWord::kUnlocked:
1038 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
1039 return; // Failure.
1040 case LockWord::kThinLocked: {
1041 uint32_t thread_id = self->GetThreadId();
1042 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1043 if (owner_thread_id != thread_id) {
1044 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
1045 return; // Failure.
1046 } else {
1047 // We own the lock but there's no Monitor and therefore no waiters.
1048 return; // Success.
1049 }
1050 }
1051 case LockWord::kFatLocked: {
1052 Monitor* mon = lock_word.FatLockMonitor();
1053 if (notify_all) {
1054 mon->NotifyAll(self);
1055 } else {
1056 mon->Notify(self);
1057 }
1058 return; // Success.
1059 }
1060 default: {
1061 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1062 return;
1063 }
1064 }
1065 }
1066
GetLockOwnerThreadId(mirror::Object * obj)1067 uint32_t Monitor::GetLockOwnerThreadId(mirror::Object* obj) {
1068 DCHECK(obj != nullptr);
1069 LockWord lock_word = obj->GetLockWord(true);
1070 switch (lock_word.GetState()) {
1071 case LockWord::kHashCode:
1072 // Fall-through.
1073 case LockWord::kUnlocked:
1074 return ThreadList::kInvalidThreadId;
1075 case LockWord::kThinLocked:
1076 return lock_word.ThinLockOwner();
1077 case LockWord::kFatLocked: {
1078 Monitor* mon = lock_word.FatLockMonitor();
1079 return mon->GetOwnerThreadId();
1080 }
1081 default: {
1082 LOG(FATAL) << "Unreachable";
1083 UNREACHABLE();
1084 }
1085 }
1086 }
1087
DescribeWait(std::ostream & os,const Thread * thread)1088 void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
1089 // Determine the wait message and object we're waiting or blocked upon.
1090 mirror::Object* pretty_object = nullptr;
1091 const char* wait_message = nullptr;
1092 uint32_t lock_owner = ThreadList::kInvalidThreadId;
1093 ThreadState state = thread->GetState();
1094 if (state == kWaiting || state == kTimedWaiting || state == kSleeping) {
1095 wait_message = (state == kSleeping) ? " - sleeping on " : " - waiting on ";
1096 Thread* self = Thread::Current();
1097 MutexLock mu(self, *thread->GetWaitMutex());
1098 Monitor* monitor = thread->GetWaitMonitor();
1099 if (monitor != nullptr) {
1100 pretty_object = monitor->GetObject();
1101 }
1102 } else if (state == kBlocked) {
1103 wait_message = " - waiting to lock ";
1104 pretty_object = thread->GetMonitorEnterObject();
1105 if (pretty_object != nullptr) {
1106 lock_owner = pretty_object->GetLockOwnerThreadId();
1107 }
1108 }
1109
1110 if (wait_message != nullptr) {
1111 if (pretty_object == nullptr) {
1112 os << wait_message << "an unknown object";
1113 } else {
1114 if ((pretty_object->GetLockWord(true).GetState() == LockWord::kThinLocked) &&
1115 Locks::mutator_lock_->IsExclusiveHeld(Thread::Current())) {
1116 // Getting the identity hashcode here would result in lock inflation and suspension of the
1117 // current thread, which isn't safe if this is the only runnable thread.
1118 os << wait_message << StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)",
1119 reinterpret_cast<intptr_t>(pretty_object),
1120 PrettyTypeOf(pretty_object).c_str());
1121 } else {
1122 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
1123 // Call PrettyTypeOf before IdentityHashCode since IdentityHashCode can cause thread
1124 // suspension and move pretty_object.
1125 const std::string pretty_type(PrettyTypeOf(pretty_object));
1126 os << wait_message << StringPrintf("<0x%08x> (a %s)", pretty_object->IdentityHashCode(),
1127 pretty_type.c_str());
1128 }
1129 }
1130 // - waiting to lock <0x613f83d8> (a java.lang.Object) held by thread 5
1131 if (lock_owner != ThreadList::kInvalidThreadId) {
1132 os << " held by thread " << lock_owner;
1133 }
1134 os << "\n";
1135 }
1136 }
1137
GetContendedMonitor(Thread * thread)1138 mirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
1139 // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
1140 // definition of contended that includes a monitor a thread is trying to enter...
1141 mirror::Object* result = thread->GetMonitorEnterObject();
1142 if (result == nullptr) {
1143 // ...but also a monitor that the thread is waiting on.
1144 MutexLock mu(Thread::Current(), *thread->GetWaitMutex());
1145 Monitor* monitor = thread->GetWaitMonitor();
1146 if (monitor != nullptr) {
1147 result = monitor->GetObject();
1148 }
1149 }
1150 return result;
1151 }
1152
VisitLocks(StackVisitor * stack_visitor,void (* callback)(mirror::Object *,void *),void * callback_context,bool abort_on_failure)1153 void Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
1154 void* callback_context, bool abort_on_failure) {
1155 ArtMethod* m = stack_visitor->GetMethod();
1156 CHECK(m != nullptr);
1157
1158 // Native methods are an easy special case.
1159 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
1160 if (m->IsNative()) {
1161 if (m->IsSynchronized()) {
1162 mirror::Object* jni_this =
1163 stack_visitor->GetCurrentHandleScope(sizeof(void*))->GetReference(0);
1164 callback(jni_this, callback_context);
1165 }
1166 return;
1167 }
1168
1169 // Proxy methods should not be synchronized.
1170 if (m->IsProxyMethod()) {
1171 CHECK(!m->IsSynchronized());
1172 return;
1173 }
1174
1175 // Is there any reason to believe there's any synchronization in this method?
1176 const DexFile::CodeItem* code_item = m->GetCodeItem();
1177 CHECK(code_item != nullptr) << PrettyMethod(m);
1178 if (code_item->tries_size_ == 0) {
1179 return; // No "tries" implies no synchronization, so no held locks to report.
1180 }
1181
1182 // Get the dex pc. If abort_on_failure is false, GetDexPc will not abort in the case it cannot
1183 // find the dex pc, and instead return kDexNoIndex. Then bail out, as it indicates we have an
1184 // inconsistent stack anyways.
1185 uint32_t dex_pc = stack_visitor->GetDexPc(abort_on_failure);
1186 if (!abort_on_failure && dex_pc == DexFile::kDexNoIndex) {
1187 LOG(ERROR) << "Could not find dex_pc for " << PrettyMethod(m);
1188 return;
1189 }
1190
1191 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
1192 // the locks held in this stack frame.
1193 std::vector<uint32_t> monitor_enter_dex_pcs;
1194 verifier::MethodVerifier::FindLocksAtDexPc(m, dex_pc, &monitor_enter_dex_pcs);
1195 for (uint32_t monitor_dex_pc : monitor_enter_dex_pcs) {
1196 // The verifier works in terms of the dex pcs of the monitor-enter instructions.
1197 // We want the registers used by those instructions (so we can read the values out of them).
1198 const Instruction* monitor_enter_instruction =
1199 Instruction::At(&code_item->insns_[monitor_dex_pc]);
1200
1201 // Quick sanity check.
1202 CHECK_EQ(monitor_enter_instruction->Opcode(), Instruction::MONITOR_ENTER)
1203 << "expected monitor-enter @" << monitor_dex_pc << "; was "
1204 << reinterpret_cast<const void*>(monitor_enter_instruction);
1205
1206 uint16_t monitor_register = monitor_enter_instruction->VRegA();
1207 uint32_t value;
1208 bool success = stack_visitor->GetVReg(m, monitor_register, kReferenceVReg, &value);
1209 CHECK(success) << "Failed to read v" << monitor_register << " of kind "
1210 << kReferenceVReg << " in method " << PrettyMethod(m);
1211 mirror::Object* o = reinterpret_cast<mirror::Object*>(value);
1212 callback(o, callback_context);
1213 }
1214 }
1215
IsValidLockWord(LockWord lock_word)1216 bool Monitor::IsValidLockWord(LockWord lock_word) {
1217 switch (lock_word.GetState()) {
1218 case LockWord::kUnlocked:
1219 // Nothing to check.
1220 return true;
1221 case LockWord::kThinLocked:
1222 // Basic sanity check of owner.
1223 return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
1224 case LockWord::kFatLocked: {
1225 // Check the monitor appears in the monitor list.
1226 Monitor* mon = lock_word.FatLockMonitor();
1227 MonitorList* list = Runtime::Current()->GetMonitorList();
1228 MutexLock mu(Thread::Current(), list->monitor_list_lock_);
1229 for (Monitor* list_mon : list->list_) {
1230 if (mon == list_mon) {
1231 return true; // Found our monitor.
1232 }
1233 }
1234 return false; // Fail - unowned monitor in an object.
1235 }
1236 case LockWord::kHashCode:
1237 return true;
1238 default:
1239 LOG(FATAL) << "Unreachable";
1240 UNREACHABLE();
1241 }
1242 }
1243
IsLocked()1244 bool Monitor::IsLocked() SHARED_REQUIRES(Locks::mutator_lock_) {
1245 MutexLock mu(Thread::Current(), monitor_lock_);
1246 return owner_ != nullptr;
1247 }
1248
TranslateLocation(ArtMethod * method,uint32_t dex_pc,const char ** source_file,int32_t * line_number)1249 void Monitor::TranslateLocation(ArtMethod* method,
1250 uint32_t dex_pc,
1251 const char** source_file,
1252 int32_t* line_number) {
1253 // If method is null, location is unknown
1254 if (method == nullptr) {
1255 *source_file = "";
1256 *line_number = 0;
1257 return;
1258 }
1259 *source_file = method->GetDeclaringClassSourceFile();
1260 if (*source_file == nullptr) {
1261 *source_file = "";
1262 }
1263 *line_number = method->GetLineNumFromDexPC(dex_pc);
1264 }
1265
GetOwnerThreadId()1266 uint32_t Monitor::GetOwnerThreadId() {
1267 MutexLock mu(Thread::Current(), monitor_lock_);
1268 Thread* owner = owner_;
1269 if (owner != nullptr) {
1270 return owner->GetThreadId();
1271 } else {
1272 return ThreadList::kInvalidThreadId;
1273 }
1274 }
1275
MonitorList()1276 MonitorList::MonitorList()
1277 : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock", kMonitorListLock),
1278 monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
1279 }
1280
~MonitorList()1281 MonitorList::~MonitorList() {
1282 Thread* self = Thread::Current();
1283 MutexLock mu(self, monitor_list_lock_);
1284 // Release all monitors to the pool.
1285 // TODO: Is it an invariant that *all* open monitors are in the list? Then we could
1286 // clear faster in the pool.
1287 MonitorPool::ReleaseMonitors(self, &list_);
1288 }
1289
DisallowNewMonitors()1290 void MonitorList::DisallowNewMonitors() {
1291 CHECK(!kUseReadBarrier);
1292 MutexLock mu(Thread::Current(), monitor_list_lock_);
1293 allow_new_monitors_ = false;
1294 }
1295
AllowNewMonitors()1296 void MonitorList::AllowNewMonitors() {
1297 CHECK(!kUseReadBarrier);
1298 Thread* self = Thread::Current();
1299 MutexLock mu(self, monitor_list_lock_);
1300 allow_new_monitors_ = true;
1301 monitor_add_condition_.Broadcast(self);
1302 }
1303
BroadcastForNewMonitors()1304 void MonitorList::BroadcastForNewMonitors() {
1305 CHECK(kUseReadBarrier);
1306 Thread* self = Thread::Current();
1307 MutexLock mu(self, monitor_list_lock_);
1308 monitor_add_condition_.Broadcast(self);
1309 }
1310
Add(Monitor * m)1311 void MonitorList::Add(Monitor* m) {
1312 Thread* self = Thread::Current();
1313 MutexLock mu(self, monitor_list_lock_);
1314 while (UNLIKELY((!kUseReadBarrier && !allow_new_monitors_) ||
1315 (kUseReadBarrier && !self->GetWeakRefAccessEnabled()))) {
1316 monitor_add_condition_.WaitHoldingLocks(self);
1317 }
1318 list_.push_front(m);
1319 }
1320
SweepMonitorList(IsMarkedVisitor * visitor)1321 void MonitorList::SweepMonitorList(IsMarkedVisitor* visitor) {
1322 Thread* self = Thread::Current();
1323 MutexLock mu(self, monitor_list_lock_);
1324 for (auto it = list_.begin(); it != list_.end(); ) {
1325 Monitor* m = *it;
1326 // Disable the read barrier in GetObject() as this is called by GC.
1327 mirror::Object* obj = m->GetObject<kWithoutReadBarrier>();
1328 // The object of a monitor can be null if we have deflated it.
1329 mirror::Object* new_obj = obj != nullptr ? visitor->IsMarked(obj) : nullptr;
1330 if (new_obj == nullptr) {
1331 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
1332 << obj;
1333 MonitorPool::ReleaseMonitor(self, m);
1334 it = list_.erase(it);
1335 } else {
1336 m->SetObject(new_obj);
1337 ++it;
1338 }
1339 }
1340 }
1341
1342 class MonitorDeflateVisitor : public IsMarkedVisitor {
1343 public:
MonitorDeflateVisitor()1344 MonitorDeflateVisitor() : self_(Thread::Current()), deflate_count_(0) {}
1345
IsMarked(mirror::Object * object)1346 virtual mirror::Object* IsMarked(mirror::Object* object) OVERRIDE
1347 SHARED_REQUIRES(Locks::mutator_lock_) {
1348 if (Monitor::Deflate(self_, object)) {
1349 DCHECK_NE(object->GetLockWord(true).GetState(), LockWord::kFatLocked);
1350 ++deflate_count_;
1351 // If we deflated, return null so that the monitor gets removed from the array.
1352 return nullptr;
1353 }
1354 return object; // Monitor was not deflated.
1355 }
1356
1357 Thread* const self_;
1358 size_t deflate_count_;
1359 };
1360
DeflateMonitors()1361 size_t MonitorList::DeflateMonitors() {
1362 MonitorDeflateVisitor visitor;
1363 Locks::mutator_lock_->AssertExclusiveHeld(visitor.self_);
1364 SweepMonitorList(&visitor);
1365 return visitor.deflate_count_;
1366 }
1367
MonitorInfo(mirror::Object * obj)1368 MonitorInfo::MonitorInfo(mirror::Object* obj) : owner_(nullptr), entry_count_(0) {
1369 DCHECK(obj != nullptr);
1370 LockWord lock_word = obj->GetLockWord(true);
1371 switch (lock_word.GetState()) {
1372 case LockWord::kUnlocked:
1373 // Fall-through.
1374 case LockWord::kForwardingAddress:
1375 // Fall-through.
1376 case LockWord::kHashCode:
1377 break;
1378 case LockWord::kThinLocked:
1379 owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
1380 entry_count_ = 1 + lock_word.ThinLockCount();
1381 // Thin locks have no waiters.
1382 break;
1383 case LockWord::kFatLocked: {
1384 Monitor* mon = lock_word.FatLockMonitor();
1385 owner_ = mon->owner_;
1386 entry_count_ = 1 + mon->lock_count_;
1387 for (Thread* waiter = mon->wait_set_; waiter != nullptr; waiter = waiter->GetWaitNext()) {
1388 waiters_.push_back(waiter);
1389 }
1390 break;
1391 }
1392 }
1393 }
1394
1395 } // namespace art
1396