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