blob: 0353efdfbcde7fed3e1ac965e43c34db7da14c71 [file] [log] [blame]
Elliott Hughes5f791332011-09-15 17:45:30 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Elliott Hughes54e7df12011-09-16 11:47:04 -070017#include "monitor.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070018
Elliott Hughes08fc03a2012-06-26 17:34:00 -070019#include <vector>
20
Andreas Gampe46ee31b2016-12-14 10:11:49 -080021#include "android-base/stringprintf.h"
22
Mathieu Chartiere401d142015-04-22 13:56:20 -070023#include "art_method-inl.h"
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
Ian Rogersef7d42f2014-01-06 12:55:46 -080092Monitor::Monitor(Thread* self, Thread* owner, 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 Munger1ebb52c2018-10-25 15:37:14 -0700100 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
115Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code,
116 MonitorId id)
117 : monitor_lock_("a monitor lock", kMonitorLock),
118 monitor_contenders_("monitor contenders", monitor_lock_),
119 num_waiters_(0),
120 owner_(owner),
121 lock_count_(0),
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700122 obj_(GcRoot<mirror::Object>(obj)),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700123 wait_set_(nullptr),
Charles Munger1ebb52c2018-10-25 15:37:14 -0700124 wake_set_(nullptr),
Andreas Gampe74240812014-04-17 10:35:09 -0700125 hash_code_(hash_code),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700126 locking_method_(nullptr),
Andreas Gampe74240812014-04-17 10:35:09 -0700127 locking_dex_pc_(0),
128 monitor_id_(id) {
129#ifdef __LP64__
130 next_free_ = nullptr;
131#endif
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700132 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
133 // with the owner unlocking the thin-lock.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800134 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700135 // The identity hash code is set for the life time of the monitor.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700136}
137
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700138int32_t Monitor::GetHashCode() {
Mathieu Chartier8bb3c682018-06-18 12:53:10 -0700139 int32_t hc = hash_code_.load(std::memory_order_relaxed);
140 if (!HasHashCode()) {
141 // Use a strong CAS to prevent spurious failures since these can make the boot image
142 // non-deterministic.
143 hash_code_.CompareAndSetStrongRelaxed(0, mirror::Object::GenerateIdentityHashCode());
144 hc = hash_code_.load(std::memory_order_relaxed);
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700145 }
146 DCHECK(HasHashCode());
Mathieu Chartier8bb3c682018-06-18 12:53:10 -0700147 return hc;
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700148}
149
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700150bool Monitor::Install(Thread* self) {
151 MutexLock mu(self, monitor_lock_); // Uncontended mutex acquisition as monitor isn't yet public.
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700152 CHECK(owner_ == nullptr || owner_ == self || owner_->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700153 // Propagate the lock state.
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700154 LockWord lw(GetObject()->GetLockWord(false));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700155 switch (lw.GetState()) {
156 case LockWord::kThinLocked: {
157 CHECK_EQ(owner_->GetThreadId(), lw.ThinLockOwner());
158 lock_count_ = lw.ThinLockCount();
159 break;
160 }
161 case LockWord::kHashCode: {
Orion Hodson88591fe2018-03-06 13:35:43 +0000162 CHECK_EQ(hash_code_.load(std::memory_order_relaxed), static_cast<int32_t>(lw.GetHashCode()));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700163 break;
164 }
165 case LockWord::kFatLocked: {
166 // The owner_ is suspended but another thread beat us to install a monitor.
167 return false;
168 }
169 case LockWord::kUnlocked: {
170 LOG(FATAL) << "Inflating unlocked lock word";
171 break;
172 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700173 default: {
174 LOG(FATAL) << "Invalid monitor state " << lw.GetState();
175 return false;
176 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700177 }
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700178 LockWord fat(this, lw.GCState());
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700179 // Publish the updated lock word, which may race with other threads.
Mathieu Chartier42c2e502018-06-19 12:30:56 -0700180 bool success = GetObject()->CasLockWord(lw, fat, CASMode::kWeak, std::memory_order_release);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700181 // Lock profiling.
Mathieu Chartier9728f912013-10-30 09:45:13 -0700182 if (success && owner_ != nullptr && lock_profiling_threshold_ != 0) {
Andreas Gampe6ec8ebd2014-07-25 13:36:56 -0700183 // Do not abort on dex pc errors. This can easily happen when we want to dump a stack trace on
184 // abort.
185 locking_method_ = owner_->GetCurrentMethod(&locking_dex_pc_, false);
Andreas Gampe5a387272017-11-06 19:47:16 -0800186 if (locking_method_ != nullptr && UNLIKELY(locking_method_->IsProxyMethod())) {
187 // Grab another frame. Proxy methods are not helpful for lock profiling. This should be rare
188 // enough that it's OK to walk the stack twice.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100189 struct NextMethodVisitor final : public StackVisitor {
Andreas Gampe5a387272017-11-06 19:47:16 -0800190 explicit NextMethodVisitor(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_)
191 : StackVisitor(thread,
192 nullptr,
193 StackVisitor::StackWalkKind::kIncludeInlinedFrames,
194 false),
195 count_(0),
196 method_(nullptr),
197 dex_pc_(0) {}
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100198 bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe5a387272017-11-06 19:47:16 -0800199 ArtMethod* m = GetMethod();
200 if (m->IsRuntimeMethod()) {
201 // Continue if this is a runtime method.
202 return true;
203 }
204 count_++;
205 if (count_ == 2u) {
206 method_ = m;
207 dex_pc_ = GetDexPc(false);
208 return false;
209 }
210 return true;
211 }
212 size_t count_;
213 ArtMethod* method_;
214 uint32_t dex_pc_;
215 };
216 NextMethodVisitor nmv(owner_);
217 nmv.WalkStack();
218 locking_method_ = nmv.method_;
219 locking_dex_pc_ = nmv.dex_pc_;
220 }
221 DCHECK(locking_method_ == nullptr || !locking_method_->IsProxyMethod());
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700222 }
223 return success;
Elliott Hughes5f791332011-09-15 17:45:30 -0700224}
225
226Monitor::~Monitor() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700227 // Deflated monitors have a null object.
Elliott Hughes5f791332011-09-15 17:45:30 -0700228}
229
Elliott Hughes5f791332011-09-15 17:45:30 -0700230void Monitor::AppendToWaitSet(Thread* thread) {
Charles Munger1ebb52c2018-10-25 15:37:14 -0700231 // Not checking that the owner is equal to this thread, since we've released
232 // the monitor by the time this method is called.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700233 DCHECK(thread != nullptr);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700234 DCHECK(thread->GetWaitNext() == nullptr) << thread->GetWaitNext();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700235 if (wait_set_ == nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700236 wait_set_ = thread;
237 return;
238 }
239
240 // push_back.
241 Thread* t = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700242 while (t->GetWaitNext() != nullptr) {
243 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700244 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700245 t->SetWaitNext(thread);
Elliott Hughes5f791332011-09-15 17:45:30 -0700246}
247
Elliott Hughes5f791332011-09-15 17:45:30 -0700248void Monitor::RemoveFromWaitSet(Thread *thread) {
249 DCHECK(owner_ == Thread::Current());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700250 DCHECK(thread != nullptr);
Charles Munger1ebb52c2018-10-25 15:37:14 -0700251 auto remove = [&](Thread*& set){
252 if (set != nullptr) {
253 if (set == thread) {
254 set = thread->GetWaitNext();
255 thread->SetWaitNext(nullptr);
256 return true;
257 }
258 Thread* t = set;
259 while (t->GetWaitNext() != nullptr) {
260 if (t->GetWaitNext() == thread) {
261 t->SetWaitNext(thread->GetWaitNext());
262 thread->SetWaitNext(nullptr);
263 return true;
264 }
265 t = t->GetWaitNext();
266 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700267 }
Charles Munger1ebb52c2018-10-25 15:37:14 -0700268 return false;
269 };
270 if (remove(wait_set_)) {
271 return;
Elliott Hughes5f791332011-09-15 17:45:30 -0700272 }
Charles Munger1ebb52c2018-10-25 15:37:14 -0700273 remove(wake_set_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700274}
275
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700276void Monitor::SetObject(mirror::Object* object) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700277 obj_ = GcRoot<mirror::Object>(object);
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700278}
279
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700280// Note: Adapted from CurrentMethodVisitor in thread.cc. We must not resolve here.
281
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100282struct NthCallerWithDexPcVisitor final : public StackVisitor {
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700283 explicit NthCallerWithDexPcVisitor(Thread* thread, size_t frame)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700284 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +0100285 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700286 method_(nullptr),
287 dex_pc_(0),
288 current_frame_number_(0),
289 wanted_frame_number_(frame) {}
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100290 bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700291 ArtMethod* m = GetMethod();
292 if (m == nullptr || m->IsRuntimeMethod()) {
293 // Runtime method, upcall, or resolution issue. Skip.
294 return true;
295 }
296
297 // Is this the requested frame?
298 if (current_frame_number_ == wanted_frame_number_) {
299 method_ = m;
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700300 dex_pc_ = GetDexPc(/* abort_on_failure=*/ false);
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700301 return false;
302 }
303
304 // Look for more.
305 current_frame_number_++;
306 return true;
307 }
308
309 ArtMethod* method_;
310 uint32_t dex_pc_;
311
312 private:
313 size_t current_frame_number_;
314 const size_t wanted_frame_number_;
315};
316
317// This function is inlined and just helps to not have the VLOG and ATRACE check at all the
318// potential tracing points.
319void Monitor::AtraceMonitorLock(Thread* self, mirror::Object* obj, bool is_wait) {
320 if (UNLIKELY(VLOG_IS_ON(systrace_lock_logging) && ATRACE_ENABLED())) {
321 AtraceMonitorLockImpl(self, obj, is_wait);
322 }
323}
324
325void Monitor::AtraceMonitorLockImpl(Thread* self, mirror::Object* obj, bool is_wait) {
326 // Wait() requires a deeper call stack to be useful. Otherwise you'll see "Waiting at
327 // Object.java". Assume that we'll wait a nontrivial amount, so it's OK to do a longer
328 // stack walk than if !is_wait.
329 NthCallerWithDexPcVisitor visitor(self, is_wait ? 1U : 0U);
330 visitor.WalkStack(false);
331 const char* prefix = is_wait ? "Waiting on " : "Locking ";
332
333 const char* filename;
334 int32_t line_number;
335 TranslateLocation(visitor.method_, visitor.dex_pc_, &filename, &line_number);
336
337 // It would be nice to have a stable "ID" for the object here. However, the only stable thing
338 // would be the identity hashcode. But we cannot use IdentityHashcode here: For one, there are
339 // times when it is unsafe to make that call (see stack dumping for an explanation). More
340 // importantly, we would have to give up on thin-locking when adding systrace locks, as the
341 // identity hashcode is stored in the lockword normally (so can't be used with thin-locks).
342 //
343 // Because of thin-locks we also cannot use the monitor id (as there is no monitor). Monitor ids
344 // also do not have to be stable, as the monitor may be deflated.
345 std::string tmp = StringPrintf("%s %d at %s:%d",
346 prefix,
347 (obj == nullptr ? -1 : static_cast<int32_t>(reinterpret_cast<uintptr_t>(obj))),
348 (filename != nullptr ? filename : "null"),
349 line_number);
350 ATRACE_BEGIN(tmp.c_str());
351}
352
353void Monitor::AtraceMonitorUnlock() {
354 if (UNLIKELY(VLOG_IS_ON(systrace_lock_logging))) {
355 ATRACE_END();
356 }
357}
358
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700359std::string Monitor::PrettyContentionInfo(const std::string& owner_name,
360 pid_t owner_tid,
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700361 ArtMethod* owners_method,
362 uint32_t owners_dex_pc,
363 size_t num_waiters) {
Hiroshi Yamauchi71cd68d2017-01-25 18:28:12 -0800364 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700365 const char* owners_filename;
Goran Jakovljevic49c882b2016-04-19 10:27:21 +0200366 int32_t owners_line_number = 0;
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700367 if (owners_method != nullptr) {
368 TranslateLocation(owners_method, owners_dex_pc, &owners_filename, &owners_line_number);
369 }
370 std::ostringstream oss;
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700371 oss << "monitor contention with owner " << owner_name << " (" << owner_tid << ")";
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700372 if (owners_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700373 oss << " at " << owners_method->PrettyMethod();
Mathieu Chartier36891fe2016-04-28 17:21:08 -0700374 oss << "(" << owners_filename << ":" << owners_line_number << ")";
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700375 }
376 oss << " waiters=" << num_waiters;
377 return oss.str();
378}
379
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700380bool Monitor::TryLockLocked(Thread* self) {
381 if (owner_ == nullptr) { // Unowned.
382 owner_ = self;
383 CHECK_EQ(lock_count_, 0);
384 // When debugging, save the current monitor holder for future
385 // acquisition failures to use in sampled logging.
386 if (lock_profiling_threshold_ != 0) {
387 locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
Andreas Gampe5a387272017-11-06 19:47:16 -0800388 // We don't expect a proxy method here.
389 DCHECK(locking_method_ == nullptr || !locking_method_->IsProxyMethod());
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700390 }
391 } else if (owner_ == self) { // Recursive.
392 lock_count_++;
393 } else {
394 return false;
395 }
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700396 AtraceMonitorLock(self, GetObject(), /* is_wait= */ false);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700397 return true;
398}
399
400bool Monitor::TryLock(Thread* self) {
401 MutexLock mu(self, monitor_lock_);
402 return TryLockLocked(self);
403}
404
Alex Light77fee872017-09-05 14:51:49 -0700405// Asserts that a mutex isn't held when the class comes into and out of scope.
406class ScopedAssertNotHeld {
407 public:
408 ScopedAssertNotHeld(Thread* self, Mutex& mu) : self_(self), mu_(mu) {
409 mu_.AssertNotHeld(self_);
410 }
411
412 ~ScopedAssertNotHeld() {
413 mu_.AssertNotHeld(self_);
414 }
415
416 private:
417 Thread* const self_;
418 Mutex& mu_;
419 DISALLOW_COPY_AND_ASSIGN(ScopedAssertNotHeld);
420};
421
422template <LockReason reason>
Elliott Hughes5f791332011-09-15 17:45:30 -0700423void Monitor::Lock(Thread* self) {
Alex Light77fee872017-09-05 14:51:49 -0700424 ScopedAssertNotHeld sanh(self, monitor_lock_);
425 bool called_monitors_callback = false;
426 monitor_lock_.Lock(self);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700427 while (true) {
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700428 if (TryLockLocked(self)) {
Alex Light77fee872017-09-05 14:51:49 -0700429 break;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700430 }
431 // Contended.
432 const bool log_contention = (lock_profiling_threshold_ != 0);
Xin Guanb894a192014-08-22 11:55:37 -0500433 uint64_t wait_start_ms = log_contention ? MilliTime() : 0;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700434 ArtMethod* owners_method = locking_method_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700435 uint32_t owners_dex_pc = locking_dex_pc_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700436 // Do this before releasing the lock so that we don't get deflated.
Mathieu Chartierb9001ab2014-10-03 13:28:46 -0700437 size_t num_waiters = num_waiters_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700438 ++num_waiters_;
Andreas Gampe2702d562017-02-06 09:48:00 -0800439
440 // If systrace logging is enabled, first look at the lock owner. Acquiring the monitor's
441 // lock and then re-acquiring the mutator lock can deadlock.
442 bool started_trace = false;
443 if (ATRACE_ENABLED()) {
444 if (owner_ != nullptr) { // Did the owner_ give the lock up?
445 std::ostringstream oss;
446 std::string name;
447 owner_->GetThreadName(name);
448 oss << PrettyContentionInfo(name,
449 owner_->GetTid(),
450 owners_method,
451 owners_dex_pc,
452 num_waiters);
453 // Add info for contending thread.
454 uint32_t pc;
455 ArtMethod* m = self->GetCurrentMethod(&pc);
456 const char* filename;
457 int32_t line_number;
458 TranslateLocation(m, pc, &filename, &line_number);
459 oss << " blocking from "
460 << ArtMethod::PrettyMethod(m) << "(" << (filename != nullptr ? filename : "null")
461 << ":" << line_number << ")";
462 ATRACE_BEGIN(oss.str().c_str());
463 started_trace = true;
464 }
465 }
466
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700467 monitor_lock_.Unlock(self); // Let go of locks in order.
Alex Light77fee872017-09-05 14:51:49 -0700468 // Call the contended locking cb once and only once. Also only call it if we are locking for
469 // the first time, not during a Wait wakeup.
470 if (reason == LockReason::kForLock && !called_monitors_callback) {
471 called_monitors_callback = true;
472 Runtime::Current()->GetRuntimeCallbacks()->MonitorContendedLocking(this);
473 }
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700474 self->SetMonitorEnterObject(GetObject());
Elliott Hughes5f791332011-09-15 17:45:30 -0700475 {
Hiroshi Yamauchi71cd68d2017-01-25 18:28:12 -0800476 ScopedThreadSuspension tsc(self, kBlocked); // Change to blocked and give up mutator_lock_.
Andreas Gampe2702d562017-02-06 09:48:00 -0800477 uint32_t original_owner_thread_id = 0u;
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700478 {
479 // Reacquire monitor_lock_ without mutator_lock_ for Wait.
480 MutexLock mu2(self, monitor_lock_);
481 if (owner_ != nullptr) { // Did the owner_ give the lock up?
482 original_owner_thread_id = owner_->GetThreadId();
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700483 monitor_contenders_.Wait(self); // Still contended so wait.
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800484 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700485 }
486 if (original_owner_thread_id != 0u) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700487 // Woken from contention.
488 if (log_contention) {
Andreas Gampe111b1092017-06-22 20:28:23 -0700489 uint64_t wait_ms = MilliTime() - wait_start_ms;
490 uint32_t sample_percent;
491 if (wait_ms >= lock_profiling_threshold_) {
492 sample_percent = 100;
493 } else {
494 sample_percent = 100 * wait_ms / lock_profiling_threshold_;
495 }
496 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
497 // Reacquire mutator_lock_ for logging.
498 ScopedObjectAccess soa(self);
Andreas Gampe111b1092017-06-22 20:28:23 -0700499
Andreas Gamped0210e52017-06-23 13:38:09 -0700500 bool owner_alive = false;
501 pid_t original_owner_tid = 0;
502 std::string original_owner_name;
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700503
Andreas Gamped0210e52017-06-23 13:38:09 -0700504 const bool should_dump_stacks = stack_dump_lock_profiling_threshold_ > 0 &&
505 wait_ms > stack_dump_lock_profiling_threshold_;
506 std::string owner_stack_dump;
Andreas Gampe111b1092017-06-22 20:28:23 -0700507
Andreas Gamped0210e52017-06-23 13:38:09 -0700508 // Acquire thread-list lock to find thread and keep it from dying until we've got all
509 // the info we need.
510 {
Alex Lightb1e31a82017-10-04 16:57:36 -0700511 Locks::thread_list_lock_->ExclusiveLock(Thread::Current());
Andreas Gamped0210e52017-06-23 13:38:09 -0700512
513 // Re-find the owner in case the thread got killed.
514 Thread* original_owner = Runtime::Current()->GetThreadList()->FindThreadByThreadId(
515 original_owner_thread_id);
516
517 if (original_owner != nullptr) {
518 owner_alive = true;
519 original_owner_tid = original_owner->GetTid();
520 original_owner->GetThreadName(original_owner_name);
521
522 if (should_dump_stacks) {
523 // Very long contention. Dump stacks.
524 struct CollectStackTrace : public Closure {
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100525 void Run(art::Thread* thread) override
Andreas Gamped0210e52017-06-23 13:38:09 -0700526 REQUIRES_SHARED(art::Locks::mutator_lock_) {
527 thread->DumpJavaStack(oss);
528 }
529
530 std::ostringstream oss;
531 };
532 CollectStackTrace owner_trace;
Alex Lightb1e31a82017-10-04 16:57:36 -0700533 // RequestSynchronousCheckpoint releases the thread_list_lock_ as a part of its
534 // execution.
Andreas Gamped0210e52017-06-23 13:38:09 -0700535 original_owner->RequestSynchronousCheckpoint(&owner_trace);
536 owner_stack_dump = owner_trace.oss.str();
Alex Lightb1e31a82017-10-04 16:57:36 -0700537 } else {
538 Locks::thread_list_lock_->ExclusiveUnlock(Thread::Current());
Andreas Gamped0210e52017-06-23 13:38:09 -0700539 }
Alex Lightb1e31a82017-10-04 16:57:36 -0700540 } else {
541 Locks::thread_list_lock_->ExclusiveUnlock(Thread::Current());
Andreas Gamped0210e52017-06-23 13:38:09 -0700542 }
543 // This is all the data we need. Now drop the thread-list lock, it's OK for the
544 // owner to go away now.
545 }
546
547 // If we found the owner (and thus have owner data), go and log now.
548 if (owner_alive) {
549 // Give the detailed traces for really long contention.
550 if (should_dump_stacks) {
551 // This must be here (and not above) because we cannot hold the thread-list lock
552 // while running the checkpoint.
553 std::ostringstream self_trace_oss;
554 self->DumpJavaStack(self_trace_oss);
555
556 uint32_t pc;
557 ArtMethod* m = self->GetCurrentMethod(&pc);
558
559 LOG(WARNING) << "Long "
560 << PrettyContentionInfo(original_owner_name,
561 original_owner_tid,
562 owners_method,
563 owners_dex_pc,
564 num_waiters)
565 << " in " << ArtMethod::PrettyMethod(m) << " for "
566 << PrettyDuration(MsToNs(wait_ms)) << "\n"
567 << "Current owner stack:\n" << owner_stack_dump
568 << "Contender stack:\n" << self_trace_oss.str();
569 } else if (wait_ms > kLongWaitMs && owners_method != nullptr) {
Mathieu Chartier36891fe2016-04-28 17:21:08 -0700570 uint32_t pc;
571 ArtMethod* m = self->GetCurrentMethod(&pc);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700572 // TODO: We should maybe check that original_owner is still a live thread.
573 LOG(WARNING) << "Long "
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700574 << PrettyContentionInfo(original_owner_name,
575 original_owner_tid,
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700576 owners_method,
577 owners_dex_pc,
578 num_waiters)
David Sehr709b0702016-10-13 09:12:37 -0700579 << " in " << ArtMethod::PrettyMethod(m) << " for "
580 << PrettyDuration(MsToNs(wait_ms));
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700581 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700582 LogContentionEvent(self,
Alex Light77fee872017-09-05 14:51:49 -0700583 wait_ms,
584 sample_percent,
585 owners_method,
586 owners_dex_pc);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700587 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700588 }
589 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700590 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700591 }
Andreas Gampe2702d562017-02-06 09:48:00 -0800592 if (started_trace) {
593 ATRACE_END();
594 }
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700595 self->SetMonitorEnterObject(nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700596 monitor_lock_.Lock(self); // Reacquire locks in order.
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700597 --num_waiters_;
Elliott Hughesfc861622011-10-17 17:57:47 -0700598 }
Alex Light77fee872017-09-05 14:51:49 -0700599 monitor_lock_.Unlock(self);
600 // We need to pair this with a single contended locking call. NB we match the RI behavior and call
601 // this even if MonitorEnter failed.
602 if (called_monitors_callback) {
603 CHECK(reason == LockReason::kForLock);
604 Runtime::Current()->GetRuntimeCallbacks()->MonitorContendedLocked(this);
605 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700606}
607
Alex Light77fee872017-09-05 14:51:49 -0700608template void Monitor::Lock<LockReason::kForLock>(Thread* self);
609template void Monitor::Lock<LockReason::kForWait>(Thread* self);
610
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800611static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
612 __attribute__((format(printf, 1, 2)));
613
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700614static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700615 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800616 va_list args;
617 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800618 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000619 self->ThrowNewExceptionV("Ljava/lang/IllegalMonitorStateException;", fmt, args);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700620 if (!Runtime::Current()->IsStarted() || VLOG_IS_ON(monitor)) {
Brian Carlstrom64277f32012-03-26 23:53:34 -0700621 std::ostringstream ss;
Ian Rogers62d6c772013-02-27 08:32:07 -0800622 self->Dump(ss);
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700623 LOG(Runtime::Current()->IsStarted() ? ::android::base::INFO : ::android::base::ERROR)
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000624 << self->GetException()->Dump() << "\n" << ss.str();
Brian Carlstrom64277f32012-03-26 23:53:34 -0700625 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800626 va_end(args);
627}
628
Elliott Hughesd4237412012-02-21 11:24:45 -0800629static std::string ThreadToString(Thread* thread) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700630 if (thread == nullptr) {
631 return "nullptr";
Elliott Hughesd4237412012-02-21 11:24:45 -0800632 }
633 std::ostringstream oss;
634 // TODO: alternatively, we could just return the thread's name.
635 oss << *thread;
636 return oss.str();
637}
638
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700639void Monitor::FailedUnlock(mirror::Object* o,
640 uint32_t expected_owner_thread_id,
641 uint32_t found_owner_thread_id,
Elliott Hughesffb465f2012-03-01 18:46:05 -0800642 Monitor* monitor) {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700643 // Acquire thread list lock so threads won't disappear from under us.
Elliott Hughesffb465f2012-03-01 18:46:05 -0800644 std::string current_owner_string;
645 std::string expected_owner_string;
646 std::string found_owner_string;
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700647 uint32_t current_owner_thread_id = 0u;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800648 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700649 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700650 ThreadList* const thread_list = Runtime::Current()->GetThreadList();
651 Thread* expected_owner = thread_list->FindThreadByThreadId(expected_owner_thread_id);
652 Thread* found_owner = thread_list->FindThreadByThreadId(found_owner_thread_id);
653
Elliott Hughesffb465f2012-03-01 18:46:05 -0800654 // Re-read owner now that we hold lock.
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700655 Thread* current_owner = (monitor != nullptr) ? monitor->GetOwner() : nullptr;
656 if (current_owner != nullptr) {
657 current_owner_thread_id = current_owner->GetThreadId();
658 }
Elliott Hughesffb465f2012-03-01 18:46:05 -0800659 // Get short descriptions of the threads involved.
660 current_owner_string = ThreadToString(current_owner);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700661 expected_owner_string = expected_owner != nullptr ? ThreadToString(expected_owner) : "unnamed";
662 found_owner_string = found_owner != nullptr ? ThreadToString(found_owner) : "unnamed";
Elliott Hughesffb465f2012-03-01 18:46:05 -0800663 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700664
665 if (current_owner_thread_id == 0u) {
666 if (found_owner_thread_id == 0u) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800667 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
668 " on thread '%s'",
David Sehr709b0702016-10-13 09:12:37 -0700669 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800670 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800671 } else {
672 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800673 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
674 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800675 found_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700676 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800677 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800678 }
679 } else {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700680 if (found_owner_thread_id == 0u) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800681 // Race: originally there was no owner, there is now
682 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
683 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800684 current_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700685 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800686 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800687 } else {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700688 if (found_owner_thread_id != current_owner_thread_id) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800689 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800690 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
691 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800692 found_owner_string.c_str(),
693 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 } else {
697 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
698 " on thread '%s",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800699 current_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700700 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800701 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800702 }
703 }
704 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700705}
706
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700707bool Monitor::Unlock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700708 DCHECK(self != nullptr);
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700709 uint32_t owner_thread_id = 0u;
Charles Munger1ebb52c2018-10-25 15:37:14 -0700710 DCHECK(!monitor_lock_.IsExclusiveHeld(self));
711 monitor_lock_.Lock(self);
712 Thread* owner = owner_;
713 if (owner != nullptr) {
714 owner_thread_id = owner->GetThreadId();
715 }
716 if (owner == self) {
717 // We own the monitor, so nobody else can be in here.
718 AtraceMonitorUnlock();
719 if (lock_count_ == 0) {
720 owner_ = nullptr;
721 locking_method_ = nullptr;
722 locking_dex_pc_ = 0;
723 SignalContendersAndReleaseMonitorLock(self);
724 return true;
725 } else {
726 --lock_count_;
727 monitor_lock_.Unlock(self);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700728 return true;
Elliott Hughes5f791332011-09-15 17:45:30 -0700729 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700730 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700731 // We don't own this, so we're not allowed to unlock it.
732 // The JNI spec says that we should throw IllegalMonitorStateException in this case.
733 FailedUnlock(GetObject(), self->GetThreadId(), owner_thread_id, this);
Charles Munger1ebb52c2018-10-25 15:37:14 -0700734 monitor_lock_.Unlock(self);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700735 return false;
Elliott Hughes5f791332011-09-15 17:45:30 -0700736}
737
Charles Munger1ebb52c2018-10-25 15:37:14 -0700738void Monitor::SignalContendersAndReleaseMonitorLock(Thread* self) {
739 // We want to signal one thread to wake up, to acquire the monitor that
740 // we are releasing. This could either be a Thread waiting on its own
741 // ConditionVariable, or a thread waiting on monitor_contenders_.
742 while (true) {
743 Thread* thread = wake_set_;
744 if (thread == nullptr) {
745 break;
746 } else if (thread == self) {
747 // In the case of wait(), this will be invoked with self's GetWaitMutex held.
748 // On a second run through this while loop, we will have released and reacquired
749 // monitor_lock_, so it is possible that self has moved into wake_set. Since we
750 // don't want to signal ourselves before waiting or recursively acquire GetWaitMutex,
751 // skip ourself if we encounter it while traversing the wake set.
752 thread = self->GetWaitNext();
753 if (thread == nullptr) {
754 break;
755 }
756 self->SetWaitNext(thread->GetWaitNext());
757 } else {
758 wake_set_ = thread->GetWaitNext();
759 }
760 thread->SetWaitNext(nullptr);
761
762 // Release the lock, so that a potentially awakened thread will not
763 // immediately contend on it.
764 monitor_lock_.Unlock(self);
765 // Check to see if the thread is still waiting.
766 {
767 // In the case of wait(), we'll be acquiring another thread's GetWaitMutex with
768 // self's GetWaitMutex held. This does not risk deadlock, because we only acquire this lock
769 // for threads in the wake_set_. A thread can only enter wake_set_ from Notify or NotifyAll,
770 // and those acquire each thread's GetWaitMutex before moving them. Thus, the threads whose
771 // wait mutexes we acquire here must have already been released from wait(), so there is no
772 // risk of the following lock ordering leading to deadlock:
773 // Thread 1 waits
774 // Thread 2 waits
775 // While threads 1 and 2 have released both the monitor and the monitor_lock_, thread 3 calls
776 // notify() to wake them both up.
777 // Thread 1 enters this block, and attempts to acquire Thread 2's GetWaitMutex to wake it
778 // Thread 2 enters this block, and attempts to acquire Thread 1's GetWaitMutex to wake it
779 //
780 // Thanks to the lock checking in Notify and NotifyAll, no thread is observable in wake_set_
781 // unless that thread has actually started waiting (and therefore will not subsequently
782 // acquire another thread's GetWaitMutex while holding its own).
783 MutexLock wait_mu(self, *thread->GetWaitMutex());
784 if (thread->GetWaitMonitor() != nullptr) {
785 thread->GetWaitConditionVariable()->Signal(self);
786 return;
787 }
788 }
789 // Reacquire the lock for the next iteration
790 monitor_lock_.Lock(self);
791 // We had to reacquire the lock so that we can wake a contender, or look
792 // for another notified waiter thread, but if someone else has already acquired our
793 // monitor, there's no need to wake anybody else as they'll just contend
794 // with the current owner.
795 if (owner_ != nullptr) {
796 monitor_lock_.Unlock(self);
797 return;
798 }
799 }
800 // If we didn't wake any threads that were originally waiting on us,
801 // wake a contender.
802 monitor_contenders_.Signal(self);
803 monitor_lock_.Unlock(self);
804}
805
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800806void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
807 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700808 DCHECK(self != nullptr);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800809 DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
Elliott Hughes5f791332011-09-15 17:45:30 -0700810
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700811 monitor_lock_.Lock(self);
812
Elliott Hughes5f791332011-09-15 17:45:30 -0700813 // Make sure that we hold the lock.
814 if (owner_ != self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700815 monitor_lock_.Unlock(self);
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700816 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700817 return;
818 }
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800819
Elliott Hughesdf42c482013-01-09 12:49:02 -0800820 // We need to turn a zero-length timed wait into a regular wait because
821 // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
822 if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
823 why = kWaiting;
824 }
825
Elliott Hughes5f791332011-09-15 17:45:30 -0700826 // Enforce the timeout range.
827 if (ms < 0 || ns < 0 || ns > 999999) {
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700828 monitor_lock_.Unlock(self);
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000829 self->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
Ian Rogersef7d42f2014-01-06 12:55:46 -0800830 "timeout arguments out of range: ms=%" PRId64 " ns=%d", ms, ns);
Elliott Hughes5f791332011-09-15 17:45:30 -0700831 return;
832 }
833
Elliott Hughes5f791332011-09-15 17:45:30 -0700834 /*
Charles Munger1ebb52c2018-10-25 15:37:14 -0700835 * Release our hold - we need to let it go even if we're a few levels
Elliott Hughes5f791332011-09-15 17:45:30 -0700836 * deep in a recursive lock, and we need to restore that later.
Elliott Hughes5f791332011-09-15 17:45:30 -0700837 */
Ian Rogers0399dde2012-06-06 17:09:28 -0700838 int prev_lock_count = lock_count_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700839 lock_count_ = 0;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700840 owner_ = nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700841 ArtMethod* saved_method = locking_method_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700842 locking_method_ = nullptr;
Ian Rogers0399dde2012-06-06 17:09:28 -0700843 uintptr_t saved_dex_pc = locking_dex_pc_;
844 locking_dex_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700845
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700846 AtraceMonitorUnlock(); // For the implict Unlock() just above. This will only end the deepest
847 // nesting, but that is enough for the visualization, and corresponds to
848 // the single Lock() we do afterwards.
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700849 AtraceMonitorLock(self, GetObject(), /* is_wait= */ true);
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700850
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800851 bool was_interrupted = false;
Alex Light77fee872017-09-05 14:51:49 -0700852 bool timed_out = false;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700853 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700854 // Update thread state. If the GC wakes up, it'll ignore us, knowing
855 // that we won't touch any references in this state, and we'll check
856 // our suspend mode before we transition out.
857 ScopedThreadSuspension sts(self, why);
858
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700859 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700860 MutexLock mu(self, *self->GetWaitMutex());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700861
Charles Munger1ebb52c2018-10-25 15:37:14 -0700862 /*
863 * Add ourselves to the set of threads waiting on this monitor.
864 * It's important that we are only added to the wait set after
865 * acquiring our GetWaitMutex, so that calls to Notify() that occur after we
866 * have released monitor_lock_ will not move us from wait_set_ to wake_set_
867 * until we've signalled contenders on this monitor.
868 */
869 AppendToWaitSet(self);
870 ++num_waiters_;
871
872
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700873 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700874 // non-null a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700875 // up.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700876 DCHECK(self->GetWaitMonitor() == nullptr);
877 self->SetWaitMonitor(this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700878
879 // Release the monitor lock.
Charles Munger1ebb52c2018-10-25 15:37:14 -0700880 SignalContendersAndReleaseMonitorLock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700881
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800882 // Handle the case where the thread was interrupted before we called wait().
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000883 if (self->IsInterrupted()) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800884 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700885 } else {
886 // Wait for a notification or a timeout to occur.
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800887 if (why == kWaiting) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700888 self->GetWaitConditionVariable()->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700889 } else {
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800890 DCHECK(why == kTimedWaiting || why == kSleeping) << why;
Alex Light77fee872017-09-05 14:51:49 -0700891 timed_out = self->GetWaitConditionVariable()->TimedWait(self, ms, ns);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700892 }
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000893 was_interrupted = self->IsInterrupted();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700894 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700895 }
896
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800897 {
898 // We reset the thread's wait_monitor_ field after transitioning back to runnable so
899 // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
900 // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
901 // are waiting on "null".)
Ian Rogersdd7624d2014-03-14 17:43:00 -0700902 MutexLock mu(self, *self->GetWaitMutex());
903 DCHECK(self->GetWaitMonitor() != nullptr);
904 self->SetWaitMonitor(nullptr);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800905 }
906
Mathieu Chartierdaed5d82016-03-10 10:49:35 -0800907 // Allocate the interrupted exception not holding the monitor lock since it may cause a GC.
908 // If the GC requires acquiring the monitor for enqueuing cleared references, this would
909 // cause a deadlock if the monitor is held.
910 if (was_interrupted && interruptShouldThrow) {
911 /*
912 * We were interrupted while waiting, or somebody interrupted an
913 * un-interruptible thread earlier and we're bailing out immediately.
914 *
915 * The doc sayeth: "The interrupted status of the current thread is
916 * cleared when this exception is thrown."
917 */
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000918 self->SetInterrupted(false);
Mathieu Chartierdaed5d82016-03-10 10:49:35 -0800919 self->ThrowNewException("Ljava/lang/InterruptedException;", nullptr);
920 }
921
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700922 AtraceMonitorUnlock(); // End Wait().
923
Alex Light77fee872017-09-05 14:51:49 -0700924 // We just slept, tell the runtime callbacks about this.
925 Runtime::Current()->GetRuntimeCallbacks()->MonitorWaitFinished(this, timed_out);
926
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700927 // Re-acquire the monitor and lock.
Alex Light77fee872017-09-05 14:51:49 -0700928 Lock<LockReason::kForWait>(self);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700929 monitor_lock_.Lock(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700930 self->GetWaitMutex()->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700931
Elliott Hughes5f791332011-09-15 17:45:30 -0700932 /*
933 * We remove our thread from wait set after restoring the count
934 * and owner fields so the subroutine can check that the calling
935 * thread owns the monitor. Aside from that, the order of member
936 * updates is not order sensitive as we hold the pthread mutex.
937 */
938 owner_ = self;
Ian Rogers0399dde2012-06-06 17:09:28 -0700939 lock_count_ = prev_lock_count;
940 locking_method_ = saved_method;
941 locking_dex_pc_ = saved_dex_pc;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700942 --num_waiters_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700943 RemoveFromWaitSet(self);
944
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700945 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700946}
947
948void Monitor::Notify(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700949 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700950 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700951 // Make sure that we hold the lock.
952 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800953 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700954 return;
955 }
Charles Munger1ebb52c2018-10-25 15:37:14 -0700956 // Move one thread from waiters to wake set
957 Thread* to_move = wait_set_;
958 if (to_move != nullptr) {
959 // Acquiring the thread's wait mutex before moving it prevents us from moving a thread that
960 // has released monitor_lock_ in wait() but not yet tried to wake an entry in wake_set_. See
961 // comments in SignalContendersAndReleaseMonitorLock.
962 MutexLock wait(self, *to_move->GetWaitMutex());
963 wait_set_ = to_move->GetWaitNext();
964 to_move->SetWaitNext(wake_set_);
965 wake_set_ = to_move;
Elliott Hughes5f791332011-09-15 17:45:30 -0700966 }
967}
968
969void Monitor::NotifyAll(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700970 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700971 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700972 // Make sure that we hold the lock.
973 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800974 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700975 return;
976 }
Charles Munger1ebb52c2018-10-25 15:37:14 -0700977
978 // Move all threads from waiters to wake set
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700979 while (wait_set_ != nullptr) {
Charles Munger1ebb52c2018-10-25 15:37:14 -0700980 Thread* to_move = wait_set_;
981 // Acquiring the thread's wait mutex before moving it prevents us from moving a thread that
982 // has released monitor_lock_ in wait() but not yet tried to wake an entry in wake_set_. See
983 // comments in SignalContendersAndReleaseMonitorLock.
984 MutexLock wait(self, *to_move->GetWaitMutex());
985 wait_set_ = to_move->GetWaitNext();
986 to_move->SetWaitNext(wake_set_);
987 wake_set_ = to_move;
Elliott Hughes5f791332011-09-15 17:45:30 -0700988 }
989}
990
Mathieu Chartier590fee92013-09-13 13:46:47 -0700991bool Monitor::Deflate(Thread* self, mirror::Object* obj) {
992 DCHECK(obj != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700993 // Don't need volatile since we only deflate with mutators suspended.
994 LockWord lw(obj->GetLockWord(false));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700995 // If the lock isn't an inflated monitor, then we don't need to deflate anything.
996 if (lw.GetState() == LockWord::kFatLocked) {
997 Monitor* monitor = lw.FatLockMonitor();
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700998 DCHECK(monitor != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700999 MutexLock mu(self, monitor->monitor_lock_);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001000 // Can't deflate if we have anybody waiting on the CV.
1001 if (monitor->num_waiters_ > 0) {
1002 return false;
1003 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001004 Thread* owner = monitor->owner_;
1005 if (owner != nullptr) {
1006 // Can't deflate if we are locked and have a hash code.
1007 if (monitor->HasHashCode()) {
1008 return false;
1009 }
1010 // Can't deflate if our lock count is too high.
Mathieu Chartier1cf194f2016-11-01 20:13:24 -07001011 if (static_cast<uint32_t>(monitor->lock_count_) > LockWord::kThinLockMaxCount) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001012 return false;
1013 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001014 // Deflate to a thin lock.
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001015 LockWord new_lw = LockWord::FromThinLockId(owner->GetThreadId(),
1016 monitor->lock_count_,
1017 lw.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001018 // Assume no concurrent read barrier state changes as mutators are suspended.
1019 obj->SetLockWord(new_lw, false);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001020 VLOG(monitor) << "Deflated " << obj << " to thin lock " << owner->GetTid() << " / "
1021 << monitor->lock_count_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001022 } else if (monitor->HasHashCode()) {
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001023 LockWord new_lw = LockWord::FromHashCode(monitor->GetHashCode(), lw.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001024 // Assume no concurrent read barrier state changes as mutators are suspended.
1025 obj->SetLockWord(new_lw, false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001026 VLOG(monitor) << "Deflated " << obj << " to hash monitor " << monitor->GetHashCode();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001027 } else {
1028 // No lock and no hash, just put an empty lock word inside the object.
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001029 LockWord new_lw = LockWord::FromDefault(lw.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001030 // Assume no concurrent read barrier state changes as mutators are suspended.
1031 obj->SetLockWord(new_lw, false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001032 VLOG(monitor) << "Deflated" << obj << " to empty lock word";
Mathieu Chartier590fee92013-09-13 13:46:47 -07001033 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001034 // 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 -07001035 // next GC.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001036 monitor->obj_ = GcRoot<mirror::Object>(nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001037 }
1038 return true;
1039}
1040
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001041void Monitor::Inflate(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code) {
Andreas Gampe74240812014-04-17 10:35:09 -07001042 DCHECK(self != nullptr);
1043 DCHECK(obj != nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -07001044 // Allocate and acquire a new monitor.
Andreas Gampe74240812014-04-17 10:35:09 -07001045 Monitor* m = MonitorPool::CreateMonitor(self, owner, obj, hash_code);
1046 DCHECK(m != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001047 if (m->Install(self)) {
Haifeng Li86ab7912014-05-16 10:47:59 +08001048 if (owner != nullptr) {
1049 VLOG(monitor) << "monitor: thread" << owner->GetThreadId()
Andreas Gampe74240812014-04-17 10:35:09 -07001050 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +08001051 } else {
1052 VLOG(monitor) << "monitor: Inflate with hashcode " << hash_code
Andreas Gampe74240812014-04-17 10:35:09 -07001053 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +08001054 }
Andreas Gampe74240812014-04-17 10:35:09 -07001055 Runtime::Current()->GetMonitorList()->Add(m);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001056 CHECK_EQ(obj->GetLockWord(true).GetState(), LockWord::kFatLocked);
Andreas Gampe74240812014-04-17 10:35:09 -07001057 } else {
1058 MonitorPool::ReleaseMonitor(self, m);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001059 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001060}
1061
Mathieu Chartier0cd81352014-05-22 16:48:55 -07001062void Monitor::InflateThinLocked(Thread* self, Handle<mirror::Object> obj, LockWord lock_word,
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001063 uint32_t hash_code) {
1064 DCHECK_EQ(lock_word.GetState(), LockWord::kThinLocked);
1065 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1066 if (owner_thread_id == self->GetThreadId()) {
1067 // We own the monitor, we can easily inflate it.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001068 Inflate(self, self, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001069 } else {
1070 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1071 // Suspend the owner, inflate. First change to blocked and give up mutator_lock_.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001072 self->SetMonitorEnterObject(obj.Get());
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -07001073 bool timed_out;
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07001074 Thread* owner;
1075 {
Alex Light77fee872017-09-05 14:51:49 -07001076 ScopedThreadSuspension sts(self, kWaitingForLockInflation);
Alex Light46f93402017-06-29 11:59:50 -07001077 owner = thread_list->SuspendThreadByThreadId(owner_thread_id,
1078 SuspendReason::kInternal,
1079 &timed_out);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07001080 }
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -07001081 if (owner != nullptr) {
1082 // We succeeded in suspending the thread, check the lock's status didn't change.
1083 lock_word = obj->GetLockWord(true);
1084 if (lock_word.GetState() == LockWord::kThinLocked &&
1085 lock_word.ThinLockOwner() == owner_thread_id) {
1086 // Go ahead and inflate the lock.
1087 Inflate(self, owner, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001088 }
Alex Light88fd7202017-06-30 08:31:59 -07001089 bool resumed = thread_list->Resume(owner, SuspendReason::kInternal);
1090 DCHECK(resumed);
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001091 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07001092 self->SetMonitorEnterObject(nullptr);
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001093 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001094}
1095
Ian Rogers719d1a32014-03-06 12:13:39 -08001096// Fool annotalysis into thinking that the lock on obj is acquired.
1097static mirror::Object* FakeLock(mirror::Object* obj)
1098 EXCLUSIVE_LOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
1099 return obj;
1100}
1101
1102// Fool annotalysis into thinking that the lock on obj is release.
1103static mirror::Object* FakeUnlock(mirror::Object* obj)
1104 UNLOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
1105 return obj;
1106}
1107
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07001108mirror::Object* Monitor::MonitorEnter(Thread* self, mirror::Object* obj, bool trylock) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001109 DCHECK(self != nullptr);
1110 DCHECK(obj != nullptr);
Mathieu Chartier2d096c92015-10-12 16:18:20 -07001111 self->AssertThreadSuspensionIsAllowable();
Ian Rogers719d1a32014-03-06 12:13:39 -08001112 obj = FakeLock(obj);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001113 uint32_t thread_id = self->GetThreadId();
1114 size_t contention_count = 0;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001115 StackHandleScope<1> hs(self);
1116 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001117 while (true) {
Hans Boehmb3da36c2016-12-15 13:12:59 -08001118 // We initially read the lockword with ordinary Java/relaxed semantics. When stronger
1119 // semantics are needed, we address it below. Since GetLockWord bottoms out to a relaxed load,
1120 // we can fix it later, in an infrequently executed case, with a fence.
1121 LockWord lock_word = h_obj->GetLockWord(false);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001122 switch (lock_word.GetState()) {
1123 case LockWord::kUnlocked: {
Hans Boehmb3da36c2016-12-15 13:12:59 -08001124 // No ordering required for preceding lockword read, since we retest.
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001125 LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0, lock_word.GCState()));
Mathieu Chartier42c2e502018-06-19 12:30:56 -07001126 if (h_obj->CasLockWord(lock_word, thin_locked, CASMode::kWeak, std::memory_order_acquire)) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001127 AtraceMonitorLock(self, h_obj.Get(), /* is_wait= */ false);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001128 return h_obj.Get(); // Success!
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001129 }
1130 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -07001131 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001132 case LockWord::kThinLocked: {
1133 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1134 if (owner_thread_id == thread_id) {
Hans Boehmb3da36c2016-12-15 13:12:59 -08001135 // No ordering required for initial lockword read.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001136 // We own the lock, increase the recursion count.
1137 uint32_t new_count = lock_word.ThinLockCount() + 1;
1138 if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001139 LockWord thin_locked(LockWord::FromThinLockId(thread_id,
1140 new_count,
1141 lock_word.GCState()));
Hans Boehmb3da36c2016-12-15 13:12:59 -08001142 // Only this thread pays attention to the count. Thus there is no need for stronger
1143 // than relaxed memory ordering.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001144 if (!kUseReadBarrier) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001145 h_obj->SetLockWord(thin_locked, /* as_volatile= */ false);
1146 AtraceMonitorLock(self, h_obj.Get(), /* is_wait= */ false);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001147 return h_obj.Get(); // Success!
1148 } else {
1149 // Use CAS to preserve the read barrier state.
Mathieu Chartier42c2e502018-06-19 12:30:56 -07001150 if (h_obj->CasLockWord(lock_word,
1151 thin_locked,
1152 CASMode::kWeak,
1153 std::memory_order_relaxed)) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001154 AtraceMonitorLock(self, h_obj.Get(), /* is_wait= */ false);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001155 return h_obj.Get(); // Success!
1156 }
1157 }
1158 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -07001159 } else {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001160 // We'd overflow the recursion count, so inflate the monitor.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001161 InflateThinLocked(self, h_obj, lock_word, 0);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001162 }
1163 } else {
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07001164 if (trylock) {
1165 return nullptr;
1166 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001167 // Contention.
1168 contention_count++;
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001169 Runtime* runtime = Runtime::Current();
Hans Boehmb3da36c2016-12-15 13:12:59 -08001170 if (contention_count <= runtime->GetMaxSpinsBeforeThinLockInflation()) {
Alex Light77fee872017-09-05 14:51:49 -07001171 // TODO: Consider switching the thread state to kWaitingForLockInflation when we are
1172 // yielding. Use sched_yield instead of NanoSleep since NanoSleep can wait much longer
1173 // than the parameter you pass in. This can cause thread suspension to take excessively
1174 // long and make long pauses. See b/16307460.
Hans Boehmb3da36c2016-12-15 13:12:59 -08001175 // TODO: We should literally spin first, without sched_yield. Sched_yield either does
1176 // nothing (at significant expense), or guarantees that we wait at least microseconds.
1177 // If the owner is running, I would expect the median lock hold time to be hundreds
1178 // of nanoseconds or less.
Mathieu Chartier251755c2014-07-15 18:10:25 -07001179 sched_yield();
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001180 } else {
1181 contention_count = 0;
Hans Boehmb3da36c2016-12-15 13:12:59 -08001182 // No ordering required for initial lockword read. Install rereads it anyway.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001183 InflateThinLocked(self, h_obj, lock_word, 0);
Elliott Hughes5f791332011-09-15 17:45:30 -07001184 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001185 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001186 continue; // Start from the beginning.
Elliott Hughes5f791332011-09-15 17:45:30 -07001187 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001188 case LockWord::kFatLocked: {
Hans Boehmb3da36c2016-12-15 13:12:59 -08001189 // We should have done an acquire read of the lockword initially, to ensure
1190 // visibility of the monitor data structure. Use an explicit fence instead.
Orion Hodson27b96762018-03-13 16:06:57 +00001191 std::atomic_thread_fence(std::memory_order_acquire);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001192 Monitor* mon = lock_word.FatLockMonitor();
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07001193 if (trylock) {
1194 return mon->TryLock(self) ? h_obj.Get() : nullptr;
1195 } else {
1196 mon->Lock(self);
1197 return h_obj.Get(); // Success!
1198 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001199 }
Ian Rogers719d1a32014-03-06 12:13:39 -08001200 case LockWord::kHashCode:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001201 // Inflate with the existing hashcode.
Hans Boehmb3da36c2016-12-15 13:12:59 -08001202 // Again no ordering required for initial lockword read, since we don't rely
1203 // on the visibility of any prior computation.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001204 Inflate(self, nullptr, h_obj.Get(), lock_word.GetHashCode());
Ian Rogers719d1a32014-03-06 12:13:39 -08001205 continue; // Start from the beginning.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001206 default: {
1207 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Andreas Gampec7ed09b2016-04-25 20:08:55 -07001208 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001209 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001210 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001211 }
1212}
1213
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001214bool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001215 DCHECK(self != nullptr);
1216 DCHECK(obj != nullptr);
Mathieu Chartier2d096c92015-10-12 16:18:20 -07001217 self->AssertThreadSuspensionIsAllowable();
Ian Rogers719d1a32014-03-06 12:13:39 -08001218 obj = FakeUnlock(obj);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001219 StackHandleScope<1> hs(self);
1220 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001221 while (true) {
1222 LockWord lock_word = obj->GetLockWord(true);
1223 switch (lock_word.GetState()) {
1224 case LockWord::kHashCode:
1225 // Fall-through.
1226 case LockWord::kUnlocked:
Mathieu Chartier61b3cd42016-04-18 11:43:29 -07001227 FailedUnlock(h_obj.Get(), self->GetThreadId(), 0u, nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001228 return false; // Failure.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001229 case LockWord::kThinLocked: {
1230 uint32_t thread_id = self->GetThreadId();
1231 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1232 if (owner_thread_id != thread_id) {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -07001233 FailedUnlock(h_obj.Get(), thread_id, owner_thread_id, nullptr);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001234 return false; // Failure.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001235 } else {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001236 // We own the lock, decrease the recursion count.
1237 LockWord new_lw = LockWord::Default();
1238 if (lock_word.ThinLockCount() != 0) {
1239 uint32_t new_count = lock_word.ThinLockCount() - 1;
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001240 new_lw = LockWord::FromThinLockId(thread_id, new_count, lock_word.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001241 } else {
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001242 new_lw = LockWord::FromDefault(lock_word.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001243 }
1244 if (!kUseReadBarrier) {
1245 DCHECK_EQ(new_lw.ReadBarrierState(), 0U);
Hans Boehmb3da36c2016-12-15 13:12:59 -08001246 // TODO: This really only needs memory_order_release, but we currently have
1247 // no way to specify that. In fact there seem to be no legitimate uses of SetLockWord
1248 // with a final argument of true. This slows down x86 and ARMv7, but probably not v8.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001249 h_obj->SetLockWord(new_lw, true);
Andreas Gampe6e759ad2016-05-17 10:13:10 -07001250 AtraceMonitorUnlock();
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001251 // Success!
1252 return true;
1253 } else {
1254 // Use CAS to preserve the read barrier state.
Mathieu Chartier42c2e502018-06-19 12:30:56 -07001255 if (h_obj->CasLockWord(lock_word, new_lw, CASMode::kWeak, std::memory_order_release)) {
Andreas Gampe6e759ad2016-05-17 10:13:10 -07001256 AtraceMonitorUnlock();
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001257 // Success!
1258 return true;
1259 }
1260 }
1261 continue; // Go again.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001262 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001263 }
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001264 case LockWord::kFatLocked: {
1265 Monitor* mon = lock_word.FatLockMonitor();
1266 return mon->Unlock(self);
1267 }
1268 default: {
1269 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1270 return false;
1271 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001272 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001273 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001274}
1275
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001276void Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
Elliott Hughes4cd121e2013-01-07 17:35:41 -08001277 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001278 DCHECK(self != nullptr);
1279 DCHECK(obj != nullptr);
Alex Light77fee872017-09-05 14:51:49 -07001280 StackHandleScope<1> hs(self);
1281 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
1282
1283 Runtime::Current()->GetRuntimeCallbacks()->ObjectWaitStart(h_obj, ms);
Alex Light848574c2017-09-25 16:59:39 -07001284 if (UNLIKELY(self->ObserveAsyncException() || self->IsExceptionPending())) {
Alex Light77fee872017-09-05 14:51:49 -07001285 // See b/65558434 for information on handling of exceptions here.
1286 return;
1287 }
1288
1289 LockWord lock_word = h_obj->GetLockWord(true);
Ian Rogers43c69cc2014-08-15 11:09:28 -07001290 while (lock_word.GetState() != LockWord::kFatLocked) {
1291 switch (lock_word.GetState()) {
1292 case LockWord::kHashCode:
1293 // Fall-through.
1294 case LockWord::kUnlocked:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001295 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
1296 return; // Failure.
Ian Rogers43c69cc2014-08-15 11:09:28 -07001297 case LockWord::kThinLocked: {
1298 uint32_t thread_id = self->GetThreadId();
1299 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1300 if (owner_thread_id != thread_id) {
1301 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
1302 return; // Failure.
1303 } else {
1304 // We own the lock, inflate to enqueue ourself on the Monitor. May fail spuriously so
1305 // re-load.
Alex Light77fee872017-09-05 14:51:49 -07001306 Inflate(self, self, h_obj.Get(), 0);
1307 lock_word = h_obj->GetLockWord(true);
Ian Rogers43c69cc2014-08-15 11:09:28 -07001308 }
1309 break;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001310 }
Ian Rogers43c69cc2014-08-15 11:09:28 -07001311 case LockWord::kFatLocked: // Unreachable given the loop condition above. Fall-through.
1312 default: {
1313 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1314 return;
1315 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001316 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001317 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001318 Monitor* mon = lock_word.FatLockMonitor();
1319 mon->Wait(self, ms, ns, interruptShouldThrow, why);
Elliott Hughes5f791332011-09-15 17:45:30 -07001320}
1321
Ian Rogers13c479e2013-10-11 07:59:01 -07001322void Monitor::DoNotify(Thread* self, mirror::Object* obj, bool notify_all) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001323 DCHECK(self != nullptr);
1324 DCHECK(obj != nullptr);
1325 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001326 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001327 case LockWord::kHashCode:
1328 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001329 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -08001330 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001331 return; // Failure.
1332 case LockWord::kThinLocked: {
1333 uint32_t thread_id = self->GetThreadId();
1334 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1335 if (owner_thread_id != thread_id) {
1336 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
1337 return; // Failure.
1338 } else {
1339 // We own the lock but there's no Monitor and therefore no waiters.
1340 return; // Success.
1341 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001342 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001343 case LockWord::kFatLocked: {
1344 Monitor* mon = lock_word.FatLockMonitor();
1345 if (notify_all) {
1346 mon->NotifyAll(self);
1347 } else {
1348 mon->Notify(self);
1349 }
1350 return; // Success.
1351 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001352 default: {
1353 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1354 return;
1355 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001356 }
1357}
1358
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001359uint32_t Monitor::GetLockOwnerThreadId(mirror::Object* obj) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001360 DCHECK(obj != nullptr);
1361 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001362 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001363 case LockWord::kHashCode:
1364 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001365 case LockWord::kUnlocked:
1366 return ThreadList::kInvalidThreadId;
1367 case LockWord::kThinLocked:
1368 return lock_word.ThinLockOwner();
1369 case LockWord::kFatLocked: {
1370 Monitor* mon = lock_word.FatLockMonitor();
1371 return mon->GetOwnerThreadId();
Elliott Hughes5f791332011-09-15 17:45:30 -07001372 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001373 default: {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001374 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001375 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001376 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001377 }
1378}
1379
Andreas Gampef3ebcce2017-12-11 20:40:23 -08001380ThreadState Monitor::FetchState(const Thread* thread,
1381 /* out */ mirror::Object** monitor_object,
1382 /* out */ uint32_t* lock_owner_tid) {
1383 DCHECK(monitor_object != nullptr);
1384 DCHECK(lock_owner_tid != nullptr);
1385
1386 *monitor_object = nullptr;
1387 *lock_owner_tid = ThreadList::kInvalidThreadId;
1388
1389 ThreadState state = thread->GetState();
1390
1391 switch (state) {
1392 case kWaiting:
1393 case kTimedWaiting:
1394 case kSleeping:
1395 {
1396 Thread* self = Thread::Current();
1397 MutexLock mu(self, *thread->GetWaitMutex());
1398 Monitor* monitor = thread->GetWaitMonitor();
1399 if (monitor != nullptr) {
1400 *monitor_object = monitor->GetObject();
Ian Rogersd803bc72014-04-01 15:33:03 -07001401 }
1402 }
Andreas Gampef3ebcce2017-12-11 20:40:23 -08001403 break;
1404
1405 case kBlocked:
1406 case kWaitingForLockInflation:
1407 {
1408 mirror::Object* lock_object = thread->GetMonitorEnterObject();
1409 if (lock_object != nullptr) {
1410 if (kUseReadBarrier && Thread::Current()->GetIsGcMarking()) {
1411 // We may call Thread::Dump() in the middle of the CC thread flip and this thread's stack
1412 // may have not been flipped yet and "pretty_object" may be a from-space (stale) ref, in
1413 // which case the GetLockOwnerThreadId() call below will crash. So explicitly mark/forward
1414 // it here.
1415 lock_object = ReadBarrier::Mark(lock_object);
1416 }
1417 *monitor_object = lock_object;
1418 *lock_owner_tid = lock_object->GetLockOwnerThreadId();
1419 }
Ian Rogersd803bc72014-04-01 15:33:03 -07001420 }
Andreas Gampef3ebcce2017-12-11 20:40:23 -08001421 break;
1422
1423 default:
1424 break;
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001425 }
Andreas Gampef3ebcce2017-12-11 20:40:23 -08001426
1427 return state;
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001428}
1429
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001430mirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -08001431 // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
1432 // definition of contended that includes a monitor a thread is trying to enter...
Ian Rogersdd7624d2014-03-14 17:43:00 -07001433 mirror::Object* result = thread->GetMonitorEnterObject();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001434 if (result == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001435 // ...but also a monitor that the thread is waiting on.
Ian Rogersdd7624d2014-03-14 17:43:00 -07001436 MutexLock mu(Thread::Current(), *thread->GetWaitMutex());
1437 Monitor* monitor = thread->GetWaitMonitor();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001438 if (monitor != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001439 result = monitor->GetObject();
Elliott Hughesf9501702013-01-11 11:22:27 -08001440 }
1441 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001442 return result;
Elliott Hughesf9501702013-01-11 11:22:27 -08001443}
1444
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001445void Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
Andreas Gampe760172c2014-08-16 13:41:10 -07001446 void* callback_context, bool abort_on_failure) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001447 ArtMethod* m = stack_visitor->GetMethod();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001448 CHECK(m != nullptr);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001449
1450 // Native methods are an easy special case.
1451 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
1452 if (m->IsNative()) {
1453 if (m->IsSynchronized()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001454 mirror::Object* jni_this =
1455 stack_visitor->GetCurrentHandleScope(sizeof(void*))->GetReference(0);
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001456 callback(jni_this, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001457 }
1458 return;
1459 }
1460
jeffhao61f916c2012-10-25 17:48:51 -07001461 // Proxy methods should not be synchronized.
1462 if (m->IsProxyMethod()) {
1463 CHECK(!m->IsSynchronized());
1464 return;
1465 }
1466
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001467 // Is there any reason to believe there's any synchronization in this method?
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001468 CHECK(m->GetCodeItem() != nullptr) << m->PrettyMethod();
David Sehr0225f8e2018-01-31 08:52:24 +00001469 CodeItemDataAccessor accessor(m->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001470 if (accessor.TriesSize() == 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001471 return; // No "tries" implies no synchronization, so no held locks to report.
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001472 }
1473
Andreas Gampe760172c2014-08-16 13:41:10 -07001474 // Get the dex pc. If abort_on_failure is false, GetDexPc will not abort in the case it cannot
1475 // find the dex pc, and instead return kDexNoIndex. Then bail out, as it indicates we have an
1476 // inconsistent stack anyways.
1477 uint32_t dex_pc = stack_visitor->GetDexPc(abort_on_failure);
Andreas Gampee2abbc62017-09-15 11:59:26 -07001478 if (!abort_on_failure && dex_pc == dex::kDexNoIndex) {
David Sehr709b0702016-10-13 09:12:37 -07001479 LOG(ERROR) << "Could not find dex_pc for " << m->PrettyMethod();
Andreas Gampe760172c2014-08-16 13:41:10 -07001480 return;
1481 }
1482
Elliott Hughes80537bb2013-01-04 16:37:26 -08001483 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
1484 // the locks held in this stack frame.
Andreas Gampeaaf0d382017-11-27 14:10:21 -08001485 std::vector<verifier::MethodVerifier::DexLockInfo> monitor_enter_dex_pcs;
Andreas Gampe6cc23ac2018-08-24 15:22:43 -07001486 verifier::MethodVerifier::FindLocksAtDexPc(m,
1487 dex_pc,
1488 &monitor_enter_dex_pcs,
1489 Runtime::Current()->GetTargetSdkVersion());
Andreas Gampeaaf0d382017-11-27 14:10:21 -08001490 for (verifier::MethodVerifier::DexLockInfo& dex_lock_info : monitor_enter_dex_pcs) {
1491 // As a debug check, check that dex PC corresponds to a monitor-enter.
1492 if (kIsDebugBuild) {
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001493 const Instruction& monitor_enter_instruction = accessor.InstructionAt(dex_lock_info.dex_pc);
1494 CHECK_EQ(monitor_enter_instruction.Opcode(), Instruction::MONITOR_ENTER)
Andreas Gampeaaf0d382017-11-27 14:10:21 -08001495 << "expected monitor-enter @" << dex_lock_info.dex_pc << "; was "
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001496 << reinterpret_cast<const void*>(&monitor_enter_instruction);
Andreas Gampeaaf0d382017-11-27 14:10:21 -08001497 }
Elliott Hughes80537bb2013-01-04 16:37:26 -08001498
Andreas Gampeaaf0d382017-11-27 14:10:21 -08001499 // Iterate through the set of dex registers, as the compiler may not have held all of them
1500 // live.
1501 bool success = false;
1502 for (uint32_t dex_reg : dex_lock_info.dex_registers) {
1503 uint32_t value;
1504 success = stack_visitor->GetVReg(m, dex_reg, kReferenceVReg, &value);
1505 if (success) {
1506 mirror::Object* o = reinterpret_cast<mirror::Object*>(value);
1507 callback(o, callback_context);
1508 break;
1509 }
1510 }
1511 DCHECK(success) << "Failed to find/read reference for monitor-enter at dex pc "
1512 << dex_lock_info.dex_pc
1513 << " in method "
1514 << m->PrettyMethod();
1515 if (!success) {
1516 LOG(WARNING) << "Had a lock reported for dex pc " << dex_lock_info.dex_pc
1517 << " but was not able to fetch a corresponding object!";
1518 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001519 }
1520}
1521
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001522bool Monitor::IsValidLockWord(LockWord lock_word) {
1523 switch (lock_word.GetState()) {
1524 case LockWord::kUnlocked:
1525 // Nothing to check.
1526 return true;
1527 case LockWord::kThinLocked:
1528 // Basic sanity check of owner.
1529 return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
1530 case LockWord::kFatLocked: {
1531 // Check the monitor appears in the monitor list.
1532 Monitor* mon = lock_word.FatLockMonitor();
1533 MonitorList* list = Runtime::Current()->GetMonitorList();
1534 MutexLock mu(Thread::Current(), list->monitor_list_lock_);
1535 for (Monitor* list_mon : list->list_) {
1536 if (mon == list_mon) {
1537 return true; // Found our monitor.
1538 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001539 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001540 return false; // Fail - unowned monitor in an object.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001541 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001542 case LockWord::kHashCode:
1543 return true;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001544 default:
1545 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001546 UNREACHABLE();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001547 }
1548}
1549
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001550bool Monitor::IsLocked() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001551 MutexLock mu(Thread::Current(), monitor_lock_);
1552 return owner_ != nullptr;
1553}
1554
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -07001555void Monitor::TranslateLocation(ArtMethod* method,
1556 uint32_t dex_pc,
1557 const char** source_file,
1558 int32_t* line_number) {
jeffhao33dc7712011-11-09 17:54:24 -08001559 // If method is null, location is unknown
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001560 if (method == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001561 *source_file = "";
1562 *line_number = 0;
jeffhao33dc7712011-11-09 17:54:24 -08001563 return;
1564 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001565 *source_file = method->GetDeclaringClassSourceFile();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001566 if (*source_file == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001567 *source_file = "";
Elliott Hughes12c51e32012-01-17 20:25:05 -08001568 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001569 *line_number = method->GetLineNumFromDexPC(dex_pc);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001570}
1571
1572uint32_t Monitor::GetOwnerThreadId() {
1573 MutexLock mu(Thread::Current(), monitor_lock_);
1574 Thread* owner = owner_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001575 if (owner != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001576 return owner->GetThreadId();
1577 } else {
1578 return ThreadList::kInvalidThreadId;
1579 }
jeffhao33dc7712011-11-09 17:54:24 -08001580}
1581
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001582MonitorList::MonitorList()
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001583 : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock", kMonitorListLock),
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001584 monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001585}
1586
1587MonitorList::~MonitorList() {
Andreas Gampe74240812014-04-17 10:35:09 -07001588 Thread* self = Thread::Current();
1589 MutexLock mu(self, monitor_list_lock_);
1590 // Release all monitors to the pool.
1591 // TODO: Is it an invariant that *all* open monitors are in the list? Then we could
1592 // clear faster in the pool.
1593 MonitorPool::ReleaseMonitors(self, &list_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001594}
1595
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001596void MonitorList::DisallowNewMonitors() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001597 CHECK(!kUseReadBarrier);
Ian Rogers50b35e22012-10-04 10:09:15 -07001598 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001599 allow_new_monitors_ = false;
1600}
1601
1602void MonitorList::AllowNewMonitors() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001603 CHECK(!kUseReadBarrier);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001604 Thread* self = Thread::Current();
1605 MutexLock mu(self, monitor_list_lock_);
1606 allow_new_monitors_ = true;
1607 monitor_add_condition_.Broadcast(self);
1608}
1609
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001610void MonitorList::BroadcastForNewMonitors() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001611 Thread* self = Thread::Current();
1612 MutexLock mu(self, monitor_list_lock_);
1613 monitor_add_condition_.Broadcast(self);
1614}
1615
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001616void MonitorList::Add(Monitor* m) {
1617 Thread* self = Thread::Current();
1618 MutexLock mu(self, monitor_list_lock_);
Hiroshi Yamauchif1c6f872017-01-06 12:23:47 -08001619 // CMS needs this to block for concurrent reference processing because an object allocated during
1620 // the GC won't be marked and concurrent reference processing would incorrectly clear the JNI weak
1621 // ref. But CC (kUseReadBarrier == true) doesn't because of the to-space invariant.
1622 while (!kUseReadBarrier && UNLIKELY(!allow_new_monitors_)) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -07001623 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
1624 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -08001625 self->CheckEmptyCheckpointFromWeakRefAccess(&monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001626 monitor_add_condition_.WaitHoldingLocks(self);
1627 }
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001628 list_.push_front(m);
1629}
1630
Mathieu Chartier97509952015-07-13 14:35:43 -07001631void MonitorList::SweepMonitorList(IsMarkedVisitor* visitor) {
Andreas Gampe74240812014-04-17 10:35:09 -07001632 Thread* self = Thread::Current();
1633 MutexLock mu(self, monitor_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001634 for (auto it = list_.begin(); it != list_.end(); ) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001635 Monitor* m = *it;
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001636 // Disable the read barrier in GetObject() as this is called by GC.
1637 mirror::Object* obj = m->GetObject<kWithoutReadBarrier>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001638 // The object of a monitor can be null if we have deflated it.
Mathieu Chartier97509952015-07-13 14:35:43 -07001639 mirror::Object* new_obj = obj != nullptr ? visitor->IsMarked(obj) : nullptr;
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001640 if (new_obj == nullptr) {
1641 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001642 << obj;
Andreas Gampe74240812014-04-17 10:35:09 -07001643 MonitorPool::ReleaseMonitor(self, m);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001644 it = list_.erase(it);
1645 } else {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001646 m->SetObject(new_obj);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001647 ++it;
1648 }
1649 }
1650}
1651
Hans Boehm6fe97e02016-05-04 18:35:57 -07001652size_t MonitorList::Size() {
1653 Thread* self = Thread::Current();
1654 MutexLock mu(self, monitor_list_lock_);
1655 return list_.size();
1656}
1657
Mathieu Chartier97509952015-07-13 14:35:43 -07001658class MonitorDeflateVisitor : public IsMarkedVisitor {
1659 public:
1660 MonitorDeflateVisitor() : self_(Thread::Current()), deflate_count_(0) {}
1661
Roland Levillainf73caca2018-08-24 17:19:07 +01001662 mirror::Object* IsMarked(mirror::Object* object) override
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001663 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001664 if (Monitor::Deflate(self_, object)) {
1665 DCHECK_NE(object->GetLockWord(true).GetState(), LockWord::kFatLocked);
1666 ++deflate_count_;
1667 // If we deflated, return null so that the monitor gets removed from the array.
1668 return nullptr;
1669 }
1670 return object; // Monitor was not deflated.
1671 }
1672
1673 Thread* const self_;
1674 size_t deflate_count_;
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001675};
1676
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001677size_t MonitorList::DeflateMonitors() {
Mathieu Chartier97509952015-07-13 14:35:43 -07001678 MonitorDeflateVisitor visitor;
1679 Locks::mutator_lock_->AssertExclusiveHeld(visitor.self_);
1680 SweepMonitorList(&visitor);
1681 return visitor.deflate_count_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001682}
1683
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001684MonitorInfo::MonitorInfo(mirror::Object* obj) : owner_(nullptr), entry_count_(0) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001685 DCHECK(obj != nullptr);
1686 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001687 switch (lock_word.GetState()) {
1688 case LockWord::kUnlocked:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001689 // Fall-through.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001690 case LockWord::kForwardingAddress:
1691 // Fall-through.
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001692 case LockWord::kHashCode:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001693 break;
1694 case LockWord::kThinLocked:
1695 owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
Alex Lightce568642017-09-05 16:54:25 -07001696 DCHECK(owner_ != nullptr) << "Thin-locked without owner!";
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001697 entry_count_ = 1 + lock_word.ThinLockCount();
1698 // Thin locks have no waiters.
1699 break;
1700 case LockWord::kFatLocked: {
1701 Monitor* mon = lock_word.FatLockMonitor();
1702 owner_ = mon->owner_;
Alex Lightce568642017-09-05 16:54:25 -07001703 // Here it is okay for the owner to be null since we don't reset the LockWord back to
1704 // kUnlocked until we get a GC. In cases where this hasn't happened yet we will have a fat
1705 // lock without an owner.
1706 if (owner_ != nullptr) {
1707 entry_count_ = 1 + mon->lock_count_;
1708 } else {
1709 DCHECK_EQ(mon->lock_count_, 0) << "Monitor is fat-locked without any owner!";
1710 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001711 for (Thread* waiter = mon->wait_set_; waiter != nullptr; waiter = waiter->GetWaitNext()) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001712 waiters_.push_back(waiter);
1713 }
1714 break;
Elliott Hughesf327e072013-01-09 16:01:26 -08001715 }
1716 }
1717}
1718
Elliott Hughes5f791332011-09-15 17:45:30 -07001719} // namespace art