blob: 676bceb766a521c4984bd6ee7827c8bb4fb6fdb8 [file] [log] [blame]
Elliott Hughes5f791332011-09-15 17:45:30 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Vladimir Markof52d92f2019-03-29 12:33:02 +000017#include "monitor-inl.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070018
Elliott Hughes08fc03a2012-06-26 17:34:00 -070019#include <vector>
20
Andreas Gampe46ee31b2016-12-14 10:11:49 -080021#include "android-base/stringprintf.h"
22
Mathieu Chartiere401d142015-04-22 13:56:20 -070023#include "art_method-inl.h"
Andreas Gampe170331f2017-12-07 18:41:03 -080024#include "base/logging.h" // For VLOG.
Elliott Hughes76b61672012-12-12 17:47:30 -080025#include "base/mutex.h"
David Sehrc431b9d2018-03-02 12:01:51 -080026#include "base/quasi_atomic.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080027#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080028#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010029#include "base/time_utils.h"
jeffhao33dc7712011-11-09 17:54:24 -080030#include "class_linker.h"
David Sehr9e734c72018-01-04 17:56:19 -080031#include "dex/dex_file-inl.h"
32#include "dex/dex_file_types.h"
33#include "dex/dex_instruction-inl.h"
Ian Rogersd9c4fc92013-10-01 19:45:43 -070034#include "lock_word-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070035#include "mirror/class-inl.h"
Ian Rogers05f30572013-02-20 12:13:11 -080036#include "mirror/object-inl.h"
Andreas Gampe5d08fcc2017-06-05 17:56:46 -070037#include "object_callbacks.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070038#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070039#include "stack.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070040#include "thread.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070041#include "thread_list.h"
Elliott Hughes08fc03a2012-06-26 17:34:00 -070042#include "verifier/method_verifier.h"
Elliott Hughes044288f2012-06-25 14:46:39 -070043#include "well_known_classes.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070044
45namespace art {
46
Andreas Gampe46ee31b2016-12-14 10:11:49 -080047using android::base::StringPrintf;
48
Andreas Gampe5d689142017-10-19 13:03:29 -070049static constexpr uint64_t kDebugThresholdFudgeFactor = kIsDebugBuild ? 10 : 1;
50static constexpr uint64_t kLongWaitMs = 100 * kDebugThresholdFudgeFactor;
Mathieu Chartierb9001ab2014-10-03 13:28:46 -070051
Elliott Hughes5f791332011-09-15 17:45:30 -070052/*
Ian Rogersd9c4fc92013-10-01 19:45:43 -070053 * Every Object has a monitor associated with it, but not every Object is actually locked. Even
54 * the ones that are locked do not need a full-fledged monitor until a) there is actual contention
55 * or b) wait() is called on the Object.
Elliott Hughes5f791332011-09-15 17:45:30 -070056 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070057 * For Android, we have implemented a scheme similar to the one described in Bacon et al.'s
58 * "Thin locks: featherweight synchronization for Java" (ACM 1998). Things are even easier for us,
59 * though, because we have a full 32 bits to work with.
Elliott Hughes5f791332011-09-15 17:45:30 -070060 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070061 * The two states of an Object's lock are referred to as "thin" and "fat". A lock may transition
Daniel Colascionec3d5b842018-04-15 10:52:18 -070062 * from the "thin" state to the "fat" state and this transition is referred to as inflation. We
63 * deflate locks from time to time as part of heap trimming.
Elliott Hughes5f791332011-09-15 17:45:30 -070064 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070065 * The lock value itself is stored in mirror::Object::monitor_ and the representation is described
66 * in the LockWord value type.
Elliott Hughes54e7df12011-09-16 11:47:04 -070067 *
Elliott Hughes5f791332011-09-15 17:45:30 -070068 * Monitors provide:
69 * - mutually exclusive access to resources
70 * - a way for multiple threads to wait for notification
71 *
72 * In effect, they fill the role of both mutexes and condition variables.
73 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070074 * Only one thread can own the monitor at any time. There may be several threads waiting on it
75 * (the wait call unlocks it). One or more waiting threads may be getting interrupted or notified
76 * at any given time.
Elliott Hughes5f791332011-09-15 17:45:30 -070077 */
Elliott Hughes54e7df12011-09-16 11:47:04 -070078
Elliott Hughesfc861622011-10-17 17:57:47 -070079uint32_t Monitor::lock_profiling_threshold_ = 0;
Andreas Gamped0210e52017-06-23 13:38:09 -070080uint32_t Monitor::stack_dump_lock_profiling_threshold_ = 0;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070081
Andreas Gamped0210e52017-06-23 13:38:09 -070082void Monitor::Init(uint32_t lock_profiling_threshold,
83 uint32_t stack_dump_lock_profiling_threshold) {
Andreas Gampe5d689142017-10-19 13:03:29 -070084 // It isn't great to always include the debug build fudge factor for command-
85 // line driven arguments, but it's easier to adjust here than in the build.
86 lock_profiling_threshold_ =
87 lock_profiling_threshold * kDebugThresholdFudgeFactor;
88 stack_dump_lock_profiling_threshold_ =
89 stack_dump_lock_profiling_threshold * kDebugThresholdFudgeFactor;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070090}
91
Vladimir Markof52d92f2019-03-29 12:33:02 +000092Monitor::Monitor(Thread* self, Thread* owner, ObjPtr<mirror::Object> obj, int32_t hash_code)
Ian Rogers00f7d0e2012-07-19 15:28:27 -070093 : monitor_lock_("a monitor lock", kMonitorLock),
Ian Rogersd9c4fc92013-10-01 19:45:43 -070094 monitor_contenders_("monitor contenders", monitor_lock_),
Mathieu Chartier46bc7782013-11-12 17:03:02 -080095 num_waiters_(0),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070096 owner_(owner),
Elliott Hughes5f791332011-09-15 17:45:30 -070097 lock_count_(0),
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070098 obj_(GcRoot<mirror::Object>(obj)),
Mathieu Chartier2cebb242015-04-21 16:50:40 -070099 wait_set_(nullptr),
Charles Mungerc665d632018-11-06 16:20:13 +0000100 wake_set_(nullptr),
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700101 hash_code_(hash_code),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700102 locking_method_(nullptr),
Ian Rogersef7d42f2014-01-06 12:55:46 -0800103 locking_dex_pc_(0),
Andreas Gampe74240812014-04-17 10:35:09 -0700104 monitor_id_(MonitorPool::ComputeMonitorId(this, self)) {
105#ifdef __LP64__
106 DCHECK(false) << "Should not be reached in 64b";
107 next_free_ = nullptr;
108#endif
109 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
110 // with the owner unlocking the thin-lock.
111 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
112 // The identity hash code is set for the life time of the monitor.
113}
114
Vladimir Markof52d92f2019-03-29 12:33:02 +0000115Monitor::Monitor(Thread* self,
116 Thread* owner,
117 ObjPtr<mirror::Object> obj,
118 int32_t hash_code,
Andreas Gampe74240812014-04-17 10:35:09 -0700119 MonitorId id)
120 : monitor_lock_("a monitor lock", kMonitorLock),
121 monitor_contenders_("monitor contenders", monitor_lock_),
122 num_waiters_(0),
123 owner_(owner),
124 lock_count_(0),
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700125 obj_(GcRoot<mirror::Object>(obj)),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700126 wait_set_(nullptr),
Charles Mungerc665d632018-11-06 16:20:13 +0000127 wake_set_(nullptr),
Andreas Gampe74240812014-04-17 10:35:09 -0700128 hash_code_(hash_code),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700129 locking_method_(nullptr),
Andreas Gampe74240812014-04-17 10:35:09 -0700130 locking_dex_pc_(0),
131 monitor_id_(id) {
132#ifdef __LP64__
133 next_free_ = nullptr;
134#endif
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700135 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
136 // with the owner unlocking the thin-lock.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800137 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700138 // The identity hash code is set for the life time of the monitor.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700139}
140
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700141int32_t Monitor::GetHashCode() {
Mathieu Chartier8bb3c682018-06-18 12:53:10 -0700142 int32_t hc = hash_code_.load(std::memory_order_relaxed);
143 if (!HasHashCode()) {
144 // Use a strong CAS to prevent spurious failures since these can make the boot image
145 // non-deterministic.
146 hash_code_.CompareAndSetStrongRelaxed(0, mirror::Object::GenerateIdentityHashCode());
147 hc = hash_code_.load(std::memory_order_relaxed);
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700148 }
149 DCHECK(HasHashCode());
Mathieu Chartier8bb3c682018-06-18 12:53:10 -0700150 return hc;
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700151}
152
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700153bool Monitor::Install(Thread* self) {
154 MutexLock mu(self, monitor_lock_); // Uncontended mutex acquisition as monitor isn't yet public.
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700155 CHECK(owner_ == nullptr || owner_ == self || owner_->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700156 // Propagate the lock state.
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700157 LockWord lw(GetObject()->GetLockWord(false));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700158 switch (lw.GetState()) {
159 case LockWord::kThinLocked: {
160 CHECK_EQ(owner_->GetThreadId(), lw.ThinLockOwner());
161 lock_count_ = lw.ThinLockCount();
162 break;
163 }
164 case LockWord::kHashCode: {
Orion Hodson88591fe2018-03-06 13:35:43 +0000165 CHECK_EQ(hash_code_.load(std::memory_order_relaxed), static_cast<int32_t>(lw.GetHashCode()));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700166 break;
167 }
168 case LockWord::kFatLocked: {
169 // The owner_ is suspended but another thread beat us to install a monitor.
170 return false;
171 }
172 case LockWord::kUnlocked: {
173 LOG(FATAL) << "Inflating unlocked lock word";
Elliott Hughesc1896c92018-11-29 11:33:18 -0800174 UNREACHABLE();
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700175 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700176 default: {
177 LOG(FATAL) << "Invalid monitor state " << lw.GetState();
Elliott Hughesc1896c92018-11-29 11:33:18 -0800178 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700179 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700180 }
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700181 LockWord fat(this, lw.GCState());
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700182 // Publish the updated lock word, which may race with other threads.
Mathieu Chartier42c2e502018-06-19 12:30:56 -0700183 bool success = GetObject()->CasLockWord(lw, fat, CASMode::kWeak, std::memory_order_release);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700184 // Lock profiling.
Mathieu Chartier9728f912013-10-30 09:45:13 -0700185 if (success && owner_ != nullptr && lock_profiling_threshold_ != 0) {
Andreas Gampe6ec8ebd2014-07-25 13:36:56 -0700186 // Do not abort on dex pc errors. This can easily happen when we want to dump a stack trace on
187 // abort.
188 locking_method_ = owner_->GetCurrentMethod(&locking_dex_pc_, false);
Andreas Gampe5a387272017-11-06 19:47:16 -0800189 if (locking_method_ != nullptr && UNLIKELY(locking_method_->IsProxyMethod())) {
190 // Grab another frame. Proxy methods are not helpful for lock profiling. This should be rare
191 // enough that it's OK to walk the stack twice.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100192 struct NextMethodVisitor final : public StackVisitor {
Andreas Gampe5a387272017-11-06 19:47:16 -0800193 explicit NextMethodVisitor(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_)
194 : StackVisitor(thread,
195 nullptr,
196 StackVisitor::StackWalkKind::kIncludeInlinedFrames,
197 false),
198 count_(0),
199 method_(nullptr),
200 dex_pc_(0) {}
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100201 bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe5a387272017-11-06 19:47:16 -0800202 ArtMethod* m = GetMethod();
203 if (m->IsRuntimeMethod()) {
204 // Continue if this is a runtime method.
205 return true;
206 }
207 count_++;
208 if (count_ == 2u) {
209 method_ = m;
210 dex_pc_ = GetDexPc(false);
211 return false;
212 }
213 return true;
214 }
215 size_t count_;
216 ArtMethod* method_;
217 uint32_t dex_pc_;
218 };
219 NextMethodVisitor nmv(owner_);
220 nmv.WalkStack();
221 locking_method_ = nmv.method_;
222 locking_dex_pc_ = nmv.dex_pc_;
223 }
224 DCHECK(locking_method_ == nullptr || !locking_method_->IsProxyMethod());
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700225 }
226 return success;
Elliott Hughes5f791332011-09-15 17:45:30 -0700227}
228
229Monitor::~Monitor() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700230 // Deflated monitors have a null object.
Elliott Hughes5f791332011-09-15 17:45:30 -0700231}
232
Elliott Hughes5f791332011-09-15 17:45:30 -0700233void Monitor::AppendToWaitSet(Thread* thread) {
Charles Mungerc665d632018-11-06 16:20:13 +0000234 // Not checking that the owner is equal to this thread, since we've released
235 // the monitor by the time this method is called.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700236 DCHECK(thread != nullptr);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700237 DCHECK(thread->GetWaitNext() == nullptr) << thread->GetWaitNext();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700238 if (wait_set_ == nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700239 wait_set_ = thread;
240 return;
241 }
242
243 // push_back.
244 Thread* t = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700245 while (t->GetWaitNext() != nullptr) {
246 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700247 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700248 t->SetWaitNext(thread);
Elliott Hughes5f791332011-09-15 17:45:30 -0700249}
250
Elliott Hughes5f791332011-09-15 17:45:30 -0700251void Monitor::RemoveFromWaitSet(Thread *thread) {
252 DCHECK(owner_ == Thread::Current());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700253 DCHECK(thread != nullptr);
Charles Mungerc665d632018-11-06 16:20:13 +0000254 auto remove = [&](Thread*& set){
255 if (set != nullptr) {
256 if (set == thread) {
257 set = thread->GetWaitNext();
258 thread->SetWaitNext(nullptr);
259 return true;
260 }
261 Thread* t = set;
262 while (t->GetWaitNext() != nullptr) {
263 if (t->GetWaitNext() == thread) {
264 t->SetWaitNext(thread->GetWaitNext());
265 thread->SetWaitNext(nullptr);
266 return true;
267 }
268 t = t->GetWaitNext();
269 }
Roland Levillain9cec9652018-11-06 10:50:20 +0000270 }
Charles Mungerc665d632018-11-06 16:20:13 +0000271 return false;
272 };
273 if (remove(wait_set_)) {
274 return;
Roland Levillain9cec9652018-11-06 10:50:20 +0000275 }
Charles Mungerc665d632018-11-06 16:20:13 +0000276 remove(wake_set_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700277}
278
Vladimir Markof52d92f2019-03-29 12:33:02 +0000279void Monitor::SetObject(ObjPtr<mirror::Object> object) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700280 obj_ = GcRoot<mirror::Object>(object);
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700281}
282
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700283// This function is inlined and just helps to not have the VLOG and ATRACE check at all the
284// potential tracing points.
Vladimir Markof52d92f2019-03-29 12:33:02 +0000285void Monitor::AtraceMonitorLock(Thread* self, ObjPtr<mirror::Object> obj, bool is_wait) {
Orion Hodson119733d2019-01-30 15:14:41 +0000286 if (UNLIKELY(VLOG_IS_ON(systrace_lock_logging) && ATraceEnabled())) {
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700287 AtraceMonitorLockImpl(self, obj, is_wait);
288 }
289}
290
Vladimir Markof52d92f2019-03-29 12:33:02 +0000291void Monitor::AtraceMonitorLockImpl(Thread* self, ObjPtr<mirror::Object> obj, bool is_wait) {
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700292 // Wait() requires a deeper call stack to be useful. Otherwise you'll see "Waiting at
293 // Object.java". Assume that we'll wait a nontrivial amount, so it's OK to do a longer
294 // stack walk than if !is_wait.
Andreas Gampec7d878d2018-11-19 18:42:06 +0000295 const size_t wanted_frame_number = is_wait ? 1U : 0U;
296
297 ArtMethod* method = nullptr;
298 uint32_t dex_pc = 0u;
299
300 size_t current_frame_number = 0u;
301 StackVisitor::WalkStack(
302 // Note: Adapted from CurrentMethodVisitor in thread.cc. We must not resolve here.
303 [&](const art::StackVisitor* stack_visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
304 ArtMethod* m = stack_visitor->GetMethod();
305 if (m == nullptr || m->IsRuntimeMethod()) {
306 // Runtime method, upcall, or resolution issue. Skip.
307 return true;
308 }
309
310 // Is this the requested frame?
311 if (current_frame_number == wanted_frame_number) {
312 method = m;
313 dex_pc = stack_visitor->GetDexPc(false /* abort_on_error*/);
314 return false;
315 }
316
317 // Look for more.
318 current_frame_number++;
319 return true;
320 },
321 self,
322 /* context= */ nullptr,
323 art::StackVisitor::StackWalkKind::kIncludeInlinedFrames);
324
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700325 const char* prefix = is_wait ? "Waiting on " : "Locking ";
326
327 const char* filename;
328 int32_t line_number;
Andreas Gampec7d878d2018-11-19 18:42:06 +0000329 TranslateLocation(method, dex_pc, &filename, &line_number);
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700330
331 // It would be nice to have a stable "ID" for the object here. However, the only stable thing
332 // would be the identity hashcode. But we cannot use IdentityHashcode here: For one, there are
333 // times when it is unsafe to make that call (see stack dumping for an explanation). More
334 // importantly, we would have to give up on thin-locking when adding systrace locks, as the
335 // identity hashcode is stored in the lockword normally (so can't be used with thin-locks).
336 //
337 // Because of thin-locks we also cannot use the monitor id (as there is no monitor). Monitor ids
338 // also do not have to be stable, as the monitor may be deflated.
339 std::string tmp = StringPrintf("%s %d at %s:%d",
340 prefix,
Vladimir Markof52d92f2019-03-29 12:33:02 +0000341 (obj == nullptr ? -1 : static_cast<int32_t>(reinterpret_cast<uintptr_t>(obj.Ptr()))),
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700342 (filename != nullptr ? filename : "null"),
343 line_number);
Orion Hodson119733d2019-01-30 15:14:41 +0000344 ATraceBegin(tmp.c_str());
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700345}
346
347void Monitor::AtraceMonitorUnlock() {
348 if (UNLIKELY(VLOG_IS_ON(systrace_lock_logging))) {
Orion Hodson119733d2019-01-30 15:14:41 +0000349 ATraceEnd();
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700350 }
351}
352
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700353std::string Monitor::PrettyContentionInfo(const std::string& owner_name,
354 pid_t owner_tid,
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700355 ArtMethod* owners_method,
356 uint32_t owners_dex_pc,
357 size_t num_waiters) {
Hiroshi Yamauchi71cd68d2017-01-25 18:28:12 -0800358 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700359 const char* owners_filename;
Goran Jakovljevic49c882b2016-04-19 10:27:21 +0200360 int32_t owners_line_number = 0;
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700361 if (owners_method != nullptr) {
362 TranslateLocation(owners_method, owners_dex_pc, &owners_filename, &owners_line_number);
363 }
364 std::ostringstream oss;
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700365 oss << "monitor contention with owner " << owner_name << " (" << owner_tid << ")";
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700366 if (owners_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700367 oss << " at " << owners_method->PrettyMethod();
Mathieu Chartier36891fe2016-04-28 17:21:08 -0700368 oss << "(" << owners_filename << ":" << owners_line_number << ")";
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700369 }
370 oss << " waiters=" << num_waiters;
371 return oss.str();
372}
373
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700374bool Monitor::TryLockLocked(Thread* self) {
375 if (owner_ == nullptr) { // Unowned.
376 owner_ = self;
377 CHECK_EQ(lock_count_, 0);
378 // When debugging, save the current monitor holder for future
379 // acquisition failures to use in sampled logging.
380 if (lock_profiling_threshold_ != 0) {
381 locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
Andreas Gampe5a387272017-11-06 19:47:16 -0800382 // We don't expect a proxy method here.
383 DCHECK(locking_method_ == nullptr || !locking_method_->IsProxyMethod());
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700384 }
385 } else if (owner_ == self) { // Recursive.
386 lock_count_++;
387 } else {
388 return false;
389 }
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700390 AtraceMonitorLock(self, GetObject(), /* is_wait= */ false);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700391 return true;
392}
393
394bool Monitor::TryLock(Thread* self) {
395 MutexLock mu(self, monitor_lock_);
396 return TryLockLocked(self);
397}
398
Alex Light77fee872017-09-05 14:51:49 -0700399// Asserts that a mutex isn't held when the class comes into and out of scope.
400class ScopedAssertNotHeld {
401 public:
402 ScopedAssertNotHeld(Thread* self, Mutex& mu) : self_(self), mu_(mu) {
403 mu_.AssertNotHeld(self_);
404 }
405
406 ~ScopedAssertNotHeld() {
407 mu_.AssertNotHeld(self_);
408 }
409
410 private:
411 Thread* const self_;
412 Mutex& mu_;
413 DISALLOW_COPY_AND_ASSIGN(ScopedAssertNotHeld);
414};
415
416template <LockReason reason>
Elliott Hughes5f791332011-09-15 17:45:30 -0700417void Monitor::Lock(Thread* self) {
Alex Light77fee872017-09-05 14:51:49 -0700418 ScopedAssertNotHeld sanh(self, monitor_lock_);
419 bool called_monitors_callback = false;
420 monitor_lock_.Lock(self);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700421 while (true) {
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700422 if (TryLockLocked(self)) {
Alex Light77fee872017-09-05 14:51:49 -0700423 break;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700424 }
425 // Contended.
426 const bool log_contention = (lock_profiling_threshold_ != 0);
Xin Guanb894a192014-08-22 11:55:37 -0500427 uint64_t wait_start_ms = log_contention ? MilliTime() : 0;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700428 ArtMethod* owners_method = locking_method_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700429 uint32_t owners_dex_pc = locking_dex_pc_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700430 // Do this before releasing the lock so that we don't get deflated.
Mathieu Chartierb9001ab2014-10-03 13:28:46 -0700431 size_t num_waiters = num_waiters_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700432 ++num_waiters_;
Andreas Gampe2702d562017-02-06 09:48:00 -0800433
434 // If systrace logging is enabled, first look at the lock owner. Acquiring the monitor's
435 // lock and then re-acquiring the mutator lock can deadlock.
436 bool started_trace = false;
Orion Hodson119733d2019-01-30 15:14:41 +0000437 if (ATraceEnabled()) {
Andreas Gampe2702d562017-02-06 09:48:00 -0800438 if (owner_ != nullptr) { // Did the owner_ give the lock up?
439 std::ostringstream oss;
440 std::string name;
441 owner_->GetThreadName(name);
442 oss << PrettyContentionInfo(name,
443 owner_->GetTid(),
444 owners_method,
445 owners_dex_pc,
446 num_waiters);
447 // Add info for contending thread.
448 uint32_t pc;
449 ArtMethod* m = self->GetCurrentMethod(&pc);
450 const char* filename;
451 int32_t line_number;
452 TranslateLocation(m, pc, &filename, &line_number);
453 oss << " blocking from "
454 << ArtMethod::PrettyMethod(m) << "(" << (filename != nullptr ? filename : "null")
455 << ":" << line_number << ")";
Orion Hodson119733d2019-01-30 15:14:41 +0000456 ATraceBegin(oss.str().c_str());
Andreas Gampe2702d562017-02-06 09:48:00 -0800457 started_trace = true;
458 }
459 }
460
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700461 monitor_lock_.Unlock(self); // Let go of locks in order.
Alex Light77fee872017-09-05 14:51:49 -0700462 // Call the contended locking cb once and only once. Also only call it if we are locking for
463 // the first time, not during a Wait wakeup.
464 if (reason == LockReason::kForLock && !called_monitors_callback) {
465 called_monitors_callback = true;
466 Runtime::Current()->GetRuntimeCallbacks()->MonitorContendedLocking(this);
467 }
Vladimir Markof52d92f2019-03-29 12:33:02 +0000468 self->SetMonitorEnterObject(GetObject().Ptr());
Elliott Hughes5f791332011-09-15 17:45:30 -0700469 {
Hiroshi Yamauchi71cd68d2017-01-25 18:28:12 -0800470 ScopedThreadSuspension tsc(self, kBlocked); // Change to blocked and give up mutator_lock_.
Andreas Gampe2702d562017-02-06 09:48:00 -0800471 uint32_t original_owner_thread_id = 0u;
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700472 {
473 // Reacquire monitor_lock_ without mutator_lock_ for Wait.
474 MutexLock mu2(self, monitor_lock_);
475 if (owner_ != nullptr) { // Did the owner_ give the lock up?
476 original_owner_thread_id = owner_->GetThreadId();
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700477 monitor_contenders_.Wait(self); // Still contended so wait.
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800478 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700479 }
480 if (original_owner_thread_id != 0u) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700481 // Woken from contention.
482 if (log_contention) {
Andreas Gampe111b1092017-06-22 20:28:23 -0700483 uint64_t wait_ms = MilliTime() - wait_start_ms;
484 uint32_t sample_percent;
485 if (wait_ms >= lock_profiling_threshold_) {
486 sample_percent = 100;
487 } else {
488 sample_percent = 100 * wait_ms / lock_profiling_threshold_;
489 }
490 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
491 // Reacquire mutator_lock_ for logging.
492 ScopedObjectAccess soa(self);
Andreas Gampe111b1092017-06-22 20:28:23 -0700493
Andreas Gamped0210e52017-06-23 13:38:09 -0700494 bool owner_alive = false;
495 pid_t original_owner_tid = 0;
496 std::string original_owner_name;
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700497
Andreas Gamped0210e52017-06-23 13:38:09 -0700498 const bool should_dump_stacks = stack_dump_lock_profiling_threshold_ > 0 &&
499 wait_ms > stack_dump_lock_profiling_threshold_;
500 std::string owner_stack_dump;
Andreas Gampe111b1092017-06-22 20:28:23 -0700501
Andreas Gamped0210e52017-06-23 13:38:09 -0700502 // Acquire thread-list lock to find thread and keep it from dying until we've got all
503 // the info we need.
504 {
Alex Lightb1e31a82017-10-04 16:57:36 -0700505 Locks::thread_list_lock_->ExclusiveLock(Thread::Current());
Andreas Gamped0210e52017-06-23 13:38:09 -0700506
507 // Re-find the owner in case the thread got killed.
508 Thread* original_owner = Runtime::Current()->GetThreadList()->FindThreadByThreadId(
509 original_owner_thread_id);
510
511 if (original_owner != nullptr) {
512 owner_alive = true;
513 original_owner_tid = original_owner->GetTid();
514 original_owner->GetThreadName(original_owner_name);
515
516 if (should_dump_stacks) {
517 // Very long contention. Dump stacks.
518 struct CollectStackTrace : public Closure {
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100519 void Run(art::Thread* thread) override
Andreas Gamped0210e52017-06-23 13:38:09 -0700520 REQUIRES_SHARED(art::Locks::mutator_lock_) {
521 thread->DumpJavaStack(oss);
522 }
523
524 std::ostringstream oss;
525 };
526 CollectStackTrace owner_trace;
Alex Lightb1e31a82017-10-04 16:57:36 -0700527 // RequestSynchronousCheckpoint releases the thread_list_lock_ as a part of its
528 // execution.
Andreas Gamped0210e52017-06-23 13:38:09 -0700529 original_owner->RequestSynchronousCheckpoint(&owner_trace);
530 owner_stack_dump = owner_trace.oss.str();
Alex Lightb1e31a82017-10-04 16:57:36 -0700531 } else {
532 Locks::thread_list_lock_->ExclusiveUnlock(Thread::Current());
Andreas Gamped0210e52017-06-23 13:38:09 -0700533 }
Alex Lightb1e31a82017-10-04 16:57:36 -0700534 } else {
535 Locks::thread_list_lock_->ExclusiveUnlock(Thread::Current());
Andreas Gamped0210e52017-06-23 13:38:09 -0700536 }
537 // This is all the data we need. Now drop the thread-list lock, it's OK for the
538 // owner to go away now.
539 }
540
541 // If we found the owner (and thus have owner data), go and log now.
542 if (owner_alive) {
543 // Give the detailed traces for really long contention.
544 if (should_dump_stacks) {
545 // This must be here (and not above) because we cannot hold the thread-list lock
546 // while running the checkpoint.
547 std::ostringstream self_trace_oss;
548 self->DumpJavaStack(self_trace_oss);
549
550 uint32_t pc;
551 ArtMethod* m = self->GetCurrentMethod(&pc);
552
553 LOG(WARNING) << "Long "
554 << PrettyContentionInfo(original_owner_name,
555 original_owner_tid,
556 owners_method,
557 owners_dex_pc,
558 num_waiters)
559 << " in " << ArtMethod::PrettyMethod(m) << " for "
560 << PrettyDuration(MsToNs(wait_ms)) << "\n"
561 << "Current owner stack:\n" << owner_stack_dump
562 << "Contender stack:\n" << self_trace_oss.str();
563 } else if (wait_ms > kLongWaitMs && owners_method != nullptr) {
Mathieu Chartier36891fe2016-04-28 17:21:08 -0700564 uint32_t pc;
565 ArtMethod* m = self->GetCurrentMethod(&pc);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700566 // TODO: We should maybe check that original_owner is still a live thread.
567 LOG(WARNING) << "Long "
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700568 << PrettyContentionInfo(original_owner_name,
569 original_owner_tid,
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700570 owners_method,
571 owners_dex_pc,
572 num_waiters)
David Sehr709b0702016-10-13 09:12:37 -0700573 << " in " << ArtMethod::PrettyMethod(m) << " for "
574 << PrettyDuration(MsToNs(wait_ms));
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700575 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700576 LogContentionEvent(self,
Alex Light77fee872017-09-05 14:51:49 -0700577 wait_ms,
578 sample_percent,
579 owners_method,
580 owners_dex_pc);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700581 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700582 }
583 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700584 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700585 }
Andreas Gampe2702d562017-02-06 09:48:00 -0800586 if (started_trace) {
Orion Hodson119733d2019-01-30 15:14:41 +0000587 ATraceEnd();
Andreas Gampe2702d562017-02-06 09:48:00 -0800588 }
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700589 self->SetMonitorEnterObject(nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700590 monitor_lock_.Lock(self); // Reacquire locks in order.
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700591 --num_waiters_;
Elliott Hughesfc861622011-10-17 17:57:47 -0700592 }
Alex Light77fee872017-09-05 14:51:49 -0700593 monitor_lock_.Unlock(self);
594 // We need to pair this with a single contended locking call. NB we match the RI behavior and call
595 // this even if MonitorEnter failed.
596 if (called_monitors_callback) {
597 CHECK(reason == LockReason::kForLock);
598 Runtime::Current()->GetRuntimeCallbacks()->MonitorContendedLocked(this);
599 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700600}
601
Alex Light77fee872017-09-05 14:51:49 -0700602template void Monitor::Lock<LockReason::kForLock>(Thread* self);
603template void Monitor::Lock<LockReason::kForWait>(Thread* self);
604
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800605static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
606 __attribute__((format(printf, 1, 2)));
607
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700608static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700609 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800610 va_list args;
611 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800612 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000613 self->ThrowNewExceptionV("Ljava/lang/IllegalMonitorStateException;", fmt, args);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700614 if (!Runtime::Current()->IsStarted() || VLOG_IS_ON(monitor)) {
Brian Carlstrom64277f32012-03-26 23:53:34 -0700615 std::ostringstream ss;
Ian Rogers62d6c772013-02-27 08:32:07 -0800616 self->Dump(ss);
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700617 LOG(Runtime::Current()->IsStarted() ? ::android::base::INFO : ::android::base::ERROR)
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000618 << self->GetException()->Dump() << "\n" << ss.str();
Brian Carlstrom64277f32012-03-26 23:53:34 -0700619 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800620 va_end(args);
621}
622
Elliott Hughesd4237412012-02-21 11:24:45 -0800623static std::string ThreadToString(Thread* thread) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700624 if (thread == nullptr) {
625 return "nullptr";
Elliott Hughesd4237412012-02-21 11:24:45 -0800626 }
627 std::ostringstream oss;
628 // TODO: alternatively, we could just return the thread's name.
629 oss << *thread;
630 return oss.str();
631}
632
Vladimir Markof52d92f2019-03-29 12:33:02 +0000633void Monitor::FailedUnlock(ObjPtr<mirror::Object> o,
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700634 uint32_t expected_owner_thread_id,
635 uint32_t found_owner_thread_id,
Elliott Hughesffb465f2012-03-01 18:46:05 -0800636 Monitor* monitor) {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700637 // Acquire thread list lock so threads won't disappear from under us.
Elliott Hughesffb465f2012-03-01 18:46:05 -0800638 std::string current_owner_string;
639 std::string expected_owner_string;
640 std::string found_owner_string;
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700641 uint32_t current_owner_thread_id = 0u;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800642 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700643 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700644 ThreadList* const thread_list = Runtime::Current()->GetThreadList();
645 Thread* expected_owner = thread_list->FindThreadByThreadId(expected_owner_thread_id);
646 Thread* found_owner = thread_list->FindThreadByThreadId(found_owner_thread_id);
647
Elliott Hughesffb465f2012-03-01 18:46:05 -0800648 // Re-read owner now that we hold lock.
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700649 Thread* current_owner = (monitor != nullptr) ? monitor->GetOwner() : nullptr;
650 if (current_owner != nullptr) {
651 current_owner_thread_id = current_owner->GetThreadId();
652 }
Elliott Hughesffb465f2012-03-01 18:46:05 -0800653 // Get short descriptions of the threads involved.
654 current_owner_string = ThreadToString(current_owner);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700655 expected_owner_string = expected_owner != nullptr ? ThreadToString(expected_owner) : "unnamed";
656 found_owner_string = found_owner != nullptr ? ThreadToString(found_owner) : "unnamed";
Elliott Hughesffb465f2012-03-01 18:46:05 -0800657 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700658
659 if (current_owner_thread_id == 0u) {
660 if (found_owner_thread_id == 0u) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800661 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
662 " on thread '%s'",
David Sehr709b0702016-10-13 09:12:37 -0700663 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800664 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800665 } else {
666 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800667 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
668 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800669 found_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700670 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800671 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800672 }
673 } else {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700674 if (found_owner_thread_id == 0u) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800675 // Race: originally there was no owner, there is now
676 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
677 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800678 current_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700679 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800680 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800681 } else {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700682 if (found_owner_thread_id != current_owner_thread_id) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800683 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800684 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
685 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800686 found_owner_string.c_str(),
687 current_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700688 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800689 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800690 } else {
691 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
692 " on thread '%s",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800693 current_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700694 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800695 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800696 }
697 }
698 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700699}
700
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700701bool Monitor::Unlock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700702 DCHECK(self != nullptr);
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700703 uint32_t owner_thread_id = 0u;
Charles Mungerc665d632018-11-06 16:20:13 +0000704 DCHECK(!monitor_lock_.IsExclusiveHeld(self));
705 monitor_lock_.Lock(self);
706 Thread* owner = owner_;
707 if (owner != nullptr) {
708 owner_thread_id = owner->GetThreadId();
709 }
710 if (owner == self) {
711 // We own the monitor, so nobody else can be in here.
712 AtraceMonitorUnlock();
713 if (lock_count_ == 0) {
714 owner_ = nullptr;
715 locking_method_ = nullptr;
716 locking_dex_pc_ = 0;
717 SignalContendersAndReleaseMonitorLock(self);
718 return true;
719 } else {
720 --lock_count_;
721 monitor_lock_.Unlock(self);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700722 return true;
Elliott Hughes5f791332011-09-15 17:45:30 -0700723 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700724 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700725 // We don't own this, so we're not allowed to unlock it.
726 // The JNI spec says that we should throw IllegalMonitorStateException in this case.
727 FailedUnlock(GetObject(), self->GetThreadId(), owner_thread_id, this);
Charles Mungerc665d632018-11-06 16:20:13 +0000728 monitor_lock_.Unlock(self);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700729 return false;
Elliott Hughes5f791332011-09-15 17:45:30 -0700730}
731
Charles Mungerc665d632018-11-06 16:20:13 +0000732void Monitor::SignalContendersAndReleaseMonitorLock(Thread* self) {
733 // We want to signal one thread to wake up, to acquire the monitor that
734 // we are releasing. This could either be a Thread waiting on its own
735 // ConditionVariable, or a thread waiting on monitor_contenders_.
736 while (wake_set_ != nullptr) {
737 // No risk of waking ourselves here; since monitor_lock_ is not released until we're ready to
738 // return, notify can't move the current thread from wait_set_ to wake_set_ until this
739 // method is done checking wake_set_.
740 Thread* thread = wake_set_;
741 wake_set_ = thread->GetWaitNext();
742 thread->SetWaitNext(nullptr);
743
744 // Check to see if the thread is still waiting.
745 {
746 // In the case of wait(), we'll be acquiring another thread's GetWaitMutex with
747 // self's GetWaitMutex held. This does not risk deadlock, because we only acquire this lock
748 // for threads in the wake_set_. A thread can only enter wake_set_ from Notify or NotifyAll,
749 // and those hold monitor_lock_. Thus, the threads whose wait mutexes we acquire here must
750 // have already been released from wait(), since we have not released monitor_lock_ until
751 // after we've chosen our thread to wake, so there is no risk of the following lock ordering
752 // leading to deadlock:
753 // Thread 1 waits
754 // Thread 2 waits
755 // Thread 3 moves threads 1 and 2 from wait_set_ to wake_set_
756 // Thread 1 enters this block, and attempts to acquire Thread 2's GetWaitMutex to wake it
757 // Thread 2 enters this block, and attempts to acquire Thread 1's GetWaitMutex to wake it
758 //
759 // Since monitor_lock_ is not released until the thread-to-be-woken-up's GetWaitMutex is
760 // acquired, two threads cannot attempt to acquire each other's GetWaitMutex while holding
761 // their own and cause deadlock.
762 MutexLock wait_mu(self, *thread->GetWaitMutex());
763 if (thread->GetWaitMonitor() != nullptr) {
764 // Release the lock, so that a potentially awakened thread will not
765 // immediately contend on it. The lock ordering here is:
766 // monitor_lock_, self->GetWaitMutex, thread->GetWaitMutex
767 monitor_lock_.Unlock(self);
768 thread->GetWaitConditionVariable()->Signal(self);
769 return;
770 }
771 }
772 }
773 // If we didn't wake any threads that were originally waiting on us,
774 // wake a contender.
775 monitor_contenders_.Signal(self);
776 monitor_lock_.Unlock(self);
777}
778
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800779void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
780 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700781 DCHECK(self != nullptr);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800782 DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
Elliott Hughes5f791332011-09-15 17:45:30 -0700783
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700784 monitor_lock_.Lock(self);
785
Elliott Hughes5f791332011-09-15 17:45:30 -0700786 // Make sure that we hold the lock.
787 if (owner_ != self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700788 monitor_lock_.Unlock(self);
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700789 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700790 return;
791 }
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800792
Elliott Hughesdf42c482013-01-09 12:49:02 -0800793 // We need to turn a zero-length timed wait into a regular wait because
794 // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
795 if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
796 why = kWaiting;
797 }
798
Elliott Hughes5f791332011-09-15 17:45:30 -0700799 // Enforce the timeout range.
800 if (ms < 0 || ns < 0 || ns > 999999) {
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700801 monitor_lock_.Unlock(self);
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000802 self->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
Ian Rogersef7d42f2014-01-06 12:55:46 -0800803 "timeout arguments out of range: ms=%" PRId64 " ns=%d", ms, ns);
Elliott Hughes5f791332011-09-15 17:45:30 -0700804 return;
805 }
806
Elliott Hughes5f791332011-09-15 17:45:30 -0700807 /*
Charles Mungerc665d632018-11-06 16:20:13 +0000808 * Release our hold - we need to let it go even if we're a few levels
Elliott Hughes5f791332011-09-15 17:45:30 -0700809 * deep in a recursive lock, and we need to restore that later.
Elliott Hughes5f791332011-09-15 17:45:30 -0700810 */
Ian Rogers0399dde2012-06-06 17:09:28 -0700811 int prev_lock_count = lock_count_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700812 lock_count_ = 0;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700813 owner_ = nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700814 ArtMethod* saved_method = locking_method_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700815 locking_method_ = nullptr;
Ian Rogers0399dde2012-06-06 17:09:28 -0700816 uintptr_t saved_dex_pc = locking_dex_pc_;
817 locking_dex_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700818
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700819 AtraceMonitorUnlock(); // For the implict Unlock() just above. This will only end the deepest
820 // nesting, but that is enough for the visualization, and corresponds to
821 // the single Lock() we do afterwards.
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700822 AtraceMonitorLock(self, GetObject(), /* is_wait= */ true);
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700823
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800824 bool was_interrupted = false;
Alex Light77fee872017-09-05 14:51:49 -0700825 bool timed_out = false;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700826 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700827 // Update thread state. If the GC wakes up, it'll ignore us, knowing
828 // that we won't touch any references in this state, and we'll check
829 // our suspend mode before we transition out.
830 ScopedThreadSuspension sts(self, why);
831
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700832 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700833 MutexLock mu(self, *self->GetWaitMutex());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700834
Charles Mungerc665d632018-11-06 16:20:13 +0000835 /*
836 * Add ourselves to the set of threads waiting on this monitor.
837 * It's important that we are only added to the wait set after
838 * acquiring our GetWaitMutex, so that calls to Notify() that occur after we
839 * have released monitor_lock_ will not move us from wait_set_ to wake_set_
840 * until we've signalled contenders on this monitor.
841 */
842 AppendToWaitSet(self);
843 ++num_waiters_;
844
845
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700846 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700847 // non-null a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700848 // up.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700849 DCHECK(self->GetWaitMonitor() == nullptr);
850 self->SetWaitMonitor(this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700851
852 // Release the monitor lock.
Charles Mungerc665d632018-11-06 16:20:13 +0000853 SignalContendersAndReleaseMonitorLock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700854
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800855 // Handle the case where the thread was interrupted before we called wait().
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000856 if (self->IsInterrupted()) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800857 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700858 } else {
859 // Wait for a notification or a timeout to occur.
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800860 if (why == kWaiting) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700861 self->GetWaitConditionVariable()->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700862 } else {
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800863 DCHECK(why == kTimedWaiting || why == kSleeping) << why;
Alex Light77fee872017-09-05 14:51:49 -0700864 timed_out = self->GetWaitConditionVariable()->TimedWait(self, ms, ns);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700865 }
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000866 was_interrupted = self->IsInterrupted();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700867 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700868 }
869
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800870 {
871 // We reset the thread's wait_monitor_ field after transitioning back to runnable so
872 // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
873 // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
874 // are waiting on "null".)
Ian Rogersdd7624d2014-03-14 17:43:00 -0700875 MutexLock mu(self, *self->GetWaitMutex());
876 DCHECK(self->GetWaitMonitor() != nullptr);
877 self->SetWaitMonitor(nullptr);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800878 }
879
Mathieu Chartierdaed5d82016-03-10 10:49:35 -0800880 // Allocate the interrupted exception not holding the monitor lock since it may cause a GC.
881 // If the GC requires acquiring the monitor for enqueuing cleared references, this would
882 // cause a deadlock if the monitor is held.
883 if (was_interrupted && interruptShouldThrow) {
884 /*
885 * We were interrupted while waiting, or somebody interrupted an
886 * un-interruptible thread earlier and we're bailing out immediately.
887 *
888 * The doc sayeth: "The interrupted status of the current thread is
889 * cleared when this exception is thrown."
890 */
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000891 self->SetInterrupted(false);
Mathieu Chartierdaed5d82016-03-10 10:49:35 -0800892 self->ThrowNewException("Ljava/lang/InterruptedException;", nullptr);
893 }
894
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700895 AtraceMonitorUnlock(); // End Wait().
896
Alex Light77fee872017-09-05 14:51:49 -0700897 // We just slept, tell the runtime callbacks about this.
898 Runtime::Current()->GetRuntimeCallbacks()->MonitorWaitFinished(this, timed_out);
899
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700900 // Re-acquire the monitor and lock.
Alex Light77fee872017-09-05 14:51:49 -0700901 Lock<LockReason::kForWait>(self);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700902 monitor_lock_.Lock(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700903 self->GetWaitMutex()->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700904
Elliott Hughes5f791332011-09-15 17:45:30 -0700905 /*
906 * We remove our thread from wait set after restoring the count
907 * and owner fields so the subroutine can check that the calling
908 * thread owns the monitor. Aside from that, the order of member
909 * updates is not order sensitive as we hold the pthread mutex.
910 */
911 owner_ = self;
Ian Rogers0399dde2012-06-06 17:09:28 -0700912 lock_count_ = prev_lock_count;
913 locking_method_ = saved_method;
914 locking_dex_pc_ = saved_dex_pc;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700915 --num_waiters_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700916 RemoveFromWaitSet(self);
917
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700918 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700919}
920
921void Monitor::Notify(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700922 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700923 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700924 // Make sure that we hold the lock.
925 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800926 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700927 return;
928 }
Charles Mungerc665d632018-11-06 16:20:13 +0000929 // Move one thread from waiters to wake set
930 Thread* to_move = wait_set_;
931 if (to_move != nullptr) {
932 wait_set_ = to_move->GetWaitNext();
933 to_move->SetWaitNext(wake_set_);
934 wake_set_ = to_move;
Elliott Hughes5f791332011-09-15 17:45:30 -0700935 }
936}
937
938void Monitor::NotifyAll(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700939 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700940 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700941 // Make sure that we hold the lock.
942 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800943 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700944 return;
945 }
Charles Mungerc665d632018-11-06 16:20:13 +0000946
947 // Move all threads from waiters to wake set
948 Thread* to_move = wait_set_;
949 if (to_move != nullptr) {
950 wait_set_ = nullptr;
951 Thread* move_to = wake_set_;
952 if (move_to == nullptr) {
953 wake_set_ = to_move;
954 return;
955 }
956 while (move_to->GetWaitNext() != nullptr) {
957 move_to = move_to->GetWaitNext();
958 }
959 move_to->SetWaitNext(to_move);
Elliott Hughes5f791332011-09-15 17:45:30 -0700960 }
961}
962
Vladimir Markof52d92f2019-03-29 12:33:02 +0000963bool Monitor::Deflate(Thread* self, ObjPtr<mirror::Object> obj) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700964 DCHECK(obj != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700965 // Don't need volatile since we only deflate with mutators suspended.
966 LockWord lw(obj->GetLockWord(false));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700967 // If the lock isn't an inflated monitor, then we don't need to deflate anything.
968 if (lw.GetState() == LockWord::kFatLocked) {
969 Monitor* monitor = lw.FatLockMonitor();
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700970 DCHECK(monitor != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700971 MutexLock mu(self, monitor->monitor_lock_);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700972 // Can't deflate if we have anybody waiting on the CV.
973 if (monitor->num_waiters_ > 0) {
974 return false;
975 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700976 Thread* owner = monitor->owner_;
977 if (owner != nullptr) {
978 // Can't deflate if we are locked and have a hash code.
979 if (monitor->HasHashCode()) {
980 return false;
981 }
982 // Can't deflate if our lock count is too high.
Mathieu Chartier1cf194f2016-11-01 20:13:24 -0700983 if (static_cast<uint32_t>(monitor->lock_count_) > LockWord::kThinLockMaxCount) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700984 return false;
985 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700986 // Deflate to a thin lock.
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700987 LockWord new_lw = LockWord::FromThinLockId(owner->GetThreadId(),
988 monitor->lock_count_,
989 lw.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800990 // Assume no concurrent read barrier state changes as mutators are suspended.
991 obj->SetLockWord(new_lw, false);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700992 VLOG(monitor) << "Deflated " << obj << " to thin lock " << owner->GetTid() << " / "
993 << monitor->lock_count_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700994 } else if (monitor->HasHashCode()) {
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700995 LockWord new_lw = LockWord::FromHashCode(monitor->GetHashCode(), lw.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800996 // Assume no concurrent read barrier state changes as mutators are suspended.
997 obj->SetLockWord(new_lw, false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700998 VLOG(monitor) << "Deflated " << obj << " to hash monitor " << monitor->GetHashCode();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700999 } else {
1000 // No lock and no hash, just put an empty lock word inside the object.
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001001 LockWord new_lw = LockWord::FromDefault(lw.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001002 // Assume no concurrent read barrier state changes as mutators are suspended.
1003 obj->SetLockWord(new_lw, false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001004 VLOG(monitor) << "Deflated" << obj << " to empty lock word";
Mathieu Chartier590fee92013-09-13 13:46:47 -07001005 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001006 // The monitor is deflated, mark the object as null so that we know to delete it during the
Mathieu Chartier590fee92013-09-13 13:46:47 -07001007 // next GC.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001008 monitor->obj_ = GcRoot<mirror::Object>(nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001009 }
1010 return true;
1011}
1012
Vladimir Markof52d92f2019-03-29 12:33:02 +00001013void Monitor::Inflate(Thread* self, Thread* owner, ObjPtr<mirror::Object> obj, int32_t hash_code) {
Andreas Gampe74240812014-04-17 10:35:09 -07001014 DCHECK(self != nullptr);
1015 DCHECK(obj != nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -07001016 // Allocate and acquire a new monitor.
Andreas Gampe74240812014-04-17 10:35:09 -07001017 Monitor* m = MonitorPool::CreateMonitor(self, owner, obj, hash_code);
1018 DCHECK(m != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001019 if (m->Install(self)) {
Haifeng Li86ab7912014-05-16 10:47:59 +08001020 if (owner != nullptr) {
1021 VLOG(monitor) << "monitor: thread" << owner->GetThreadId()
Andreas Gampe74240812014-04-17 10:35:09 -07001022 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +08001023 } else {
1024 VLOG(monitor) << "monitor: Inflate with hashcode " << hash_code
Andreas Gampe74240812014-04-17 10:35:09 -07001025 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +08001026 }
Andreas Gampe74240812014-04-17 10:35:09 -07001027 Runtime::Current()->GetMonitorList()->Add(m);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001028 CHECK_EQ(obj->GetLockWord(true).GetState(), LockWord::kFatLocked);
Andreas Gampe74240812014-04-17 10:35:09 -07001029 } else {
1030 MonitorPool::ReleaseMonitor(self, m);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001031 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001032}
1033
Mathieu Chartier0cd81352014-05-22 16:48:55 -07001034void Monitor::InflateThinLocked(Thread* self, Handle<mirror::Object> obj, LockWord lock_word,
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001035 uint32_t hash_code) {
1036 DCHECK_EQ(lock_word.GetState(), LockWord::kThinLocked);
1037 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1038 if (owner_thread_id == self->GetThreadId()) {
1039 // We own the monitor, we can easily inflate it.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001040 Inflate(self, self, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001041 } else {
1042 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1043 // Suspend the owner, inflate. First change to blocked and give up mutator_lock_.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001044 self->SetMonitorEnterObject(obj.Get());
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -07001045 bool timed_out;
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07001046 Thread* owner;
1047 {
Alex Light77fee872017-09-05 14:51:49 -07001048 ScopedThreadSuspension sts(self, kWaitingForLockInflation);
Alex Light46f93402017-06-29 11:59:50 -07001049 owner = thread_list->SuspendThreadByThreadId(owner_thread_id,
1050 SuspendReason::kInternal,
1051 &timed_out);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07001052 }
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -07001053 if (owner != nullptr) {
1054 // We succeeded in suspending the thread, check the lock's status didn't change.
1055 lock_word = obj->GetLockWord(true);
1056 if (lock_word.GetState() == LockWord::kThinLocked &&
1057 lock_word.ThinLockOwner() == owner_thread_id) {
1058 // Go ahead and inflate the lock.
1059 Inflate(self, owner, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001060 }
Alex Light88fd7202017-06-30 08:31:59 -07001061 bool resumed = thread_list->Resume(owner, SuspendReason::kInternal);
1062 DCHECK(resumed);
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001063 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07001064 self->SetMonitorEnterObject(nullptr);
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001065 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001066}
1067
Ian Rogers719d1a32014-03-06 12:13:39 -08001068// Fool annotalysis into thinking that the lock on obj is acquired.
Vladimir Markof52d92f2019-03-29 12:33:02 +00001069static ObjPtr<mirror::Object> FakeLock(ObjPtr<mirror::Object> obj)
1070 EXCLUSIVE_LOCK_FUNCTION(obj.Ptr()) NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers719d1a32014-03-06 12:13:39 -08001071 return obj;
1072}
1073
1074// Fool annotalysis into thinking that the lock on obj is release.
Vladimir Markof52d92f2019-03-29 12:33:02 +00001075static ObjPtr<mirror::Object> FakeUnlock(ObjPtr<mirror::Object> obj)
1076 UNLOCK_FUNCTION(obj.Ptr()) NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers719d1a32014-03-06 12:13:39 -08001077 return obj;
1078}
1079
Vladimir Markof52d92f2019-03-29 12:33:02 +00001080ObjPtr<mirror::Object> Monitor::MonitorEnter(Thread* self,
1081 ObjPtr<mirror::Object> obj,
1082 bool trylock) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001083 DCHECK(self != nullptr);
1084 DCHECK(obj != nullptr);
Mathieu Chartier2d096c92015-10-12 16:18:20 -07001085 self->AssertThreadSuspensionIsAllowable();
Ian Rogers719d1a32014-03-06 12:13:39 -08001086 obj = FakeLock(obj);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001087 uint32_t thread_id = self->GetThreadId();
1088 size_t contention_count = 0;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001089 StackHandleScope<1> hs(self);
1090 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001091 while (true) {
Hans Boehmb3da36c2016-12-15 13:12:59 -08001092 // We initially read the lockword with ordinary Java/relaxed semantics. When stronger
1093 // semantics are needed, we address it below. Since GetLockWord bottoms out to a relaxed load,
1094 // we can fix it later, in an infrequently executed case, with a fence.
1095 LockWord lock_word = h_obj->GetLockWord(false);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001096 switch (lock_word.GetState()) {
1097 case LockWord::kUnlocked: {
Hans Boehmb3da36c2016-12-15 13:12:59 -08001098 // No ordering required for preceding lockword read, since we retest.
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001099 LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0, lock_word.GCState()));
Mathieu Chartier42c2e502018-06-19 12:30:56 -07001100 if (h_obj->CasLockWord(lock_word, thin_locked, CASMode::kWeak, std::memory_order_acquire)) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001101 AtraceMonitorLock(self, h_obj.Get(), /* is_wait= */ false);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001102 return h_obj.Get(); // Success!
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001103 }
1104 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -07001105 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001106 case LockWord::kThinLocked: {
1107 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1108 if (owner_thread_id == thread_id) {
Hans Boehmb3da36c2016-12-15 13:12:59 -08001109 // No ordering required for initial lockword read.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001110 // We own the lock, increase the recursion count.
1111 uint32_t new_count = lock_word.ThinLockCount() + 1;
1112 if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001113 LockWord thin_locked(LockWord::FromThinLockId(thread_id,
1114 new_count,
1115 lock_word.GCState()));
Hans Boehmb3da36c2016-12-15 13:12:59 -08001116 // Only this thread pays attention to the count. Thus there is no need for stronger
1117 // than relaxed memory ordering.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001118 if (!kUseReadBarrier) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001119 h_obj->SetLockWord(thin_locked, /* as_volatile= */ false);
1120 AtraceMonitorLock(self, h_obj.Get(), /* is_wait= */ false);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001121 return h_obj.Get(); // Success!
1122 } else {
1123 // Use CAS to preserve the read barrier state.
Mathieu Chartier42c2e502018-06-19 12:30:56 -07001124 if (h_obj->CasLockWord(lock_word,
1125 thin_locked,
1126 CASMode::kWeak,
1127 std::memory_order_relaxed)) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001128 AtraceMonitorLock(self, h_obj.Get(), /* is_wait= */ false);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001129 return h_obj.Get(); // Success!
1130 }
1131 }
1132 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -07001133 } else {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001134 // We'd overflow the recursion count, so inflate the monitor.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001135 InflateThinLocked(self, h_obj, lock_word, 0);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001136 }
1137 } else {
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07001138 if (trylock) {
1139 return nullptr;
1140 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001141 // Contention.
1142 contention_count++;
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001143 Runtime* runtime = Runtime::Current();
Hans Boehmb3da36c2016-12-15 13:12:59 -08001144 if (contention_count <= runtime->GetMaxSpinsBeforeThinLockInflation()) {
Alex Light77fee872017-09-05 14:51:49 -07001145 // TODO: Consider switching the thread state to kWaitingForLockInflation when we are
1146 // yielding. Use sched_yield instead of NanoSleep since NanoSleep can wait much longer
1147 // than the parameter you pass in. This can cause thread suspension to take excessively
1148 // long and make long pauses. See b/16307460.
Hans Boehmb3da36c2016-12-15 13:12:59 -08001149 // TODO: We should literally spin first, without sched_yield. Sched_yield either does
1150 // nothing (at significant expense), or guarantees that we wait at least microseconds.
1151 // If the owner is running, I would expect the median lock hold time to be hundreds
1152 // of nanoseconds or less.
Mathieu Chartier251755c2014-07-15 18:10:25 -07001153 sched_yield();
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001154 } else {
1155 contention_count = 0;
Hans Boehmb3da36c2016-12-15 13:12:59 -08001156 // No ordering required for initial lockword read. Install rereads it anyway.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001157 InflateThinLocked(self, h_obj, lock_word, 0);
Elliott Hughes5f791332011-09-15 17:45:30 -07001158 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001159 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001160 continue; // Start from the beginning.
Elliott Hughes5f791332011-09-15 17:45:30 -07001161 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001162 case LockWord::kFatLocked: {
Hans Boehmb3da36c2016-12-15 13:12:59 -08001163 // We should have done an acquire read of the lockword initially, to ensure
1164 // visibility of the monitor data structure. Use an explicit fence instead.
Orion Hodson27b96762018-03-13 16:06:57 +00001165 std::atomic_thread_fence(std::memory_order_acquire);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001166 Monitor* mon = lock_word.FatLockMonitor();
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07001167 if (trylock) {
1168 return mon->TryLock(self) ? h_obj.Get() : nullptr;
1169 } else {
1170 mon->Lock(self);
1171 return h_obj.Get(); // Success!
1172 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001173 }
Ian Rogers719d1a32014-03-06 12:13:39 -08001174 case LockWord::kHashCode:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001175 // Inflate with the existing hashcode.
Hans Boehmb3da36c2016-12-15 13:12:59 -08001176 // Again no ordering required for initial lockword read, since we don't rely
1177 // on the visibility of any prior computation.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001178 Inflate(self, nullptr, h_obj.Get(), lock_word.GetHashCode());
Ian Rogers719d1a32014-03-06 12:13:39 -08001179 continue; // Start from the beginning.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001180 default: {
1181 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Andreas Gampec7ed09b2016-04-25 20:08:55 -07001182 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001183 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001184 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001185 }
1186}
1187
Vladimir Markof52d92f2019-03-29 12:33:02 +00001188bool Monitor::MonitorExit(Thread* self, ObjPtr<mirror::Object> obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001189 DCHECK(self != nullptr);
1190 DCHECK(obj != nullptr);
Mathieu Chartier2d096c92015-10-12 16:18:20 -07001191 self->AssertThreadSuspensionIsAllowable();
Ian Rogers719d1a32014-03-06 12:13:39 -08001192 obj = FakeUnlock(obj);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001193 StackHandleScope<1> hs(self);
1194 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001195 while (true) {
1196 LockWord lock_word = obj->GetLockWord(true);
1197 switch (lock_word.GetState()) {
1198 case LockWord::kHashCode:
1199 // Fall-through.
1200 case LockWord::kUnlocked:
Mathieu Chartier61b3cd42016-04-18 11:43:29 -07001201 FailedUnlock(h_obj.Get(), self->GetThreadId(), 0u, nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001202 return false; // Failure.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001203 case LockWord::kThinLocked: {
1204 uint32_t thread_id = self->GetThreadId();
1205 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1206 if (owner_thread_id != thread_id) {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -07001207 FailedUnlock(h_obj.Get(), thread_id, owner_thread_id, nullptr);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001208 return false; // Failure.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001209 } else {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001210 // We own the lock, decrease the recursion count.
1211 LockWord new_lw = LockWord::Default();
1212 if (lock_word.ThinLockCount() != 0) {
1213 uint32_t new_count = lock_word.ThinLockCount() - 1;
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001214 new_lw = LockWord::FromThinLockId(thread_id, new_count, lock_word.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001215 } else {
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001216 new_lw = LockWord::FromDefault(lock_word.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001217 }
1218 if (!kUseReadBarrier) {
1219 DCHECK_EQ(new_lw.ReadBarrierState(), 0U);
Hans Boehmb3da36c2016-12-15 13:12:59 -08001220 // TODO: This really only needs memory_order_release, but we currently have
1221 // no way to specify that. In fact there seem to be no legitimate uses of SetLockWord
1222 // with a final argument of true. This slows down x86 and ARMv7, but probably not v8.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001223 h_obj->SetLockWord(new_lw, true);
Andreas Gampe6e759ad2016-05-17 10:13:10 -07001224 AtraceMonitorUnlock();
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001225 // Success!
1226 return true;
1227 } else {
1228 // Use CAS to preserve the read barrier state.
Mathieu Chartier42c2e502018-06-19 12:30:56 -07001229 if (h_obj->CasLockWord(lock_word, new_lw, CASMode::kWeak, std::memory_order_release)) {
Andreas Gampe6e759ad2016-05-17 10:13:10 -07001230 AtraceMonitorUnlock();
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001231 // Success!
1232 return true;
1233 }
1234 }
1235 continue; // Go again.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001236 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001237 }
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001238 case LockWord::kFatLocked: {
1239 Monitor* mon = lock_word.FatLockMonitor();
1240 return mon->Unlock(self);
1241 }
1242 default: {
1243 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Elliott Hughesc1896c92018-11-29 11:33:18 -08001244 UNREACHABLE();
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001245 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001246 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001247 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001248}
1249
Vladimir Markof52d92f2019-03-29 12:33:02 +00001250void Monitor::Wait(Thread* self,
1251 ObjPtr<mirror::Object> obj,
1252 int64_t ms,
1253 int32_t ns,
1254 bool interruptShouldThrow,
1255 ThreadState why) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001256 DCHECK(self != nullptr);
1257 DCHECK(obj != nullptr);
Alex Light77fee872017-09-05 14:51:49 -07001258 StackHandleScope<1> hs(self);
1259 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
1260
1261 Runtime::Current()->GetRuntimeCallbacks()->ObjectWaitStart(h_obj, ms);
Alex Light848574c2017-09-25 16:59:39 -07001262 if (UNLIKELY(self->ObserveAsyncException() || self->IsExceptionPending())) {
Alex Light77fee872017-09-05 14:51:49 -07001263 // See b/65558434 for information on handling of exceptions here.
1264 return;
1265 }
1266
1267 LockWord lock_word = h_obj->GetLockWord(true);
Ian Rogers43c69cc2014-08-15 11:09:28 -07001268 while (lock_word.GetState() != LockWord::kFatLocked) {
1269 switch (lock_word.GetState()) {
1270 case LockWord::kHashCode:
1271 // Fall-through.
1272 case LockWord::kUnlocked:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001273 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
1274 return; // Failure.
Ian Rogers43c69cc2014-08-15 11:09:28 -07001275 case LockWord::kThinLocked: {
1276 uint32_t thread_id = self->GetThreadId();
1277 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1278 if (owner_thread_id != thread_id) {
1279 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
1280 return; // Failure.
1281 } else {
1282 // We own the lock, inflate to enqueue ourself on the Monitor. May fail spuriously so
1283 // re-load.
Alex Light77fee872017-09-05 14:51:49 -07001284 Inflate(self, self, h_obj.Get(), 0);
1285 lock_word = h_obj->GetLockWord(true);
Ian Rogers43c69cc2014-08-15 11:09:28 -07001286 }
1287 break;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001288 }
Ian Rogers43c69cc2014-08-15 11:09:28 -07001289 case LockWord::kFatLocked: // Unreachable given the loop condition above. Fall-through.
1290 default: {
1291 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Elliott Hughesc1896c92018-11-29 11:33:18 -08001292 UNREACHABLE();
Ian Rogers43c69cc2014-08-15 11:09:28 -07001293 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001294 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001295 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001296 Monitor* mon = lock_word.FatLockMonitor();
1297 mon->Wait(self, ms, ns, interruptShouldThrow, why);
Elliott Hughes5f791332011-09-15 17:45:30 -07001298}
1299
Vladimir Markof52d92f2019-03-29 12:33:02 +00001300void Monitor::DoNotify(Thread* self, ObjPtr<mirror::Object> obj, bool notify_all) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001301 DCHECK(self != nullptr);
1302 DCHECK(obj != nullptr);
1303 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001304 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001305 case LockWord::kHashCode:
1306 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001307 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -08001308 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001309 return; // Failure.
1310 case LockWord::kThinLocked: {
1311 uint32_t thread_id = self->GetThreadId();
1312 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1313 if (owner_thread_id != thread_id) {
1314 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
1315 return; // Failure.
1316 } else {
1317 // We own the lock but there's no Monitor and therefore no waiters.
1318 return; // Success.
1319 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001320 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001321 case LockWord::kFatLocked: {
1322 Monitor* mon = lock_word.FatLockMonitor();
1323 if (notify_all) {
1324 mon->NotifyAll(self);
1325 } else {
1326 mon->Notify(self);
1327 }
1328 return; // Success.
1329 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001330 default: {
1331 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Elliott Hughesc1896c92018-11-29 11:33:18 -08001332 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001333 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001334 }
1335}
1336
Vladimir Markof52d92f2019-03-29 12:33:02 +00001337uint32_t Monitor::GetLockOwnerThreadId(ObjPtr<mirror::Object> obj) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001338 DCHECK(obj != nullptr);
1339 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001340 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001341 case LockWord::kHashCode:
1342 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001343 case LockWord::kUnlocked:
1344 return ThreadList::kInvalidThreadId;
1345 case LockWord::kThinLocked:
1346 return lock_word.ThinLockOwner();
1347 case LockWord::kFatLocked: {
1348 Monitor* mon = lock_word.FatLockMonitor();
1349 return mon->GetOwnerThreadId();
Elliott Hughes5f791332011-09-15 17:45:30 -07001350 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001351 default: {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001352 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001353 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001354 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001355 }
1356}
1357
Andreas Gampef3ebcce2017-12-11 20:40:23 -08001358ThreadState Monitor::FetchState(const Thread* thread,
Vladimir Markof52d92f2019-03-29 12:33:02 +00001359 /* out */ ObjPtr<mirror::Object>* monitor_object,
Andreas Gampef3ebcce2017-12-11 20:40:23 -08001360 /* out */ uint32_t* lock_owner_tid) {
1361 DCHECK(monitor_object != nullptr);
1362 DCHECK(lock_owner_tid != nullptr);
1363
1364 *monitor_object = nullptr;
1365 *lock_owner_tid = ThreadList::kInvalidThreadId;
1366
1367 ThreadState state = thread->GetState();
1368
1369 switch (state) {
1370 case kWaiting:
1371 case kTimedWaiting:
1372 case kSleeping:
1373 {
1374 Thread* self = Thread::Current();
1375 MutexLock mu(self, *thread->GetWaitMutex());
1376 Monitor* monitor = thread->GetWaitMonitor();
1377 if (monitor != nullptr) {
1378 *monitor_object = monitor->GetObject();
Ian Rogersd803bc72014-04-01 15:33:03 -07001379 }
1380 }
Andreas Gampef3ebcce2017-12-11 20:40:23 -08001381 break;
1382
1383 case kBlocked:
1384 case kWaitingForLockInflation:
1385 {
Vladimir Markof52d92f2019-03-29 12:33:02 +00001386 ObjPtr<mirror::Object> lock_object = thread->GetMonitorEnterObject();
Andreas Gampef3ebcce2017-12-11 20:40:23 -08001387 if (lock_object != nullptr) {
1388 if (kUseReadBarrier && Thread::Current()->GetIsGcMarking()) {
1389 // We may call Thread::Dump() in the middle of the CC thread flip and this thread's stack
1390 // may have not been flipped yet and "pretty_object" may be a from-space (stale) ref, in
1391 // which case the GetLockOwnerThreadId() call below will crash. So explicitly mark/forward
1392 // it here.
Vladimir Markof52d92f2019-03-29 12:33:02 +00001393 lock_object = ReadBarrier::Mark(lock_object.Ptr());
Andreas Gampef3ebcce2017-12-11 20:40:23 -08001394 }
1395 *monitor_object = lock_object;
1396 *lock_owner_tid = lock_object->GetLockOwnerThreadId();
1397 }
Ian Rogersd803bc72014-04-01 15:33:03 -07001398 }
Andreas Gampef3ebcce2017-12-11 20:40:23 -08001399 break;
1400
1401 default:
1402 break;
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001403 }
Andreas Gampef3ebcce2017-12-11 20:40:23 -08001404
1405 return state;
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001406}
1407
Vladimir Markof52d92f2019-03-29 12:33:02 +00001408ObjPtr<mirror::Object> Monitor::GetContendedMonitor(Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -08001409 // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
1410 // definition of contended that includes a monitor a thread is trying to enter...
Vladimir Markof52d92f2019-03-29 12:33:02 +00001411 ObjPtr<mirror::Object> result = thread->GetMonitorEnterObject();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001412 if (result == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001413 // ...but also a monitor that the thread is waiting on.
Ian Rogersdd7624d2014-03-14 17:43:00 -07001414 MutexLock mu(Thread::Current(), *thread->GetWaitMutex());
1415 Monitor* monitor = thread->GetWaitMonitor();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001416 if (monitor != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001417 result = monitor->GetObject();
Elliott Hughesf9501702013-01-11 11:22:27 -08001418 }
1419 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001420 return result;
Elliott Hughesf9501702013-01-11 11:22:27 -08001421}
1422
Vladimir Markof52d92f2019-03-29 12:33:02 +00001423void Monitor::VisitLocks(StackVisitor* stack_visitor,
1424 void (*callback)(ObjPtr<mirror::Object>, void*),
1425 void* callback_context,
1426 bool abort_on_failure) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001427 ArtMethod* m = stack_visitor->GetMethod();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001428 CHECK(m != nullptr);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001429
1430 // Native methods are an easy special case.
1431 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
1432 if (m->IsNative()) {
1433 if (m->IsSynchronized()) {
Vladimir Markof52d92f2019-03-29 12:33:02 +00001434 ObjPtr<mirror::Object> jni_this =
Mathieu Chartiere401d142015-04-22 13:56:20 -07001435 stack_visitor->GetCurrentHandleScope(sizeof(void*))->GetReference(0);
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001436 callback(jni_this, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001437 }
1438 return;
1439 }
1440
jeffhao61f916c2012-10-25 17:48:51 -07001441 // Proxy methods should not be synchronized.
1442 if (m->IsProxyMethod()) {
1443 CHECK(!m->IsSynchronized());
1444 return;
1445 }
1446
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001447 // Is there any reason to believe there's any synchronization in this method?
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001448 CHECK(m->GetCodeItem() != nullptr) << m->PrettyMethod();
David Sehr0225f8e2018-01-31 08:52:24 +00001449 CodeItemDataAccessor accessor(m->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001450 if (accessor.TriesSize() == 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001451 return; // No "tries" implies no synchronization, so no held locks to report.
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001452 }
1453
Andreas Gampe760172c2014-08-16 13:41:10 -07001454 // Get the dex pc. If abort_on_failure is false, GetDexPc will not abort in the case it cannot
1455 // find the dex pc, and instead return kDexNoIndex. Then bail out, as it indicates we have an
1456 // inconsistent stack anyways.
1457 uint32_t dex_pc = stack_visitor->GetDexPc(abort_on_failure);
Andreas Gampee2abbc62017-09-15 11:59:26 -07001458 if (!abort_on_failure && dex_pc == dex::kDexNoIndex) {
David Sehr709b0702016-10-13 09:12:37 -07001459 LOG(ERROR) << "Could not find dex_pc for " << m->PrettyMethod();
Andreas Gampe760172c2014-08-16 13:41:10 -07001460 return;
1461 }
1462
Elliott Hughes80537bb2013-01-04 16:37:26 -08001463 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
1464 // the locks held in this stack frame.
Andreas Gampeaaf0d382017-11-27 14:10:21 -08001465 std::vector<verifier::MethodVerifier::DexLockInfo> monitor_enter_dex_pcs;
Andreas Gampe6cc23ac2018-08-24 15:22:43 -07001466 verifier::MethodVerifier::FindLocksAtDexPc(m,
1467 dex_pc,
1468 &monitor_enter_dex_pcs,
1469 Runtime::Current()->GetTargetSdkVersion());
Andreas Gampeaaf0d382017-11-27 14:10:21 -08001470 for (verifier::MethodVerifier::DexLockInfo& dex_lock_info : monitor_enter_dex_pcs) {
1471 // As a debug check, check that dex PC corresponds to a monitor-enter.
1472 if (kIsDebugBuild) {
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001473 const Instruction& monitor_enter_instruction = accessor.InstructionAt(dex_lock_info.dex_pc);
1474 CHECK_EQ(monitor_enter_instruction.Opcode(), Instruction::MONITOR_ENTER)
Andreas Gampeaaf0d382017-11-27 14:10:21 -08001475 << "expected monitor-enter @" << dex_lock_info.dex_pc << "; was "
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001476 << reinterpret_cast<const void*>(&monitor_enter_instruction);
Andreas Gampeaaf0d382017-11-27 14:10:21 -08001477 }
Elliott Hughes80537bb2013-01-04 16:37:26 -08001478
Andreas Gampeaaf0d382017-11-27 14:10:21 -08001479 // Iterate through the set of dex registers, as the compiler may not have held all of them
1480 // live.
1481 bool success = false;
1482 for (uint32_t dex_reg : dex_lock_info.dex_registers) {
1483 uint32_t value;
1484 success = stack_visitor->GetVReg(m, dex_reg, kReferenceVReg, &value);
1485 if (success) {
Vladimir Markof52d92f2019-03-29 12:33:02 +00001486 ObjPtr<mirror::Object> o = reinterpret_cast<mirror::Object*>(value);
Andreas Gampeaaf0d382017-11-27 14:10:21 -08001487 callback(o, callback_context);
1488 break;
1489 }
1490 }
1491 DCHECK(success) << "Failed to find/read reference for monitor-enter at dex pc "
1492 << dex_lock_info.dex_pc
1493 << " in method "
1494 << m->PrettyMethod();
1495 if (!success) {
1496 LOG(WARNING) << "Had a lock reported for dex pc " << dex_lock_info.dex_pc
1497 << " but was not able to fetch a corresponding object!";
1498 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001499 }
1500}
1501
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001502bool Monitor::IsValidLockWord(LockWord lock_word) {
1503 switch (lock_word.GetState()) {
1504 case LockWord::kUnlocked:
1505 // Nothing to check.
1506 return true;
1507 case LockWord::kThinLocked:
1508 // Basic sanity check of owner.
1509 return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
1510 case LockWord::kFatLocked: {
1511 // Check the monitor appears in the monitor list.
1512 Monitor* mon = lock_word.FatLockMonitor();
1513 MonitorList* list = Runtime::Current()->GetMonitorList();
1514 MutexLock mu(Thread::Current(), list->monitor_list_lock_);
1515 for (Monitor* list_mon : list->list_) {
1516 if (mon == list_mon) {
1517 return true; // Found our monitor.
1518 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001519 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001520 return false; // Fail - unowned monitor in an object.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001521 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001522 case LockWord::kHashCode:
1523 return true;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001524 default:
1525 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001526 UNREACHABLE();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001527 }
1528}
1529
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001530bool Monitor::IsLocked() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001531 MutexLock mu(Thread::Current(), monitor_lock_);
1532 return owner_ != nullptr;
1533}
1534
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -07001535void Monitor::TranslateLocation(ArtMethod* method,
1536 uint32_t dex_pc,
1537 const char** source_file,
1538 int32_t* line_number) {
jeffhao33dc7712011-11-09 17:54:24 -08001539 // If method is null, location is unknown
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001540 if (method == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001541 *source_file = "";
1542 *line_number = 0;
jeffhao33dc7712011-11-09 17:54:24 -08001543 return;
1544 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001545 *source_file = method->GetDeclaringClassSourceFile();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001546 if (*source_file == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001547 *source_file = "";
Elliott Hughes12c51e32012-01-17 20:25:05 -08001548 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001549 *line_number = method->GetLineNumFromDexPC(dex_pc);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001550}
1551
1552uint32_t Monitor::GetOwnerThreadId() {
1553 MutexLock mu(Thread::Current(), monitor_lock_);
1554 Thread* owner = owner_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001555 if (owner != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001556 return owner->GetThreadId();
1557 } else {
1558 return ThreadList::kInvalidThreadId;
1559 }
jeffhao33dc7712011-11-09 17:54:24 -08001560}
1561
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001562MonitorList::MonitorList()
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001563 : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock", kMonitorListLock),
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001564 monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001565}
1566
1567MonitorList::~MonitorList() {
Andreas Gampe74240812014-04-17 10:35:09 -07001568 Thread* self = Thread::Current();
1569 MutexLock mu(self, monitor_list_lock_);
1570 // Release all monitors to the pool.
1571 // TODO: Is it an invariant that *all* open monitors are in the list? Then we could
1572 // clear faster in the pool.
1573 MonitorPool::ReleaseMonitors(self, &list_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001574}
1575
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001576void MonitorList::DisallowNewMonitors() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001577 CHECK(!kUseReadBarrier);
Ian Rogers50b35e22012-10-04 10:09:15 -07001578 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001579 allow_new_monitors_ = false;
1580}
1581
1582void MonitorList::AllowNewMonitors() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001583 CHECK(!kUseReadBarrier);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001584 Thread* self = Thread::Current();
1585 MutexLock mu(self, monitor_list_lock_);
1586 allow_new_monitors_ = true;
1587 monitor_add_condition_.Broadcast(self);
1588}
1589
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001590void MonitorList::BroadcastForNewMonitors() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001591 Thread* self = Thread::Current();
1592 MutexLock mu(self, monitor_list_lock_);
1593 monitor_add_condition_.Broadcast(self);
1594}
1595
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001596void MonitorList::Add(Monitor* m) {
1597 Thread* self = Thread::Current();
1598 MutexLock mu(self, monitor_list_lock_);
Hiroshi Yamauchif1c6f872017-01-06 12:23:47 -08001599 // CMS needs this to block for concurrent reference processing because an object allocated during
1600 // the GC won't be marked and concurrent reference processing would incorrectly clear the JNI weak
1601 // ref. But CC (kUseReadBarrier == true) doesn't because of the to-space invariant.
1602 while (!kUseReadBarrier && UNLIKELY(!allow_new_monitors_)) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -07001603 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
1604 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -08001605 self->CheckEmptyCheckpointFromWeakRefAccess(&monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001606 monitor_add_condition_.WaitHoldingLocks(self);
1607 }
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001608 list_.push_front(m);
1609}
1610
Mathieu Chartier97509952015-07-13 14:35:43 -07001611void MonitorList::SweepMonitorList(IsMarkedVisitor* visitor) {
Andreas Gampe74240812014-04-17 10:35:09 -07001612 Thread* self = Thread::Current();
1613 MutexLock mu(self, monitor_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001614 for (auto it = list_.begin(); it != list_.end(); ) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001615 Monitor* m = *it;
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001616 // Disable the read barrier in GetObject() as this is called by GC.
Vladimir Markof52d92f2019-03-29 12:33:02 +00001617 ObjPtr<mirror::Object> obj = m->GetObject<kWithoutReadBarrier>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001618 // The object of a monitor can be null if we have deflated it.
Vladimir Markof52d92f2019-03-29 12:33:02 +00001619 ObjPtr<mirror::Object> new_obj = obj != nullptr ? visitor->IsMarked(obj.Ptr()) : nullptr;
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001620 if (new_obj == nullptr) {
1621 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001622 << obj;
Andreas Gampe74240812014-04-17 10:35:09 -07001623 MonitorPool::ReleaseMonitor(self, m);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001624 it = list_.erase(it);
1625 } else {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001626 m->SetObject(new_obj);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001627 ++it;
1628 }
1629 }
1630}
1631
Hans Boehm6fe97e02016-05-04 18:35:57 -07001632size_t MonitorList::Size() {
1633 Thread* self = Thread::Current();
1634 MutexLock mu(self, monitor_list_lock_);
1635 return list_.size();
1636}
1637
Mathieu Chartier97509952015-07-13 14:35:43 -07001638class MonitorDeflateVisitor : public IsMarkedVisitor {
1639 public:
1640 MonitorDeflateVisitor() : self_(Thread::Current()), deflate_count_(0) {}
1641
Roland Levillainf73caca2018-08-24 17:19:07 +01001642 mirror::Object* IsMarked(mirror::Object* object) override
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001643 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001644 if (Monitor::Deflate(self_, object)) {
1645 DCHECK_NE(object->GetLockWord(true).GetState(), LockWord::kFatLocked);
1646 ++deflate_count_;
1647 // If we deflated, return null so that the monitor gets removed from the array.
1648 return nullptr;
1649 }
1650 return object; // Monitor was not deflated.
1651 }
1652
1653 Thread* const self_;
1654 size_t deflate_count_;
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001655};
1656
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001657size_t MonitorList::DeflateMonitors() {
Mathieu Chartier97509952015-07-13 14:35:43 -07001658 MonitorDeflateVisitor visitor;
1659 Locks::mutator_lock_->AssertExclusiveHeld(visitor.self_);
1660 SweepMonitorList(&visitor);
1661 return visitor.deflate_count_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001662}
1663
Vladimir Markof52d92f2019-03-29 12:33:02 +00001664MonitorInfo::MonitorInfo(ObjPtr<mirror::Object> obj) : owner_(nullptr), entry_count_(0) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001665 DCHECK(obj != nullptr);
1666 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001667 switch (lock_word.GetState()) {
1668 case LockWord::kUnlocked:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001669 // Fall-through.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001670 case LockWord::kForwardingAddress:
1671 // Fall-through.
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001672 case LockWord::kHashCode:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001673 break;
1674 case LockWord::kThinLocked:
1675 owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
Alex Lightce568642017-09-05 16:54:25 -07001676 DCHECK(owner_ != nullptr) << "Thin-locked without owner!";
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001677 entry_count_ = 1 + lock_word.ThinLockCount();
1678 // Thin locks have no waiters.
1679 break;
1680 case LockWord::kFatLocked: {
1681 Monitor* mon = lock_word.FatLockMonitor();
1682 owner_ = mon->owner_;
Alex Lightce568642017-09-05 16:54:25 -07001683 // Here it is okay for the owner to be null since we don't reset the LockWord back to
1684 // kUnlocked until we get a GC. In cases where this hasn't happened yet we will have a fat
1685 // lock without an owner.
1686 if (owner_ != nullptr) {
1687 entry_count_ = 1 + mon->lock_count_;
1688 } else {
1689 DCHECK_EQ(mon->lock_count_, 0) << "Monitor is fat-locked without any owner!";
1690 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001691 for (Thread* waiter = mon->wait_set_; waiter != nullptr; waiter = waiter->GetWaitNext()) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001692 waiters_.push_back(waiter);
1693 }
1694 break;
Elliott Hughesf327e072013-01-09 16:01:26 -08001695 }
1696 }
1697}
1698
Elliott Hughes5f791332011-09-15 17:45:30 -07001699} // namespace art