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 <android-base/properties.h>
18
19 #include <vector>
20
21 #include "android-base/stringprintf.h"
22 #include "art_method-inl.h"
23 #include "base/logging.h" // For VLOG.
24 #include "base/mutex.h"
25 #include "base/quasi_atomic.h"
26 #include "base/stl_util.h"
27 #include "base/systrace.h"
28 #include "base/time_utils.h"
29 #include "class_linker.h"
30 #include "dex/dex_file-inl.h"
31 #include "dex/dex_file_types.h"
32 #include "dex/dex_instruction-inl.h"
33 #include "entrypoints/entrypoint_utils-inl.h"
34 #include "gc/verification-inl.h"
35 #include "lock_word-inl.h"
36 #include "mirror/class-inl.h"
37 #include "mirror/object-inl.h"
38 #include "monitor-inl.h"
39 #include "object_callbacks.h"
40 #include "scoped_thread_state_change-inl.h"
41 #include "stack.h"
42 #include "thread.h"
43 #include "thread_list.h"
44 #include "verifier/method_verifier.h"
45 #include "well_known_classes.h"
46
47 static_assert(ART_USE_FUTEXES);
48
49 namespace art HIDDEN {
50
51 using android::base::StringPrintf;
52
53 static constexpr uint64_t kDebugThresholdFudgeFactor = kIsDebugBuild ? 10 : 1;
54 static constexpr uint64_t kLongWaitMs = 100 * kDebugThresholdFudgeFactor;
55
56 /*
57 * Every Object has a monitor associated with it, but not every Object is actually locked. Even
58 * the ones that are locked do not need a full-fledged monitor until a) there is actual contention
59 * or b) wait() is called on the Object, or (c) we need to lock an object that also has an
60 * identity hashcode.
61 *
62 * For Android, we have implemented a scheme similar to the one described in Bacon et al.'s
63 * "Thin locks: featherweight synchronization for Java" (ACM 1998). Things are even easier for us,
64 * though, because we have a full 32 bits to work with.
65 *
66 * The two states of an Object's lock are referred to as "thin" and "fat". A lock may transition
67 * from the "thin" state to the "fat" state and this transition is referred to as inflation. We
68 * deflate locks from time to time as part of heap trimming.
69 *
70 * The lock value itself is stored in mirror::Object::monitor_ and the representation is described
71 * in the LockWord value type.
72 *
73 * Monitors provide:
74 * - mutually exclusive access to resources
75 * - a way for multiple threads to wait for notification
76 *
77 * In effect, they fill the role of both mutexes and condition variables.
78 *
79 * Only one thread can own the monitor at any time. There may be several threads waiting on it
80 * (the wait call unlocks it). One or more waiting threads may be getting interrupted or notified
81 * at any given time.
82 */
83
84 uint32_t Monitor::lock_profiling_threshold_ = 0;
85 uint32_t Monitor::stack_dump_lock_profiling_threshold_ = 0;
86
Init(uint32_t lock_profiling_threshold,uint32_t stack_dump_lock_profiling_threshold)87 void Monitor::Init(uint32_t lock_profiling_threshold,
88 uint32_t stack_dump_lock_profiling_threshold) {
89 // It isn't great to always include the debug build fudge factor for command-
90 // line driven arguments, but it's easier to adjust here than in the build.
91 lock_profiling_threshold_ =
92 lock_profiling_threshold * kDebugThresholdFudgeFactor;
93 stack_dump_lock_profiling_threshold_ =
94 stack_dump_lock_profiling_threshold * kDebugThresholdFudgeFactor;
95 }
96
Monitor(Thread * self,Thread * owner,ObjPtr<mirror::Object> obj,int32_t hash_code)97 Monitor::Monitor(Thread* self, Thread* owner, ObjPtr<mirror::Object> obj, int32_t hash_code)
98 : monitor_lock_("a monitor lock", kMonitorLock),
99 num_waiters_(0),
100 owner_(owner),
101 lock_count_(0),
102 obj_(GcRoot<mirror::Object>(obj)),
103 wait_set_(nullptr),
104 wake_set_(nullptr),
105 hash_code_(hash_code),
106 lock_owner_(nullptr),
107 lock_owner_method_(nullptr),
108 lock_owner_dex_pc_(0),
109 lock_owner_sum_(0),
110 lock_owner_request_(nullptr),
111 monitor_id_(MonitorPool::ComputeMonitorId(this, self)) {
112 #ifdef __LP64__
113 DCHECK(false) << "Should not be reached in 64b";
114 next_free_ = nullptr;
115 #endif
116 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
117 // with the owner unlocking the thin-lock.
118 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
119 // The identity hash code is set for the life time of the monitor.
120
121 bool monitor_timeout_enabled = Runtime::Current()->IsMonitorTimeoutEnabled();
122 if (monitor_timeout_enabled) {
123 MaybeEnableTimeout();
124 }
125 }
126
Monitor(Thread * self,Thread * owner,ObjPtr<mirror::Object> obj,int32_t hash_code,MonitorId id)127 Monitor::Monitor(Thread* self,
128 Thread* owner,
129 ObjPtr<mirror::Object> obj,
130 int32_t hash_code,
131 MonitorId id)
132 : monitor_lock_("a monitor lock", kMonitorLock),
133 num_waiters_(0),
134 owner_(owner),
135 lock_count_(0),
136 obj_(GcRoot<mirror::Object>(obj)),
137 wait_set_(nullptr),
138 wake_set_(nullptr),
139 hash_code_(hash_code),
140 lock_owner_(nullptr),
141 lock_owner_method_(nullptr),
142 lock_owner_dex_pc_(0),
143 lock_owner_sum_(0),
144 lock_owner_request_(nullptr),
145 monitor_id_(id) {
146 #ifdef __LP64__
147 next_free_ = nullptr;
148 #endif
149 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
150 // with the owner unlocking the thin-lock.
151 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
152 // The identity hash code is set for the life time of the monitor.
153
154 bool monitor_timeout_enabled = Runtime::Current()->IsMonitorTimeoutEnabled();
155 if (monitor_timeout_enabled) {
156 MaybeEnableTimeout();
157 }
158 }
159
GetHashCode()160 int32_t Monitor::GetHashCode() {
161 int32_t hc = hash_code_.load(std::memory_order_relaxed);
162 if (!HasHashCode()) {
163 // Use a strong CAS to prevent spurious failures since these can make the boot image
164 // non-deterministic.
165 hash_code_.CompareAndSetStrongRelaxed(0, mirror::Object::GenerateIdentityHashCode());
166 hc = hash_code_.load(std::memory_order_relaxed);
167 }
168 DCHECK(HasHashCode());
169 return hc;
170 }
171
SetLockingMethod(Thread * owner)172 void Monitor::SetLockingMethod(Thread* owner) {
173 DCHECK(owner == Thread::Current() || owner->IsSuspended());
174 // Do not abort on dex pc errors. This can easily happen when we want to dump a stack trace on
175 // abort.
176 ArtMethod* lock_owner_method;
177 uint32_t lock_owner_dex_pc;
178 lock_owner_method = owner->GetCurrentMethod(&lock_owner_dex_pc, false);
179 if (lock_owner_method != nullptr && UNLIKELY(lock_owner_method->IsProxyMethod())) {
180 // Grab another frame. Proxy methods are not helpful for lock profiling. This should be rare
181 // enough that it's OK to walk the stack twice.
182 struct NextMethodVisitor final : public StackVisitor {
183 explicit NextMethodVisitor(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_)
184 : StackVisitor(thread,
185 nullptr,
186 StackVisitor::StackWalkKind::kIncludeInlinedFrames,
187 false),
188 count_(0),
189 method_(nullptr),
190 dex_pc_(0) {}
191 bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
192 ArtMethod* m = GetMethod();
193 if (m->IsRuntimeMethod()) {
194 // Continue if this is a runtime method.
195 return true;
196 }
197 count_++;
198 if (count_ == 2u) {
199 method_ = m;
200 dex_pc_ = GetDexPc(false);
201 return false;
202 }
203 return true;
204 }
205 size_t count_;
206 ArtMethod* method_;
207 uint32_t dex_pc_;
208 };
209 NextMethodVisitor nmv(owner_.load(std::memory_order_relaxed));
210 nmv.WalkStack();
211 lock_owner_method = nmv.method_;
212 lock_owner_dex_pc = nmv.dex_pc_;
213 }
214 SetLockOwnerInfo(lock_owner_method, lock_owner_dex_pc, owner);
215 DCHECK(lock_owner_method == nullptr || !lock_owner_method->IsProxyMethod());
216 }
217
SetLockingMethodNoProxy(Thread * owner)218 void Monitor::SetLockingMethodNoProxy(Thread *owner) {
219 DCHECK(owner == Thread::Current());
220 uint32_t lock_owner_dex_pc;
221 ArtMethod* lock_owner_method = owner->GetCurrentMethod(&lock_owner_dex_pc);
222 // We don't expect a proxy method here.
223 DCHECK(lock_owner_method == nullptr || !lock_owner_method->IsProxyMethod());
224 SetLockOwnerInfo(lock_owner_method, lock_owner_dex_pc, owner);
225 }
226
Install(Thread * self)227 bool Monitor::Install(Thread* self) NO_THREAD_SAFETY_ANALYSIS {
228 // This may or may not result in acquiring monitor_lock_. Its behavior is much more complicated
229 // than what clang thread safety analysis understands.
230 // Monitor is not yet public.
231 Thread* owner = owner_.load(std::memory_order_relaxed);
232 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
233 // Propagate the lock state.
234 LockWord lw(GetObject()->GetLockWord(false));
235 switch (lw.GetState()) {
236 case LockWord::kThinLocked: {
237 DCHECK(owner != nullptr);
238 CHECK_EQ(owner->GetThreadId(), lw.ThinLockOwner());
239 DCHECK_EQ(monitor_lock_.GetExclusiveOwnerTid(), 0) << " my tid = " << SafeGetTid(self);
240 lock_count_ = lw.ThinLockCount();
241 monitor_lock_.ExclusiveLockUncontendedFor(owner);
242 DCHECK_EQ(monitor_lock_.GetExclusiveOwnerTid(), owner->GetTid())
243 << " my tid = " << SafeGetTid(self);
244 LockWord fat(this, lw.GCState());
245 // Publish the updated lock word, which may race with other threads.
246 bool success = GetObject()->CasLockWord(lw, fat, CASMode::kWeak, std::memory_order_release);
247 if (success) {
248 if (ATraceEnabled()) {
249 SetLockingMethod(owner);
250 }
251 return true;
252 } else {
253 monitor_lock_.ExclusiveUnlockUncontended();
254 return false;
255 }
256 }
257 case LockWord::kHashCode: {
258 CHECK_EQ(hash_code_.load(std::memory_order_relaxed), static_cast<int32_t>(lw.GetHashCode()));
259 DCHECK_EQ(monitor_lock_.GetExclusiveOwnerTid(), 0) << " my tid = " << SafeGetTid(self);
260 LockWord fat(this, lw.GCState());
261 return GetObject()->CasLockWord(lw, fat, CASMode::kWeak, std::memory_order_release);
262 }
263 case LockWord::kFatLocked: {
264 // The owner_ is suspended but another thread beat us to install a monitor.
265 return false;
266 }
267 case LockWord::kUnlocked: {
268 LOG(FATAL) << "Inflating unlocked lock word";
269 UNREACHABLE();
270 }
271 default: {
272 LOG(FATAL) << "Invalid monitor state " << lw.GetState();
273 UNREACHABLE();
274 }
275 }
276 }
277
~Monitor()278 Monitor::~Monitor() {
279 // Deflated monitors have a null object.
280 }
281
AppendToWaitSet(Thread * thread)282 void Monitor::AppendToWaitSet(Thread* thread) {
283 // Not checking that the owner is equal to this thread, since we've released
284 // the monitor by the time this method is called.
285 DCHECK(thread != nullptr);
286 DCHECK(thread->GetWaitNext() == nullptr) << thread->GetWaitNext();
287 if (wait_set_ == nullptr) {
288 wait_set_ = thread;
289 return;
290 }
291
292 // push_back.
293 Thread* t = wait_set_;
294 while (t->GetWaitNext() != nullptr) {
295 t = t->GetWaitNext();
296 }
297 t->SetWaitNext(thread);
298 }
299
RemoveFromWaitSet(Thread * thread)300 void Monitor::RemoveFromWaitSet(Thread *thread) {
301 DCHECK(owner_ == Thread::Current());
302 DCHECK(thread != nullptr);
303 auto remove = [&](Thread*& set){
304 if (set != nullptr) {
305 if (set == thread) {
306 set = thread->GetWaitNext();
307 thread->SetWaitNext(nullptr);
308 return true;
309 }
310 Thread* t = set;
311 while (t->GetWaitNext() != nullptr) {
312 if (t->GetWaitNext() == thread) {
313 t->SetWaitNext(thread->GetWaitNext());
314 thread->SetWaitNext(nullptr);
315 return true;
316 }
317 t = t->GetWaitNext();
318 }
319 }
320 return false;
321 };
322 if (remove(wait_set_)) {
323 return;
324 }
325 remove(wake_set_);
326 }
327
SetObject(ObjPtr<mirror::Object> object)328 void Monitor::SetObject(ObjPtr<mirror::Object> object) {
329 obj_ = GcRoot<mirror::Object>(object);
330 }
331
332 // This function is inlined and just helps to not have the VLOG and ATRACE check at all the
333 // potential tracing points.
AtraceMonitorLock(Thread * self,ObjPtr<mirror::Object> obj,bool is_wait)334 void Monitor::AtraceMonitorLock(Thread* self, ObjPtr<mirror::Object> obj, bool is_wait) {
335 if (UNLIKELY(VLOG_IS_ON(systrace_lock_logging) && ATraceEnabled())) {
336 AtraceMonitorLockImpl(self, obj, is_wait);
337 }
338 }
339
AtraceMonitorLockImpl(Thread * self,ObjPtr<mirror::Object> obj,bool is_wait)340 void Monitor::AtraceMonitorLockImpl(Thread* self, ObjPtr<mirror::Object> obj, bool is_wait) {
341 // Wait() requires a deeper call stack to be useful. Otherwise you'll see "Waiting at
342 // Object.java". Assume that we'll wait a nontrivial amount, so it's OK to do a longer
343 // stack walk than if !is_wait.
344 const size_t wanted_frame_number = is_wait ? 1U : 0U;
345
346 ArtMethod* method = nullptr;
347 uint32_t dex_pc = 0u;
348
349 size_t current_frame_number = 0u;
350 StackVisitor::WalkStack(
351 // Note: Adapted from CurrentMethodVisitor in thread.cc. We must not resolve here.
352 [&](const art::StackVisitor* stack_visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
353 ArtMethod* m = stack_visitor->GetMethod();
354 if (m == nullptr || m->IsRuntimeMethod()) {
355 // Runtime method, upcall, or resolution issue. Skip.
356 return true;
357 }
358
359 // Is this the requested frame?
360 if (current_frame_number == wanted_frame_number) {
361 method = m;
362 dex_pc = stack_visitor->GetDexPc(false /* abort_on_error*/);
363 return false;
364 }
365
366 // Look for more.
367 current_frame_number++;
368 return true;
369 },
370 self,
371 /* context= */ nullptr,
372 art::StackVisitor::StackWalkKind::kIncludeInlinedFrames);
373
374 const char* prefix = is_wait ? "Waiting on " : "Locking ";
375
376 const char* filename;
377 int32_t line_number;
378 TranslateLocation(method, dex_pc, &filename, &line_number);
379
380 // It would be nice to have a stable "ID" for the object here. However, the only stable thing
381 // would be the identity hashcode. But we cannot use IdentityHashcode here: For one, there are
382 // times when it is unsafe to make that call (see stack dumping for an explanation). More
383 // importantly, we would have to give up on thin-locking when adding systrace locks, as the
384 // identity hashcode is stored in the lockword normally (so can't be used with thin-locks).
385 //
386 // Because of thin-locks we also cannot use the monitor id (as there is no monitor). Monitor ids
387 // also do not have to be stable, as the monitor may be deflated.
388 std::string tmp = StringPrintf("%s %d at %s:%d",
389 prefix,
390 (obj == nullptr ? -1 : static_cast<int32_t>(reinterpret_cast<uintptr_t>(obj.Ptr()))),
391 (filename != nullptr ? filename : "null"),
392 line_number);
393 ATraceBegin(tmp.c_str());
394 }
395
AtraceMonitorUnlock()396 void Monitor::AtraceMonitorUnlock() {
397 if (UNLIKELY(VLOG_IS_ON(systrace_lock_logging))) {
398 ATraceEnd();
399 }
400 }
401
PrettyContentionInfo(const std::string & owner_name,pid_t owner_tid,ArtMethod * owners_method,uint32_t owners_dex_pc,size_t num_waiters)402 std::string Monitor::PrettyContentionInfo(const std::string& owner_name,
403 pid_t owner_tid,
404 ArtMethod* owners_method,
405 uint32_t owners_dex_pc,
406 size_t num_waiters) {
407 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
408 const char* owners_filename;
409 int32_t owners_line_number = 0;
410 if (owners_method != nullptr) {
411 TranslateLocation(owners_method, owners_dex_pc, &owners_filename, &owners_line_number);
412 }
413 std::ostringstream oss;
414 oss << "monitor contention with owner " << owner_name << " (" << owner_tid << ")";
415 if (owners_method != nullptr) {
416 oss << " at " << owners_method->PrettyMethod();
417 oss << "(" << owners_filename << ":" << owners_line_number << ")";
418 }
419 oss << " waiters=" << num_waiters;
420 return oss.str();
421 }
422
TryLock(Thread * self,bool spin)423 bool Monitor::TryLock(Thread* self, bool spin) {
424 Thread *owner = owner_.load(std::memory_order_relaxed);
425 if (owner == self) {
426 lock_count_++;
427 CHECK_NE(lock_count_, 0u); // Abort on overflow.
428 } else {
429 bool success = spin ? monitor_lock_.ExclusiveTryLockWithSpinning(self)
430 : monitor_lock_.ExclusiveTryLock(self);
431 if (!success) {
432 return false;
433 }
434 DCHECK(owner_.load(std::memory_order_relaxed) == nullptr);
435 owner_.store(self, std::memory_order_relaxed);
436 CHECK_EQ(lock_count_, 0u);
437 if (ATraceEnabled()) {
438 SetLockingMethodNoProxy(self);
439 }
440 }
441 DCHECK(monitor_lock_.IsExclusiveHeld(self));
442 AtraceMonitorLock(self, GetObject(), /* is_wait= */ false);
443 return true;
444 }
445
446 template <LockReason reason>
Lock(Thread * self)447 void Monitor::Lock(Thread* self) {
448 bool called_monitors_callback = false;
449 if (TryLock(self, /*spin=*/ true)) {
450 // TODO: This preserves original behavior. Correct?
451 if (called_monitors_callback) {
452 CHECK(reason == LockReason::kForLock);
453 Runtime::Current()->GetRuntimeCallbacks()->MonitorContendedLocked(this);
454 }
455 return;
456 }
457 // Contended; not reentrant. We hold no locks, so tread carefully.
458 const bool log_contention = (lock_profiling_threshold_ != 0);
459 uint64_t wait_start_ms = log_contention ? MilliTime() : 0;
460
461 Thread *orig_owner = nullptr;
462 ArtMethod* owners_method;
463 uint32_t owners_dex_pc;
464
465 // Do this before releasing the mutator lock so that we don't get deflated.
466 size_t num_waiters = num_waiters_.fetch_add(1, std::memory_order_relaxed);
467
468 bool started_trace = false;
469 if (ATraceEnabled() && owner_.load(std::memory_order_relaxed) != nullptr) {
470 // Acquiring thread_list_lock_ ensures that owner doesn't disappear while
471 // we're looking at it.
472 Locks::thread_list_lock_->ExclusiveLock(self);
473 orig_owner = owner_.load(std::memory_order_relaxed);
474 if (orig_owner != nullptr) { // Did the owner_ give the lock up?
475 const uint32_t orig_owner_thread_id = orig_owner->GetTid();
476 GetLockOwnerInfo(&owners_method, &owners_dex_pc, orig_owner);
477 std::ostringstream oss;
478 std::string name;
479 orig_owner->GetThreadName(name);
480 oss << PrettyContentionInfo(name,
481 orig_owner_thread_id,
482 owners_method,
483 owners_dex_pc,
484 num_waiters);
485 Locks::thread_list_lock_->ExclusiveUnlock(self);
486 // Add info for contending thread.
487 uint32_t pc;
488 ArtMethod* m = self->GetCurrentMethod(&pc);
489 const char* filename;
490 int32_t line_number;
491 TranslateLocation(m, pc, &filename, &line_number);
492 oss << " blocking from "
493 << ArtMethod::PrettyMethod(m) << "(" << (filename != nullptr ? filename : "null")
494 << ":" << line_number << ")";
495 ATraceBegin(oss.str().c_str());
496 started_trace = true;
497 } else {
498 Locks::thread_list_lock_->ExclusiveUnlock(self);
499 }
500 }
501 if (log_contention) {
502 // Request the current holder to set lock_owner_info.
503 // Do this even if tracing is enabled, so we semi-consistently get the information
504 // corresponding to MonitorExit.
505 // TODO: Consider optionally obtaining a stack trace here via a checkpoint. That would allow
506 // us to see what the other thread is doing while we're waiting.
507 orig_owner = owner_.load(std::memory_order_relaxed);
508 lock_owner_request_.store(orig_owner, std::memory_order_relaxed);
509 }
510 // Call the contended locking cb once and only once. Also only call it if we are locking for
511 // the first time, not during a Wait wakeup.
512 if (reason == LockReason::kForLock && !called_monitors_callback) {
513 called_monitors_callback = true;
514 Runtime::Current()->GetRuntimeCallbacks()->MonitorContendedLocking(this);
515 }
516 self->SetMonitorEnterObject(GetObject().Ptr());
517 {
518 // Change to blocked and give up mutator_lock_.
519 ScopedThreadSuspension tsc(self, ThreadState::kBlocked);
520
521 // Acquire monitor_lock_ without mutator_lock_, expecting to block this time.
522 // We already tried spinning above. The shutdown procedure currently assumes we stop
523 // touching monitors shortly after we suspend, so don't spin again here.
524 monitor_lock_.ExclusiveLock(self);
525
526 if (log_contention && orig_owner != nullptr) {
527 // Woken from contention.
528 uint64_t wait_ms = MilliTime() - wait_start_ms;
529 uint32_t sample_percent;
530 if (wait_ms >= lock_profiling_threshold_) {
531 sample_percent = 100;
532 } else {
533 sample_percent = 100 * wait_ms / lock_profiling_threshold_;
534 }
535 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
536 // Do this unconditionally for consistency. It's possible another thread
537 // snuck in in the middle, and tracing was enabled. In that case, we may get its
538 // MonitorEnter information. We can live with that.
539 GetLockOwnerInfo(&owners_method, &owners_dex_pc, orig_owner);
540
541 // Reacquire mutator_lock_ for logging.
542 ScopedObjectAccess soa(self);
543
544 const bool should_dump_stacks = stack_dump_lock_profiling_threshold_ > 0 &&
545 wait_ms > stack_dump_lock_profiling_threshold_;
546
547 // Acquire thread-list lock to find thread and keep it from dying until we've got all
548 // the info we need.
549 Locks::thread_list_lock_->ExclusiveLock(self);
550
551 // Is there still a thread at the same address as the original owner?
552 // We tolerate the fact that it may occasionally be the wrong one.
553 if (Runtime::Current()->GetThreadList()->Contains(orig_owner)) {
554 uint32_t original_owner_tid = orig_owner->GetTid(); // System thread id.
555 std::string original_owner_name;
556 orig_owner->GetThreadName(original_owner_name);
557 std::string owner_stack_dump;
558
559 if (should_dump_stacks) {
560 // Very long contention. Dump stacks.
561 struct CollectStackTrace : public Closure {
562 void Run(art::Thread* thread) override
563 REQUIRES_SHARED(art::Locks::mutator_lock_) {
564 thread->DumpJavaStack(oss);
565 }
566
567 std::ostringstream oss;
568 };
569 CollectStackTrace owner_trace;
570 // RequestSynchronousCheckpoint releases the thread_list_lock_ as a part of its
571 // execution.
572 orig_owner->RequestSynchronousCheckpoint(&owner_trace);
573 owner_stack_dump = owner_trace.oss.str();
574 } else {
575 Locks::thread_list_lock_->ExclusiveUnlock(self);
576 }
577
578 // This is all the data we need. We dropped the thread-list lock, it's OK for the
579 // owner to go away now.
580
581 if (should_dump_stacks) {
582 // Give the detailed traces for really long contention.
583 // This must be here (and not above) because we cannot hold the thread-list lock
584 // while running the checkpoint.
585 std::ostringstream self_trace_oss;
586 self->DumpJavaStack(self_trace_oss);
587
588 uint32_t pc;
589 ArtMethod* m = self->GetCurrentMethod(&pc);
590
591 LOG(WARNING) << "Long "
592 << PrettyContentionInfo(original_owner_name,
593 original_owner_tid,
594 owners_method,
595 owners_dex_pc,
596 num_waiters)
597 << " in " << ArtMethod::PrettyMethod(m) << " for "
598 << PrettyDuration(MsToNs(wait_ms)) << "\n"
599 << "Current owner stack:\n" << owner_stack_dump
600 << "Contender stack:\n" << self_trace_oss.str();
601 } else if (wait_ms > kLongWaitMs && owners_method != nullptr) {
602 uint32_t pc;
603 ArtMethod* m = self->GetCurrentMethod(&pc);
604 // TODO: We should maybe check that original_owner is still a live thread.
605 LOG(WARNING) << "Long "
606 << PrettyContentionInfo(original_owner_name,
607 original_owner_tid,
608 owners_method,
609 owners_dex_pc,
610 num_waiters)
611 << " in " << ArtMethod::PrettyMethod(m) << " for "
612 << PrettyDuration(MsToNs(wait_ms));
613 }
614 LogContentionEvent(self,
615 wait_ms,
616 sample_percent,
617 owners_method,
618 owners_dex_pc);
619 } else {
620 Locks::thread_list_lock_->ExclusiveUnlock(self);
621 }
622 }
623 }
624 }
625 // We've successfully acquired monitor_lock_, released thread_list_lock, and are runnable.
626
627 // We avoided touching monitor fields while suspended, so set owner_ here.
628 owner_.store(self, std::memory_order_relaxed);
629 DCHECK_EQ(lock_count_, 0u);
630
631 if (ATraceEnabled()) {
632 SetLockingMethodNoProxy(self);
633 }
634 if (started_trace) {
635 ATraceEnd();
636 }
637 self->SetMonitorEnterObject(nullptr);
638 num_waiters_.fetch_sub(1, std::memory_order_relaxed);
639 DCHECK(monitor_lock_.IsExclusiveHeld(self));
640 // We need to pair this with a single contended locking call. NB we match the RI behavior and call
641 // this even if MonitorEnter failed.
642 if (called_monitors_callback) {
643 CHECK(reason == LockReason::kForLock);
644 Runtime::Current()->GetRuntimeCallbacks()->MonitorContendedLocked(this);
645 }
646 }
647
648 template void Monitor::Lock<LockReason::kForLock>(Thread* self);
649 template void Monitor::Lock<LockReason::kForWait>(Thread* self);
650
651 static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
652 __attribute__((format(printf, 1, 2)));
653
ThrowIllegalMonitorStateExceptionF(const char * fmt,...)654 static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
655 REQUIRES_SHARED(Locks::mutator_lock_) {
656 va_list args;
657 va_start(args, fmt);
658 Thread* self = Thread::Current();
659 self->ThrowNewExceptionV("Ljava/lang/IllegalMonitorStateException;", fmt, args);
660 if (!Runtime::Current()->IsStarted() || VLOG_IS_ON(monitor)) {
661 std::ostringstream ss;
662 self->Dump(ss);
663 LOG(Runtime::Current()->IsStarted() ? ::android::base::INFO : ::android::base::ERROR)
664 << self->GetException()->Dump() << "\n" << ss.str();
665 }
666 va_end(args);
667 }
668
ThreadToString(Thread * thread)669 static std::string ThreadToString(Thread* thread) {
670 if (thread == nullptr) {
671 return "nullptr";
672 }
673 std::ostringstream oss;
674 // TODO: alternatively, we could just return the thread's name.
675 oss << *thread;
676 return oss.str();
677 }
678
FailedUnlock(ObjPtr<mirror::Object> o,uint32_t expected_owner_thread_id,uint32_t found_owner_thread_id,Monitor * monitor)679 void Monitor::FailedUnlock(ObjPtr<mirror::Object> o,
680 uint32_t expected_owner_thread_id,
681 uint32_t found_owner_thread_id,
682 Monitor* monitor) {
683 std::string current_owner_string;
684 std::string expected_owner_string;
685 std::string found_owner_string;
686 uint32_t current_owner_thread_id = 0u;
687 {
688 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
689 ThreadList* const thread_list = Runtime::Current()->GetThreadList();
690 Thread* expected_owner = thread_list->FindThreadByThreadId(expected_owner_thread_id);
691 Thread* found_owner = thread_list->FindThreadByThreadId(found_owner_thread_id);
692
693 // Re-read owner now that we hold lock.
694 Thread* current_owner = (monitor != nullptr) ? monitor->GetOwner() : nullptr;
695 if (current_owner != nullptr) {
696 current_owner_thread_id = current_owner->GetThreadId();
697 }
698 // Get short descriptions of the threads involved.
699 current_owner_string = ThreadToString(current_owner);
700 expected_owner_string = expected_owner != nullptr ? ThreadToString(expected_owner) : "unnamed";
701 found_owner_string = found_owner != nullptr ? ThreadToString(found_owner) : "unnamed";
702 }
703
704 if (current_owner_thread_id == 0u) {
705 if (found_owner_thread_id == 0u) {
706 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
707 " on thread '%s'",
708 mirror::Object::PrettyTypeOf(o).c_str(),
709 expected_owner_string.c_str());
710 } else {
711 // Race: the original read found an owner but now there is none
712 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
713 " (where now the monitor appears unowned) on thread '%s'",
714 found_owner_string.c_str(),
715 mirror::Object::PrettyTypeOf(o).c_str(),
716 expected_owner_string.c_str());
717 }
718 } else {
719 if (found_owner_thread_id == 0u) {
720 // Race: originally there was no owner, there is now
721 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
722 " (originally believed to be unowned) on thread '%s'",
723 current_owner_string.c_str(),
724 mirror::Object::PrettyTypeOf(o).c_str(),
725 expected_owner_string.c_str());
726 } else {
727 if (found_owner_thread_id != current_owner_thread_id) {
728 // Race: originally found and current owner have changed
729 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
730 " owned by '%s') on object of type '%s' on thread '%s'",
731 found_owner_string.c_str(),
732 current_owner_string.c_str(),
733 mirror::Object::PrettyTypeOf(o).c_str(),
734 expected_owner_string.c_str());
735 } else {
736 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
737 " on thread '%s",
738 current_owner_string.c_str(),
739 mirror::Object::PrettyTypeOf(o).c_str(),
740 expected_owner_string.c_str());
741 }
742 }
743 }
744 }
745
Unlock(Thread * self)746 bool Monitor::Unlock(Thread* self) {
747 DCHECK(self != nullptr);
748 Thread* owner = owner_.load(std::memory_order_relaxed);
749 if (owner == self) {
750 // We own the monitor, so nobody else can be in here.
751 CheckLockOwnerRequest(self);
752 AtraceMonitorUnlock();
753 if (lock_count_ == 0) {
754 owner_.store(nullptr, std::memory_order_relaxed);
755 SignalWaiterAndReleaseMonitorLock(self);
756 } else {
757 --lock_count_;
758 DCHECK(monitor_lock_.IsExclusiveHeld(self));
759 DCHECK_EQ(owner_.load(std::memory_order_relaxed), self);
760 // Keep monitor_lock_, but pretend we released it.
761 FakeUnlockMonitorLock();
762 }
763 return true;
764 }
765 // We don't own this, so we're not allowed to unlock it.
766 // The JNI spec says that we should throw IllegalMonitorStateException in this case.
767 uint32_t owner_thread_id = 0u;
768 {
769 MutexLock mu(self, *Locks::thread_list_lock_);
770 owner = owner_.load(std::memory_order_relaxed);
771 if (owner != nullptr) {
772 owner_thread_id = owner->GetThreadId();
773 }
774 }
775 FailedUnlock(GetObject(), self->GetThreadId(), owner_thread_id, this);
776 // Pretend to release monitor_lock_, which we should not.
777 FakeUnlockMonitorLock();
778 return false;
779 }
780
SignalWaiterAndReleaseMonitorLock(Thread * self)781 void Monitor::SignalWaiterAndReleaseMonitorLock(Thread* self) {
782 // We want to release the monitor and signal up to one thread that was waiting
783 // but has since been notified.
784 DCHECK_EQ(lock_count_, 0u);
785 DCHECK(monitor_lock_.IsExclusiveHeld(self));
786 while (wake_set_ != nullptr) {
787 // No risk of waking ourselves here; since monitor_lock_ is not released until we're ready to
788 // return, notify can't move the current thread from wait_set_ to wake_set_ until this
789 // method is done checking wake_set_.
790 Thread* thread = wake_set_;
791 wake_set_ = thread->GetWaitNext();
792 thread->SetWaitNext(nullptr);
793 DCHECK(owner_.load(std::memory_order_relaxed) == nullptr);
794
795 // Check to see if the thread is still waiting.
796 {
797 // In the case of wait(), we'll be acquiring another thread's GetWaitMutex with
798 // self's GetWaitMutex held. This does not risk deadlock, because we only acquire this lock
799 // for threads in the wake_set_. A thread can only enter wake_set_ from Notify or NotifyAll,
800 // and those hold monitor_lock_. Thus, the threads whose wait mutexes we acquire here must
801 // have already been released from wait(), since we have not released monitor_lock_ until
802 // after we've chosen our thread to wake, so there is no risk of the following lock ordering
803 // leading to deadlock:
804 // Thread 1 waits
805 // Thread 2 waits
806 // Thread 3 moves threads 1 and 2 from wait_set_ to wake_set_
807 // Thread 1 enters this block, and attempts to acquire Thread 2's GetWaitMutex to wake it
808 // Thread 2 enters this block, and attempts to acquire Thread 1's GetWaitMutex to wake it
809 //
810 // Since monitor_lock_ is not released until the thread-to-be-woken-up's GetWaitMutex is
811 // acquired, two threads cannot attempt to acquire each other's GetWaitMutex while holding
812 // their own and cause deadlock.
813 MutexLock wait_mu(self, *thread->GetWaitMutex());
814 if (thread->GetWaitMonitor() != nullptr) {
815 // Release the lock, so that a potentially awakened thread will not
816 // immediately contend on it. The lock ordering here is:
817 // monitor_lock_, self->GetWaitMutex, thread->GetWaitMutex
818 monitor_lock_.Unlock(self); // Releases contenders.
819 thread->GetWaitConditionVariable()->Signal(self);
820 return;
821 }
822 }
823 }
824 monitor_lock_.Unlock(self);
825 DCHECK(!monitor_lock_.IsExclusiveHeld(self));
826 }
827
Wait(Thread * self,int64_t ms,int32_t ns,bool interruptShouldThrow,ThreadState why)828 void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
829 bool interruptShouldThrow, ThreadState why) {
830 DCHECK(self != nullptr);
831 DCHECK(why == ThreadState::kTimedWaiting ||
832 why == ThreadState::kWaiting ||
833 why == ThreadState::kSleeping);
834
835 // Make sure that we hold the lock.
836 if (owner_.load(std::memory_order_relaxed) != self) {
837 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
838 return;
839 }
840
841 // We need to turn a zero-length timed wait into a regular wait because
842 // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
843 if (why == ThreadState::kTimedWaiting && (ms == 0 && ns == 0)) {
844 why = ThreadState::kWaiting;
845 }
846
847 // Enforce the timeout range.
848 if (ms < 0 || ns < 0 || ns > 999999) {
849 self->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
850 "timeout arguments out of range: ms=%" PRId64 " ns=%d", ms, ns);
851 return;
852 }
853
854 CheckLockOwnerRequest(self);
855
856 /*
857 * Release our hold - we need to let it go even if we're a few levels
858 * deep in a recursive lock, and we need to restore that later.
859 */
860 unsigned int prev_lock_count = lock_count_;
861 lock_count_ = 0;
862
863 AtraceMonitorUnlock(); // For the implict Unlock() just above. This will only end the deepest
864 // nesting, but that is enough for the visualization, and corresponds to
865 // the single Lock() we do afterwards.
866 AtraceMonitorLock(self, GetObject(), /* is_wait= */ true);
867
868 bool was_interrupted = false;
869 bool timed_out = false;
870 // Update monitor state now; it's not safe once we're "suspended".
871 owner_.store(nullptr, std::memory_order_relaxed);
872 num_waiters_.fetch_add(1, std::memory_order_relaxed);
873 {
874 // Update thread state. If the GC wakes up, it'll ignore us, knowing
875 // that we won't touch any references in this state, and we'll check
876 // our suspend mode before we transition out.
877 ScopedThreadSuspension sts(self, why);
878
879 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
880 MutexLock mu(self, *self->GetWaitMutex());
881
882 /*
883 * Add ourselves to the set of threads waiting on this monitor.
884 * It's important that we are only added to the wait set after
885 * acquiring our GetWaitMutex, so that calls to Notify() that occur after we
886 * have released monitor_lock_ will not move us from wait_set_ to wake_set_
887 * until we've signalled contenders on this monitor.
888 */
889 AppendToWaitSet(self);
890
891 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
892 // non-null a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
893 // up.
894 DCHECK(self->GetWaitMonitor() == nullptr);
895 self->SetWaitMonitor(this);
896
897 // Release the monitor lock.
898 DCHECK(monitor_lock_.IsExclusiveHeld(self));
899 SignalWaiterAndReleaseMonitorLock(self);
900
901 // Handle the case where the thread was interrupted before we called wait().
902 if (self->IsInterrupted()) {
903 was_interrupted = true;
904 } else {
905 // Wait for a notification or a timeout to occur.
906 if (why == ThreadState::kWaiting) {
907 self->GetWaitConditionVariable()->Wait(self);
908 } else {
909 DCHECK(why == ThreadState::kTimedWaiting || why == ThreadState::kSleeping) << why;
910 timed_out = self->GetWaitConditionVariable()->TimedWait(self, ms, ns);
911 }
912 was_interrupted = self->IsInterrupted();
913 }
914 }
915
916 {
917 // We reset the thread's wait_monitor_ field after transitioning back to runnable so
918 // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
919 // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
920 // are waiting on "null".)
921 MutexLock mu(self, *self->GetWaitMutex());
922 DCHECK(self->GetWaitMonitor() != nullptr);
923 self->SetWaitMonitor(nullptr);
924 }
925
926 // Allocate the interrupted exception not holding the monitor lock since it may cause a GC.
927 // If the GC requires acquiring the monitor for enqueuing cleared references, this would
928 // cause a deadlock if the monitor is held.
929 if (was_interrupted && interruptShouldThrow) {
930 /*
931 * We were interrupted while waiting, or somebody interrupted an
932 * un-interruptible thread earlier and we're bailing out immediately.
933 *
934 * The doc sayeth: "The interrupted status of the current thread is
935 * cleared when this exception is thrown."
936 */
937 self->SetInterrupted(false);
938 self->ThrowNewException("Ljava/lang/InterruptedException;", nullptr);
939 }
940
941 AtraceMonitorUnlock(); // End Wait().
942
943 // We just slept, tell the runtime callbacks about this.
944 Runtime::Current()->GetRuntimeCallbacks()->MonitorWaitFinished(this, timed_out);
945
946 // Re-acquire the monitor and lock.
947 Lock<LockReason::kForWait>(self);
948 lock_count_ = prev_lock_count;
949 DCHECK(monitor_lock_.IsExclusiveHeld(self));
950 self->GetWaitMutex()->AssertNotHeld(self);
951
952 num_waiters_.fetch_sub(1, std::memory_order_relaxed);
953 RemoveFromWaitSet(self);
954 }
955
Notify(Thread * self)956 void Monitor::Notify(Thread* self) {
957 DCHECK(self != nullptr);
958 // Make sure that we hold the lock.
959 if (owner_.load(std::memory_order_relaxed) != self) {
960 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
961 return;
962 }
963 // Move one thread from waiters to wake set
964 Thread* to_move = wait_set_;
965 if (to_move != nullptr) {
966 wait_set_ = to_move->GetWaitNext();
967 to_move->SetWaitNext(wake_set_);
968 wake_set_ = to_move;
969 }
970 }
971
NotifyAll(Thread * self)972 void Monitor::NotifyAll(Thread* self) {
973 DCHECK(self != nullptr);
974 // Make sure that we hold the lock.
975 if (owner_.load(std::memory_order_relaxed) != self) {
976 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
977 return;
978 }
979
980 // Move all threads from waiters to wake set
981 Thread* to_move = wait_set_;
982 if (to_move != nullptr) {
983 wait_set_ = nullptr;
984 Thread* move_to = wake_set_;
985 if (move_to == nullptr) {
986 wake_set_ = to_move;
987 return;
988 }
989 while (move_to->GetWaitNext() != nullptr) {
990 move_to = move_to->GetWaitNext();
991 }
992 move_to->SetWaitNext(to_move);
993 }
994 }
995
Deflate(Thread * self,ObjPtr<mirror::Object> obj)996 bool Monitor::Deflate(Thread* self, ObjPtr<mirror::Object> obj) {
997 // No other relevant code is running. We should hold mutator_lock_ exclusively, but
998 // ImageWriter cheats, since it's single-threaded.
999 DCHECK(obj != nullptr);
1000 // Don't need volatile since we only deflate with mutators suspended.
1001 LockWord lw(obj->GetLockWord(false));
1002 // If the lock isn't an inflated monitor, then we don't need to deflate anything.
1003 if (lw.GetState() == LockWord::kFatLocked) {
1004 Monitor* monitor = lw.FatLockMonitor();
1005 DCHECK(monitor != nullptr);
1006 // Can't deflate if we have anybody waiting on the CV or trying to acquire the monitor.
1007 if (monitor->num_waiters_.load(std::memory_order_relaxed) > 0) {
1008 return false;
1009 }
1010 if (!monitor->monitor_lock_.ExclusiveTryLock</* check= */ false>(self)) {
1011 // We cannot deflate a monitor that's currently held. It's unclear whether we should if
1012 // we could.
1013 return false;
1014 }
1015 DCHECK_EQ(monitor->lock_count_, 0u);
1016 DCHECK_EQ(monitor->owner_.load(std::memory_order_relaxed), static_cast<Thread*>(nullptr));
1017 if (monitor->HasHashCode()) {
1018 LockWord new_lw = LockWord::FromHashCode(monitor->GetHashCode(), lw.GCState());
1019 // Assume no concurrent read barrier state changes as mutators are suspended.
1020 obj->SetLockWord(new_lw, false);
1021 VLOG(monitor) << "Deflated " << obj << " to hash monitor " << monitor->GetHashCode();
1022 } else {
1023 // No lock and no hash, just put an empty lock word inside the object.
1024 LockWord new_lw = LockWord::FromDefault(lw.GCState());
1025 // Assume no concurrent read barrier state changes as mutators are suspended.
1026 obj->SetLockWord(new_lw, false);
1027 VLOG(monitor) << "Deflated" << obj << " to empty lock word";
1028 }
1029 monitor->monitor_lock_.ExclusiveUnlock(self);
1030 DCHECK(!(monitor->monitor_lock_.IsExclusiveHeld(self)));
1031 // The monitor is deflated, mark the object as null so that we know to delete it during the
1032 // next GC.
1033 monitor->obj_ = GcRoot<mirror::Object>(nullptr);
1034 }
1035 return true;
1036 }
1037
Inflate(Thread * self,Thread * owner,ObjPtr<mirror::Object> obj,int32_t hash_code)1038 void Monitor::Inflate(Thread* self, Thread* owner, ObjPtr<mirror::Object> obj, int32_t hash_code) {
1039 DCHECK(self != nullptr);
1040 DCHECK(obj != nullptr);
1041 // Allocate and acquire a new monitor.
1042 Monitor* m = MonitorPool::CreateMonitor(self, owner, obj, hash_code);
1043 DCHECK(m != nullptr);
1044 if (m->Install(self)) {
1045 if (owner != nullptr) {
1046 VLOG(monitor) << "monitor: thread" << owner->GetThreadId()
1047 << " created monitor " << m << " for object " << obj;
1048 } else {
1049 VLOG(monitor) << "monitor: Inflate with hashcode " << hash_code
1050 << " created monitor " << m << " for object " << obj;
1051 }
1052 Runtime::Current()->GetMonitorList()->Add(m);
1053 CHECK_EQ(obj->GetLockWord(true).GetState(), LockWord::kFatLocked);
1054 } else {
1055 MonitorPool::ReleaseMonitor(self, m);
1056 }
1057 }
1058
InflateThinLocked(Thread * self,Handle<mirror::Object> obj,LockWord lock_word,uint32_t hash_code,int attempt_of_4)1059 void Monitor::InflateThinLocked(Thread* self,
1060 Handle<mirror::Object> obj,
1061 LockWord lock_word,
1062 uint32_t hash_code,
1063 int attempt_of_4) {
1064 DCHECK_EQ(lock_word.GetState(), LockWord::kThinLocked);
1065 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1066 if (owner_thread_id == self->GetThreadId()) {
1067 // We own the monitor, we can easily inflate it.
1068 Inflate(self, self, obj.Get(), hash_code);
1069 } else {
1070 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1071 // Suspend the owner, inflate. First change to blocked and give up mutator_lock_.
1072 self->SetMonitorEnterObject(obj.Get());
1073 Thread* owner;
1074 {
1075 ScopedThreadSuspension sts(self, ThreadState::kWaitingForLockInflation);
1076 owner = thread_list->SuspendThreadByThreadId(
1077 owner_thread_id, SuspendReason::kInternal, attempt_of_4);
1078 }
1079 if (owner != nullptr) {
1080 // We succeeded in suspending the thread, check the lock's status didn't change.
1081 lock_word = obj->GetLockWord(true);
1082 if (lock_word.GetState() == LockWord::kThinLocked &&
1083 lock_word.ThinLockOwner() == owner_thread_id) {
1084 // Go ahead and inflate the lock.
1085 Inflate(self, owner, obj.Get(), hash_code);
1086 }
1087 bool resumed = thread_list->Resume(owner, SuspendReason::kInternal);
1088 DCHECK(resumed);
1089 }
1090 self->SetMonitorEnterObject(nullptr);
1091 }
1092 }
1093
1094 // Fool annotalysis into thinking that the lock on obj is acquired.
FakeLock(ObjPtr<mirror::Object> obj)1095 static ObjPtr<mirror::Object> FakeLock(ObjPtr<mirror::Object> obj)
1096 EXCLUSIVE_LOCK_FUNCTION(obj.Ptr()) NO_THREAD_SAFETY_ANALYSIS {
1097 return obj;
1098 }
1099
1100 // Fool annotalysis into thinking that the lock on obj is release.
FakeUnlock(ObjPtr<mirror::Object> obj)1101 static ObjPtr<mirror::Object> FakeUnlock(ObjPtr<mirror::Object> obj)
1102 UNLOCK_FUNCTION(obj.Ptr()) NO_THREAD_SAFETY_ANALYSIS {
1103 return obj;
1104 }
1105
MonitorEnter(Thread * self,ObjPtr<mirror::Object> obj,bool trylock)1106 ObjPtr<mirror::Object> Monitor::MonitorEnter(Thread* self,
1107 ObjPtr<mirror::Object> obj,
1108 bool trylock) {
1109 DCHECK(self != nullptr);
1110 DCHECK(obj != nullptr);
1111 self->AssertThreadSuspensionIsAllowable();
1112 obj = FakeLock(obj);
1113 uint32_t thread_id = self->GetThreadId();
1114 size_t contention_count = 0;
1115 constexpr size_t kExtraSpinIters = 100;
1116 int inflation_attempt = 1;
1117 StackHandleScope<1> hs(self);
1118 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
1119 while (true) {
1120 // We initially read the lockword with ordinary Java/relaxed semantics. When stronger
1121 // semantics are needed, we address it below. Since GetLockWord bottoms out to a relaxed load,
1122 // we can fix it later, in an infrequently executed case, with a fence.
1123 LockWord lock_word = h_obj->GetLockWord(false);
1124 switch (lock_word.GetState()) {
1125 case LockWord::kUnlocked: {
1126 // No ordering required for preceding lockword read, since we retest.
1127 LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0, lock_word.GCState()));
1128 if (h_obj->CasLockWord(lock_word, thin_locked, CASMode::kWeak, std::memory_order_acquire)) {
1129 AtraceMonitorLock(self, h_obj.Get(), /* is_wait= */ false);
1130 return h_obj.Get(); // Success!
1131 }
1132 continue; // Go again.
1133 }
1134 case LockWord::kThinLocked: {
1135 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1136 if (owner_thread_id == thread_id) {
1137 // No ordering required for initial lockword read.
1138 // We own the lock, increase the recursion count.
1139 uint32_t new_count = lock_word.ThinLockCount() + 1;
1140 if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
1141 LockWord thin_locked(LockWord::FromThinLockId(thread_id,
1142 new_count,
1143 lock_word.GCState()));
1144 // Only this thread pays attention to the count. Thus there is no need for stronger
1145 // than relaxed memory ordering.
1146 if (!gUseReadBarrier) {
1147 h_obj->SetLockWord(thin_locked, /* as_volatile= */ false);
1148 AtraceMonitorLock(self, h_obj.Get(), /* is_wait= */ false);
1149 return h_obj.Get(); // Success!
1150 } else {
1151 // Use CAS to preserve the read barrier state.
1152 if (h_obj->CasLockWord(lock_word,
1153 thin_locked,
1154 CASMode::kWeak,
1155 std::memory_order_relaxed)) {
1156 AtraceMonitorLock(self, h_obj.Get(), /* is_wait= */ false);
1157 return h_obj.Get(); // Success!
1158 }
1159 }
1160 continue; // Go again.
1161 } else {
1162 // We'd overflow the recursion count, so inflate the monitor.
1163 InflateThinLocked(self, h_obj, lock_word, 0, inflation_attempt++);
1164 }
1165 } else {
1166 if (trylock) {
1167 return nullptr;
1168 }
1169 // Contention.
1170 contention_count++;
1171 Runtime* runtime = Runtime::Current();
1172 if (contention_count
1173 <= kExtraSpinIters + runtime->GetMaxSpinsBeforeThinLockInflation()) {
1174 // TODO: Consider switching the thread state to kWaitingForLockInflation when we are
1175 // yielding. Use sched_yield instead of NanoSleep since NanoSleep can wait much longer
1176 // than the parameter you pass in. This can cause thread suspension to take excessively
1177 // long and make long pauses. See b/16307460.
1178 if (contention_count > kExtraSpinIters) {
1179 sched_yield();
1180 }
1181 } else {
1182 contention_count = 0;
1183 // No ordering required for initial lockword read. Install rereads it anyway.
1184 InflateThinLocked(self, h_obj, lock_word, 0, inflation_attempt++);
1185 }
1186 }
1187 continue; // Start from the beginning.
1188 }
1189 case LockWord::kFatLocked: {
1190 // We should have done an acquire read of the lockword initially, to ensure
1191 // visibility of the monitor data structure. Use an explicit fence instead.
1192 std::atomic_thread_fence(std::memory_order_acquire);
1193 Monitor* mon = lock_word.FatLockMonitor();
1194 if (trylock) {
1195 return mon->TryLock(self) ? h_obj.Get() : nullptr;
1196 } else {
1197 mon->Lock(self);
1198 DCHECK(mon->monitor_lock_.IsExclusiveHeld(self));
1199 return h_obj.Get(); // Success!
1200 }
1201 }
1202 case LockWord::kHashCode:
1203 // Inflate with the existing hashcode.
1204 // Again no ordering required for initial lockword read, since we don't rely
1205 // on the visibility of any prior computation.
1206 Inflate(self, nullptr, h_obj.Get(), lock_word.GetHashCode());
1207 continue; // Start from the beginning.
1208 default: {
1209 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1210 UNREACHABLE();
1211 }
1212 }
1213 }
1214 }
1215
MonitorExit(Thread * self,ObjPtr<mirror::Object> obj)1216 bool Monitor::MonitorExit(Thread* self, ObjPtr<mirror::Object> obj) {
1217 DCHECK(self != nullptr);
1218 DCHECK(obj != nullptr);
1219 self->AssertThreadSuspensionIsAllowable();
1220 obj = FakeUnlock(obj);
1221 StackHandleScope<1> hs(self);
1222 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
1223 while (true) {
1224 LockWord lock_word = obj->GetLockWord(true);
1225 switch (lock_word.GetState()) {
1226 case LockWord::kHashCode:
1227 // Fall-through.
1228 case LockWord::kUnlocked:
1229 FailedUnlock(h_obj.Get(), self->GetThreadId(), 0u, nullptr);
1230 return false; // Failure.
1231 case LockWord::kThinLocked: {
1232 uint32_t thread_id = self->GetThreadId();
1233 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1234 if (owner_thread_id != thread_id) {
1235 FailedUnlock(h_obj.Get(), thread_id, owner_thread_id, nullptr);
1236 return false; // Failure.
1237 } else {
1238 // We own the lock, decrease the recursion count.
1239 LockWord new_lw = LockWord::Default();
1240 if (lock_word.ThinLockCount() != 0) {
1241 uint32_t new_count = lock_word.ThinLockCount() - 1;
1242 new_lw = LockWord::FromThinLockId(thread_id, new_count, lock_word.GCState());
1243 } else {
1244 new_lw = LockWord::FromDefault(lock_word.GCState());
1245 }
1246 if (!gUseReadBarrier) {
1247 DCHECK_EQ(new_lw.ReadBarrierState(), 0U);
1248 // TODO: This really only needs memory_order_release, but we currently have
1249 // no way to specify that. In fact there seem to be no legitimate uses of SetLockWord
1250 // with a final argument of true. This slows down x86 and ARMv7, but probably not v8.
1251 h_obj->SetLockWord(new_lw, true);
1252 AtraceMonitorUnlock();
1253 // Success!
1254 return true;
1255 } else {
1256 // Use CAS to preserve the read barrier state.
1257 if (h_obj->CasLockWord(lock_word, new_lw, CASMode::kWeak, std::memory_order_release)) {
1258 AtraceMonitorUnlock();
1259 // Success!
1260 return true;
1261 }
1262 }
1263 continue; // Go again.
1264 }
1265 }
1266 case LockWord::kFatLocked: {
1267 Monitor* mon = lock_word.FatLockMonitor();
1268 return mon->Unlock(self);
1269 }
1270 default: {
1271 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1272 UNREACHABLE();
1273 }
1274 }
1275 }
1276 }
1277
Wait(Thread * self,ObjPtr<mirror::Object> obj,int64_t ms,int32_t ns,bool interruptShouldThrow,ThreadState why)1278 void Monitor::Wait(Thread* self,
1279 ObjPtr<mirror::Object> obj,
1280 int64_t ms,
1281 int32_t ns,
1282 bool interruptShouldThrow,
1283 ThreadState why) {
1284 DCHECK(self != nullptr);
1285 DCHECK(obj != nullptr);
1286 StackHandleScope<1> hs(self);
1287 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
1288
1289 Runtime::Current()->GetRuntimeCallbacks()->ObjectWaitStart(h_obj, ms);
1290 if (UNLIKELY(self->ObserveAsyncException() || self->IsExceptionPending())) {
1291 // See b/65558434 for information on handling of exceptions here.
1292 return;
1293 }
1294
1295 LockWord lock_word = h_obj->GetLockWord(true);
1296 while (lock_word.GetState() != LockWord::kFatLocked) {
1297 switch (lock_word.GetState()) {
1298 case LockWord::kHashCode:
1299 // Fall-through.
1300 case LockWord::kUnlocked:
1301 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
1302 return; // Failure.
1303 case LockWord::kThinLocked: {
1304 uint32_t thread_id = self->GetThreadId();
1305 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1306 if (owner_thread_id != thread_id) {
1307 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
1308 return; // Failure.
1309 } else {
1310 // We own the lock, inflate to enqueue ourself on the Monitor. May fail spuriously so
1311 // re-load.
1312 Inflate(self, self, h_obj.Get(), 0);
1313 lock_word = h_obj->GetLockWord(true);
1314 }
1315 break;
1316 }
1317 case LockWord::kFatLocked: // Unreachable given the loop condition above. Fall-through.
1318 default: {
1319 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1320 UNREACHABLE();
1321 }
1322 }
1323 }
1324 Monitor* mon = lock_word.FatLockMonitor();
1325 mon->Wait(self, ms, ns, interruptShouldThrow, why);
1326 }
1327
DoNotify(Thread * self,ObjPtr<mirror::Object> obj,bool notify_all)1328 void Monitor::DoNotify(Thread* self, ObjPtr<mirror::Object> obj, bool notify_all) {
1329 DCHECK(self != nullptr);
1330 DCHECK(obj != nullptr);
1331 LockWord lock_word = obj->GetLockWord(true);
1332 switch (lock_word.GetState()) {
1333 case LockWord::kHashCode:
1334 // Fall-through.
1335 case LockWord::kUnlocked:
1336 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
1337 return; // Failure.
1338 case LockWord::kThinLocked: {
1339 uint32_t thread_id = self->GetThreadId();
1340 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1341 if (owner_thread_id != thread_id) {
1342 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
1343 return; // Failure.
1344 } else {
1345 // We own the lock but there's no Monitor and therefore no waiters.
1346 return; // Success.
1347 }
1348 }
1349 case LockWord::kFatLocked: {
1350 Monitor* mon = lock_word.FatLockMonitor();
1351 if (notify_all) {
1352 mon->NotifyAll(self);
1353 } else {
1354 mon->Notify(self);
1355 }
1356 return; // Success.
1357 }
1358 default: {
1359 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1360 UNREACHABLE();
1361 }
1362 }
1363 }
1364
GetLockOwnerThreadId(ObjPtr<mirror::Object> obj)1365 uint32_t Monitor::GetLockOwnerThreadId(ObjPtr<mirror::Object> obj) {
1366 DCHECK(obj != nullptr);
1367 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1368 LockWord lock_word = obj->GetLockWord(true);
1369 switch (lock_word.GetState()) {
1370 case LockWord::kHashCode:
1371 // Fall-through.
1372 case LockWord::kUnlocked:
1373 return ThreadList::kInvalidThreadId;
1374 case LockWord::kThinLocked:
1375 return lock_word.ThinLockOwner();
1376 case LockWord::kFatLocked: {
1377 Monitor* mon = lock_word.FatLockMonitor();
1378 // Since we hold a share of the mutator lock, the obj lock cannot be deflated here.
1379 // Since our caller holds a reference to obj, mon cannot be reclaimed.
1380 return mon->GetOwnerThreadId();
1381 }
1382 default: {
1383 LOG(FATAL) << "Unreachable";
1384 UNREACHABLE();
1385 }
1386 }
1387 }
1388
FetchState(const Thread * thread,ObjPtr<mirror::Object> * monitor_object,uint32_t * lock_owner_tid)1389 ThreadState Monitor::FetchState(const Thread* thread,
1390 /* out */ ObjPtr<mirror::Object>* monitor_object,
1391 /* out */ uint32_t* lock_owner_tid) {
1392 DCHECK(monitor_object != nullptr);
1393 DCHECK(lock_owner_tid != nullptr);
1394
1395 *monitor_object = nullptr;
1396 *lock_owner_tid = ThreadList::kInvalidThreadId;
1397
1398 ThreadState state = thread->GetState();
1399
1400 switch (state) {
1401 case ThreadState::kWaiting:
1402 case ThreadState::kTimedWaiting:
1403 case ThreadState::kSleeping:
1404 {
1405 Thread* self = Thread::Current();
1406 MutexLock mu(self, *thread->GetWaitMutex());
1407 Monitor* monitor = thread->GetWaitMonitor();
1408 if (monitor != nullptr) {
1409 *monitor_object = monitor->GetObject();
1410 }
1411 }
1412 break;
1413
1414 case ThreadState::kBlocked:
1415 case ThreadState::kWaitingForLockInflation:
1416 {
1417 ObjPtr<mirror::Object> lock_object = thread->GetMonitorEnterObject();
1418 if (lock_object != nullptr) {
1419 if (gUseReadBarrier && Thread::Current()->GetIsGcMarking()) {
1420 // We may call Thread::Dump() in the middle of the CC thread flip and this thread's stack
1421 // may have not been flipped yet and "pretty_object" may be a from-space (stale) ref, in
1422 // which case the GetLockOwnerThreadId() call below will crash. So explicitly mark/forward
1423 // it here.
1424 lock_object = ReadBarrier::Mark(lock_object.Ptr());
1425 }
1426 *monitor_object = lock_object;
1427 *lock_owner_tid = lock_object->GetLockOwnerThreadId();
1428 }
1429 }
1430 break;
1431
1432 default:
1433 break;
1434 }
1435
1436 return state;
1437 }
1438
GetContendedMonitor(Thread * thread)1439 ObjPtr<mirror::Object> Monitor::GetContendedMonitor(Thread* thread) {
1440 // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
1441 // definition of contended that includes a monitor a thread is trying to enter...
1442 ObjPtr<mirror::Object> result = thread->GetMonitorEnterObject();
1443 if (result == nullptr) {
1444 // ...but also a monitor that the thread is waiting on.
1445 MutexLock mu(Thread::Current(), *thread->GetWaitMutex());
1446 Monitor* monitor = thread->GetWaitMonitor();
1447 if (monitor != nullptr) {
1448 result = monitor->GetObject();
1449 }
1450 }
1451 return result;
1452 }
1453
VisitLocks(StackVisitor * stack_visitor,void (* callback)(ObjPtr<mirror::Object>,void *),void * callback_context,bool abort_on_failure)1454 void Monitor::VisitLocks(StackVisitor* stack_visitor,
1455 void (*callback)(ObjPtr<mirror::Object>, void*),
1456 void* callback_context,
1457 bool abort_on_failure) {
1458 ArtMethod* m = stack_visitor->GetMethod();
1459 CHECK(m != nullptr);
1460
1461 // Native methods are an easy special case.
1462 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
1463 if (m->IsNative()) {
1464 if (m->IsSynchronized()) {
1465 DCHECK(!m->IsCriticalNative());
1466 DCHECK(!m->IsFastNative());
1467 ObjPtr<mirror::Object> lock;
1468 if (m->IsStatic()) {
1469 // Static methods synchronize on the declaring class object.
1470 lock = m->GetDeclaringClass();
1471 } else {
1472 // Instance methods synchronize on the `this` object.
1473 // The `this` reference is stored in the first out vreg in the caller's frame.
1474 uint8_t* sp = reinterpret_cast<uint8_t*>(stack_visitor->GetCurrentQuickFrame());
1475 size_t frame_size = stack_visitor->GetCurrentQuickFrameInfo().FrameSizeInBytes();
1476 lock = reinterpret_cast<StackReference<mirror::Object>*>(
1477 sp + frame_size + static_cast<size_t>(kRuntimePointerSize))->AsMirrorPtr();
1478 }
1479 callback(lock, callback_context);
1480 }
1481 return;
1482 }
1483
1484 // Proxy methods should not be synchronized.
1485 if (m->IsProxyMethod()) {
1486 CHECK(!m->IsSynchronized());
1487 return;
1488 }
1489
1490 // Is there any reason to believe there's any synchronization in this method?
1491 CHECK(m->GetCodeItem() != nullptr) << m->PrettyMethod();
1492 CodeItemDataAccessor accessor(m->DexInstructionData());
1493 if (accessor.TriesSize() == 0) {
1494 return; // No "tries" implies no synchronization, so no held locks to report.
1495 }
1496
1497 // Get the dex pc. If abort_on_failure is false, GetDexPc will not abort in the case it cannot
1498 // find the dex pc, and instead return kDexNoIndex. Then bail out, as it indicates we have an
1499 // inconsistent stack anyways.
1500 uint32_t dex_pc = stack_visitor->GetDexPc(abort_on_failure);
1501 if (!abort_on_failure && dex_pc == dex::kDexNoIndex) {
1502 LOG(ERROR) << "Could not find dex_pc for " << m->PrettyMethod();
1503 return;
1504 }
1505
1506 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
1507 // the locks held in this stack frame.
1508 std::vector<verifier::MethodVerifier::DexLockInfo> monitor_enter_dex_pcs;
1509 verifier::MethodVerifier::FindLocksAtDexPc(m,
1510 dex_pc,
1511 &monitor_enter_dex_pcs,
1512 Runtime::Current()->GetTargetSdkVersion());
1513 for (verifier::MethodVerifier::DexLockInfo& dex_lock_info : monitor_enter_dex_pcs) {
1514 // As a debug check, check that dex PC corresponds to a monitor-enter.
1515 if (kIsDebugBuild) {
1516 const Instruction& monitor_enter_instruction = accessor.InstructionAt(dex_lock_info.dex_pc);
1517 CHECK_EQ(monitor_enter_instruction.Opcode(), Instruction::MONITOR_ENTER)
1518 << "expected monitor-enter @" << dex_lock_info.dex_pc << "; was "
1519 << reinterpret_cast<const void*>(&monitor_enter_instruction);
1520 }
1521
1522 // Iterate through the set of dex registers, as the compiler may not have held all of them
1523 // live.
1524 bool success = false;
1525 for (uint32_t dex_reg : dex_lock_info.dex_registers) {
1526 uint32_t value;
1527
1528 // For optimized code we expect the DexRegisterMap to be present - monitor information
1529 // not be optimized out.
1530 success = stack_visitor->GetVReg(m, dex_reg, kReferenceVReg, &value);
1531 if (success) {
1532 mirror::Object* mp = reinterpret_cast<mirror::Object*>(value);
1533 // TODO(b/299577730) Remove the extra checks here once the underlying bug is fixed.
1534 const gc::Verification* v = Runtime::Current()->GetHeap()->GetVerification();
1535 if (v->IsValidObject(mp)) {
1536 ObjPtr<mirror::Object> o = mp;
1537 callback(o, callback_context);
1538 break;
1539 } else {
1540 LOG(ERROR) << "Encountered bad lock object: " << std::hex << value << std::dec;
1541 success = false;
1542 }
1543 }
1544 }
1545 if (!success) {
1546 LOG(ERROR) << "Failed to find/read reference for monitor-enter at dex pc "
1547 << dex_lock_info.dex_pc << " in method " << m->PrettyMethod();
1548 if (kIsDebugBuild) {
1549 // Crash only in debug ART builds.
1550 LOG(FATAL) << "Had a lock reported for a dex pc "
1551 "but was not able to fetch a corresponding object!";
1552 } else {
1553 LOG(ERROR) << "Held monitor information in stack trace will be incomplete!";
1554 }
1555 }
1556 }
1557 }
1558
IsValidLockWord(LockWord lock_word)1559 bool Monitor::IsValidLockWord(LockWord lock_word) {
1560 switch (lock_word.GetState()) {
1561 case LockWord::kUnlocked:
1562 // Nothing to check.
1563 return true;
1564 case LockWord::kThinLocked:
1565 // Basic consistency check of owner.
1566 return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
1567 case LockWord::kFatLocked: {
1568 // Check the monitor appears in the monitor list.
1569 Monitor* mon = lock_word.FatLockMonitor();
1570 MonitorList* list = Runtime::Current()->GetMonitorList();
1571 MutexLock mu(Thread::Current(), list->monitor_list_lock_);
1572 for (Monitor* list_mon : list->list_) {
1573 if (mon == list_mon) {
1574 return true; // Found our monitor.
1575 }
1576 }
1577 return false; // Fail - unowned monitor in an object.
1578 }
1579 case LockWord::kHashCode:
1580 return true;
1581 default:
1582 LOG(FATAL) << "Unreachable";
1583 UNREACHABLE();
1584 }
1585 }
1586
IsLocked()1587 bool Monitor::IsLocked() REQUIRES_SHARED(Locks::mutator_lock_) {
1588 return GetOwner() != nullptr;
1589 }
1590
TranslateLocation(ArtMethod * method,uint32_t dex_pc,const char ** source_file,int32_t * line_number)1591 void Monitor::TranslateLocation(ArtMethod* method,
1592 uint32_t dex_pc,
1593 const char** source_file,
1594 int32_t* line_number) {
1595 // If method is null, location is unknown
1596 if (method == nullptr) {
1597 *source_file = "";
1598 *line_number = 0;
1599 return;
1600 }
1601 *source_file = method->GetDeclaringClassSourceFile();
1602 if (*source_file == nullptr) {
1603 *source_file = "";
1604 }
1605 *line_number = method->GetLineNumFromDexPC(dex_pc);
1606 }
1607
GetOwnerThreadId()1608 uint32_t Monitor::GetOwnerThreadId() {
1609 // Make sure owner is not deallocated during access.
1610 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
1611 Thread* owner = GetOwner();
1612 if (owner != nullptr) {
1613 return owner->GetThreadId();
1614 } else {
1615 return ThreadList::kInvalidThreadId;
1616 }
1617 }
1618
MonitorList()1619 MonitorList::MonitorList()
1620 : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock", kMonitorListLock),
1621 monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
1622 }
1623
~MonitorList()1624 MonitorList::~MonitorList() {
1625 Thread* self = Thread::Current();
1626 MutexLock mu(self, monitor_list_lock_);
1627 // Release all monitors to the pool.
1628 // TODO: Is it an invariant that *all* open monitors are in the list? Then we could
1629 // clear faster in the pool.
1630 MonitorPool::ReleaseMonitors(self, &list_);
1631 }
1632
DisallowNewMonitors()1633 void MonitorList::DisallowNewMonitors() {
1634 CHECK(!gUseReadBarrier);
1635 MutexLock mu(Thread::Current(), monitor_list_lock_);
1636 allow_new_monitors_ = false;
1637 }
1638
AllowNewMonitors()1639 void MonitorList::AllowNewMonitors() {
1640 CHECK(!gUseReadBarrier);
1641 Thread* self = Thread::Current();
1642 MutexLock mu(self, monitor_list_lock_);
1643 allow_new_monitors_ = true;
1644 monitor_add_condition_.Broadcast(self);
1645 }
1646
BroadcastForNewMonitors()1647 void MonitorList::BroadcastForNewMonitors() {
1648 Thread* self = Thread::Current();
1649 MutexLock mu(self, monitor_list_lock_);
1650 monitor_add_condition_.Broadcast(self);
1651 }
1652
Add(Monitor * m)1653 void MonitorList::Add(Monitor* m) {
1654 Thread* self = Thread::Current();
1655 MutexLock mu(self, monitor_list_lock_);
1656 // CMS needs this to block for concurrent reference processing because an object allocated during
1657 // the GC won't be marked and concurrent reference processing would incorrectly clear the JNI weak
1658 // ref. But CC (gUseReadBarrier == true) doesn't because of the to-space invariant.
1659 while (!gUseReadBarrier && UNLIKELY(!allow_new_monitors_)) {
1660 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
1661 // presence of threads blocking for weak ref access.
1662 self->CheckEmptyCheckpointFromWeakRefAccess(&monitor_list_lock_);
1663 monitor_add_condition_.WaitHoldingLocks(self);
1664 }
1665 list_.push_front(m);
1666 }
1667
SweepMonitorList(IsMarkedVisitor * visitor)1668 void MonitorList::SweepMonitorList(IsMarkedVisitor* visitor) {
1669 Thread* self = Thread::Current();
1670 MutexLock mu(self, monitor_list_lock_);
1671 for (auto it = list_.begin(); it != list_.end(); ) {
1672 Monitor* m = *it;
1673 // Disable the read barrier in GetObject() as this is called by GC.
1674 ObjPtr<mirror::Object> obj = m->GetObject<kWithoutReadBarrier>();
1675 // The object of a monitor can be null if we have deflated it.
1676 ObjPtr<mirror::Object> new_obj = obj != nullptr ? visitor->IsMarked(obj.Ptr()) : nullptr;
1677 if (new_obj == nullptr) {
1678 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
1679 << obj;
1680 MonitorPool::ReleaseMonitor(self, m);
1681 it = list_.erase(it);
1682 } else {
1683 m->SetObject(new_obj);
1684 ++it;
1685 }
1686 }
1687 }
1688
Size()1689 size_t MonitorList::Size() {
1690 Thread* self = Thread::Current();
1691 MutexLock mu(self, monitor_list_lock_);
1692 return list_.size();
1693 }
1694
1695 class MonitorDeflateVisitor : public IsMarkedVisitor {
1696 public:
MonitorDeflateVisitor()1697 MonitorDeflateVisitor() : self_(Thread::Current()), deflate_count_(0) {}
1698
IsMarked(mirror::Object * object)1699 mirror::Object* IsMarked(mirror::Object* object) override REQUIRES(Locks::mutator_lock_) {
1700 if (Monitor::Deflate(self_, object)) {
1701 DCHECK_NE(object->GetLockWord(true).GetState(), LockWord::kFatLocked);
1702 ++deflate_count_;
1703 // If we deflated, return null so that the monitor gets removed from the array.
1704 return nullptr;
1705 }
1706 return object; // Monitor was not deflated.
1707 }
1708
1709 Thread* const self_;
1710 size_t deflate_count_;
1711 };
1712
DeflateMonitors()1713 size_t MonitorList::DeflateMonitors() {
1714 MonitorDeflateVisitor visitor;
1715 Locks::mutator_lock_->AssertExclusiveHeld(visitor.self_);
1716 SweepMonitorList(&visitor);
1717 return visitor.deflate_count_;
1718 }
1719
MonitorInfo(ObjPtr<mirror::Object> obj)1720 MonitorInfo::MonitorInfo(ObjPtr<mirror::Object> obj) : owner_(nullptr), entry_count_(0) {
1721 DCHECK(obj != nullptr);
1722 LockWord lock_word = obj->GetLockWord(true);
1723 switch (lock_word.GetState()) {
1724 case LockWord::kUnlocked:
1725 // Fall-through.
1726 case LockWord::kForwardingAddress:
1727 // Fall-through.
1728 case LockWord::kHashCode:
1729 break;
1730 case LockWord::kThinLocked:
1731 owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
1732 DCHECK(owner_ != nullptr) << "Thin-locked without owner!";
1733 entry_count_ = 1 + lock_word.ThinLockCount();
1734 // Thin locks have no waiters.
1735 break;
1736 case LockWord::kFatLocked: {
1737 Monitor* mon = lock_word.FatLockMonitor();
1738 owner_ = mon->owner_.load(std::memory_order_relaxed);
1739 // Here it is okay for the owner to be null since we don't reset the LockWord back to
1740 // kUnlocked until we get a GC. In cases where this hasn't happened yet we will have a fat
1741 // lock without an owner.
1742 // Neither owner_ nor entry_count_ is touched by threads in "suspended" state, so
1743 // we must see consistent values.
1744 if (owner_ != nullptr) {
1745 entry_count_ = 1 + mon->lock_count_;
1746 } else {
1747 DCHECK_EQ(mon->lock_count_, 0u) << "Monitor is fat-locked without any owner!";
1748 }
1749 for (Thread* waiter = mon->wait_set_; waiter != nullptr; waiter = waiter->GetWaitNext()) {
1750 waiters_.push_back(waiter);
1751 }
1752 break;
1753 }
1754 }
1755 }
1756
MaybeEnableTimeout()1757 void Monitor::MaybeEnableTimeout() {
1758 std::string current_package = Runtime::Current()->GetProcessPackageName();
1759 bool enabled_for_app = android::base::GetBoolProperty("debug.art.monitor.app", false);
1760 if (current_package == "android" || enabled_for_app) {
1761 monitor_lock_.setEnableMonitorTimeout();
1762 monitor_lock_.setMonitorId(monitor_id_);
1763 }
1764 }
1765
1766 } // namespace art
1767