blob: df2a8e29cbeddfdd8430e1815856b4b8e419ebe6 [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 Mungerc665d632018-11-06 16:20:13 +0000100 wake_set_(nullptr),
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700101 hash_code_(hash_code),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700102 locking_method_(nullptr),
Ian Rogersef7d42f2014-01-06 12:55:46 -0800103 locking_dex_pc_(0),
Andreas Gampe74240812014-04-17 10:35:09 -0700104 monitor_id_(MonitorPool::ComputeMonitorId(this, self)) {
105#ifdef __LP64__
106 DCHECK(false) << "Should not be reached in 64b";
107 next_free_ = nullptr;
108#endif
109 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
110 // with the owner unlocking the thin-lock.
111 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
112 // The identity hash code is set for the life time of the monitor.
113}
114
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 Mungerc665d632018-11-06 16:20:13 +0000124 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 Mungerc665d632018-11-06 16:20:13 +0000231 // 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 Mungerc665d632018-11-06 16:20:13 +0000251 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 }
Roland Levillain9cec9652018-11-06 10:50:20 +0000267 }
Charles Mungerc665d632018-11-06 16:20:13 +0000268 return false;
269 };
270 if (remove(wait_set_)) {
271 return;
Roland Levillain9cec9652018-11-06 10:50:20 +0000272 }
Charles Mungerc665d632018-11-06 16:20:13 +0000273 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 Mungerc665d632018-11-06 16:20:13 +0000710 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 Mungerc665d632018-11-06 16:20:13 +0000734 monitor_lock_.Unlock(self);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700735 return false;
Elliott Hughes5f791332011-09-15 17:45:30 -0700736}
737
Charles Mungerc665d632018-11-06 16:20:13 +0000738void 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 (wake_set_ != nullptr) {
743 // No risk of waking ourselves here; since monitor_lock_ is not released until we're ready to
744 // return, notify can't move the current thread from wait_set_ to wake_set_ until this
745 // method is done checking wake_set_.
746 Thread* thread = wake_set_;
747 wake_set_ = thread->GetWaitNext();
748 thread->SetWaitNext(nullptr);
749
750 // Check to see if the thread is still waiting.
751 {
752 // In the case of wait(), we'll be acquiring another thread's GetWaitMutex with
753 // self's GetWaitMutex held. This does not risk deadlock, because we only acquire this lock
754 // for threads in the wake_set_. A thread can only enter wake_set_ from Notify or NotifyAll,
755 // and those hold monitor_lock_. Thus, the threads whose wait mutexes we acquire here must
756 // have already been released from wait(), since we have not released monitor_lock_ until
757 // after we've chosen our thread to wake, so there is no risk of the following lock ordering
758 // leading to deadlock:
759 // Thread 1 waits
760 // Thread 2 waits
761 // Thread 3 moves threads 1 and 2 from wait_set_ to wake_set_
762 // Thread 1 enters this block, and attempts to acquire Thread 2's GetWaitMutex to wake it
763 // Thread 2 enters this block, and attempts to acquire Thread 1's GetWaitMutex to wake it
764 //
765 // Since monitor_lock_ is not released until the thread-to-be-woken-up's GetWaitMutex is
766 // acquired, two threads cannot attempt to acquire each other's GetWaitMutex while holding
767 // their own and cause deadlock.
768 MutexLock wait_mu(self, *thread->GetWaitMutex());
769 if (thread->GetWaitMonitor() != nullptr) {
770 // Release the lock, so that a potentially awakened thread will not
771 // immediately contend on it. The lock ordering here is:
772 // monitor_lock_, self->GetWaitMutex, thread->GetWaitMutex
773 monitor_lock_.Unlock(self);
774 thread->GetWaitConditionVariable()->Signal(self);
775 return;
776 }
777 }
778 }
779 // If we didn't wake any threads that were originally waiting on us,
780 // wake a contender.
781 monitor_contenders_.Signal(self);
782 monitor_lock_.Unlock(self);
783}
784
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800785void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
786 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700787 DCHECK(self != nullptr);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800788 DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
Elliott Hughes5f791332011-09-15 17:45:30 -0700789
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700790 monitor_lock_.Lock(self);
791
Elliott Hughes5f791332011-09-15 17:45:30 -0700792 // Make sure that we hold the lock.
793 if (owner_ != self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700794 monitor_lock_.Unlock(self);
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700795 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700796 return;
797 }
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800798
Elliott Hughesdf42c482013-01-09 12:49:02 -0800799 // We need to turn a zero-length timed wait into a regular wait because
800 // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
801 if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
802 why = kWaiting;
803 }
804
Elliott Hughes5f791332011-09-15 17:45:30 -0700805 // Enforce the timeout range.
806 if (ms < 0 || ns < 0 || ns > 999999) {
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700807 monitor_lock_.Unlock(self);
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000808 self->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
Ian Rogersef7d42f2014-01-06 12:55:46 -0800809 "timeout arguments out of range: ms=%" PRId64 " ns=%d", ms, ns);
Elliott Hughes5f791332011-09-15 17:45:30 -0700810 return;
811 }
812
Elliott Hughes5f791332011-09-15 17:45:30 -0700813 /*
Charles Mungerc665d632018-11-06 16:20:13 +0000814 * Release our hold - we need to let it go even if we're a few levels
Elliott Hughes5f791332011-09-15 17:45:30 -0700815 * deep in a recursive lock, and we need to restore that later.
Elliott Hughes5f791332011-09-15 17:45:30 -0700816 */
Ian Rogers0399dde2012-06-06 17:09:28 -0700817 int prev_lock_count = lock_count_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700818 lock_count_ = 0;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700819 owner_ = nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700820 ArtMethod* saved_method = locking_method_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700821 locking_method_ = nullptr;
Ian Rogers0399dde2012-06-06 17:09:28 -0700822 uintptr_t saved_dex_pc = locking_dex_pc_;
823 locking_dex_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700824
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700825 AtraceMonitorUnlock(); // For the implict Unlock() just above. This will only end the deepest
826 // nesting, but that is enough for the visualization, and corresponds to
827 // the single Lock() we do afterwards.
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700828 AtraceMonitorLock(self, GetObject(), /* is_wait= */ true);
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700829
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800830 bool was_interrupted = false;
Alex Light77fee872017-09-05 14:51:49 -0700831 bool timed_out = false;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700832 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700833 // Update thread state. If the GC wakes up, it'll ignore us, knowing
834 // that we won't touch any references in this state, and we'll check
835 // our suspend mode before we transition out.
836 ScopedThreadSuspension sts(self, why);
837
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700838 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700839 MutexLock mu(self, *self->GetWaitMutex());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700840
Charles Mungerc665d632018-11-06 16:20:13 +0000841 /*
842 * Add ourselves to the set of threads waiting on this monitor.
843 * It's important that we are only added to the wait set after
844 * acquiring our GetWaitMutex, so that calls to Notify() that occur after we
845 * have released monitor_lock_ will not move us from wait_set_ to wake_set_
846 * until we've signalled contenders on this monitor.
847 */
848 AppendToWaitSet(self);
849 ++num_waiters_;
850
851
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700852 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700853 // non-null a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700854 // up.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700855 DCHECK(self->GetWaitMonitor() == nullptr);
856 self->SetWaitMonitor(this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700857
858 // Release the monitor lock.
Charles Mungerc665d632018-11-06 16:20:13 +0000859 SignalContendersAndReleaseMonitorLock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700860
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800861 // Handle the case where the thread was interrupted before we called wait().
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000862 if (self->IsInterrupted()) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800863 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700864 } else {
865 // Wait for a notification or a timeout to occur.
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800866 if (why == kWaiting) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700867 self->GetWaitConditionVariable()->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700868 } else {
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800869 DCHECK(why == kTimedWaiting || why == kSleeping) << why;
Alex Light77fee872017-09-05 14:51:49 -0700870 timed_out = self->GetWaitConditionVariable()->TimedWait(self, ms, ns);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700871 }
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000872 was_interrupted = self->IsInterrupted();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700873 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700874 }
875
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800876 {
877 // We reset the thread's wait_monitor_ field after transitioning back to runnable so
878 // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
879 // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
880 // are waiting on "null".)
Ian Rogersdd7624d2014-03-14 17:43:00 -0700881 MutexLock mu(self, *self->GetWaitMutex());
882 DCHECK(self->GetWaitMonitor() != nullptr);
883 self->SetWaitMonitor(nullptr);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800884 }
885
Mathieu Chartierdaed5d82016-03-10 10:49:35 -0800886 // Allocate the interrupted exception not holding the monitor lock since it may cause a GC.
887 // If the GC requires acquiring the monitor for enqueuing cleared references, this would
888 // cause a deadlock if the monitor is held.
889 if (was_interrupted && interruptShouldThrow) {
890 /*
891 * We were interrupted while waiting, or somebody interrupted an
892 * un-interruptible thread earlier and we're bailing out immediately.
893 *
894 * The doc sayeth: "The interrupted status of the current thread is
895 * cleared when this exception is thrown."
896 */
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000897 self->SetInterrupted(false);
Mathieu Chartierdaed5d82016-03-10 10:49:35 -0800898 self->ThrowNewException("Ljava/lang/InterruptedException;", nullptr);
899 }
900
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700901 AtraceMonitorUnlock(); // End Wait().
902
Alex Light77fee872017-09-05 14:51:49 -0700903 // We just slept, tell the runtime callbacks about this.
904 Runtime::Current()->GetRuntimeCallbacks()->MonitorWaitFinished(this, timed_out);
905
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700906 // Re-acquire the monitor and lock.
Alex Light77fee872017-09-05 14:51:49 -0700907 Lock<LockReason::kForWait>(self);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700908 monitor_lock_.Lock(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700909 self->GetWaitMutex()->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700910
Elliott Hughes5f791332011-09-15 17:45:30 -0700911 /*
912 * We remove our thread from wait set after restoring the count
913 * and owner fields so the subroutine can check that the calling
914 * thread owns the monitor. Aside from that, the order of member
915 * updates is not order sensitive as we hold the pthread mutex.
916 */
917 owner_ = self;
Ian Rogers0399dde2012-06-06 17:09:28 -0700918 lock_count_ = prev_lock_count;
919 locking_method_ = saved_method;
920 locking_dex_pc_ = saved_dex_pc;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700921 --num_waiters_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700922 RemoveFromWaitSet(self);
923
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700924 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700925}
926
927void Monitor::Notify(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700928 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700929 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700930 // Make sure that we hold the lock.
931 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800932 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700933 return;
934 }
Charles Mungerc665d632018-11-06 16:20:13 +0000935 // Move one thread from waiters to wake set
936 Thread* to_move = wait_set_;
937 if (to_move != nullptr) {
938 wait_set_ = to_move->GetWaitNext();
939 to_move->SetWaitNext(wake_set_);
940 wake_set_ = to_move;
Elliott Hughes5f791332011-09-15 17:45:30 -0700941 }
942}
943
944void Monitor::NotifyAll(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700945 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700946 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700947 // Make sure that we hold the lock.
948 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800949 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700950 return;
951 }
Charles Mungerc665d632018-11-06 16:20:13 +0000952
953 // Move all threads from waiters to wake set
954 Thread* to_move = wait_set_;
955 if (to_move != nullptr) {
956 wait_set_ = nullptr;
957 Thread* move_to = wake_set_;
958 if (move_to == nullptr) {
959 wake_set_ = to_move;
960 return;
961 }
962 while (move_to->GetWaitNext() != nullptr) {
963 move_to = move_to->GetWaitNext();
964 }
965 move_to->SetWaitNext(to_move);
Elliott Hughes5f791332011-09-15 17:45:30 -0700966 }
967}
968
Mathieu Chartier590fee92013-09-13 13:46:47 -0700969bool Monitor::Deflate(Thread* self, mirror::Object* obj) {
970 DCHECK(obj != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700971 // Don't need volatile since we only deflate with mutators suspended.
972 LockWord lw(obj->GetLockWord(false));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700973 // If the lock isn't an inflated monitor, then we don't need to deflate anything.
974 if (lw.GetState() == LockWord::kFatLocked) {
975 Monitor* monitor = lw.FatLockMonitor();
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700976 DCHECK(monitor != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700977 MutexLock mu(self, monitor->monitor_lock_);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700978 // Can't deflate if we have anybody waiting on the CV.
979 if (monitor->num_waiters_ > 0) {
980 return false;
981 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700982 Thread* owner = monitor->owner_;
983 if (owner != nullptr) {
984 // Can't deflate if we are locked and have a hash code.
985 if (monitor->HasHashCode()) {
986 return false;
987 }
988 // Can't deflate if our lock count is too high.
Mathieu Chartier1cf194f2016-11-01 20:13:24 -0700989 if (static_cast<uint32_t>(monitor->lock_count_) > LockWord::kThinLockMaxCount) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700990 return false;
991 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700992 // Deflate to a thin lock.
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700993 LockWord new_lw = LockWord::FromThinLockId(owner->GetThreadId(),
994 monitor->lock_count_,
995 lw.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800996 // Assume no concurrent read barrier state changes as mutators are suspended.
997 obj->SetLockWord(new_lw, false);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700998 VLOG(monitor) << "Deflated " << obj << " to thin lock " << owner->GetTid() << " / "
999 << monitor->lock_count_;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001000 } else if (monitor->HasHashCode()) {
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001001 LockWord new_lw = LockWord::FromHashCode(monitor->GetHashCode(), lw.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001002 // Assume no concurrent read barrier state changes as mutators are suspended.
1003 obj->SetLockWord(new_lw, false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001004 VLOG(monitor) << "Deflated " << obj << " to hash monitor " << monitor->GetHashCode();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001005 } else {
1006 // No lock and no hash, just put an empty lock word inside the object.
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001007 LockWord new_lw = LockWord::FromDefault(lw.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001008 // Assume no concurrent read barrier state changes as mutators are suspended.
1009 obj->SetLockWord(new_lw, false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001010 VLOG(monitor) << "Deflated" << obj << " to empty lock word";
Mathieu Chartier590fee92013-09-13 13:46:47 -07001011 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001012 // 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 -07001013 // next GC.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001014 monitor->obj_ = GcRoot<mirror::Object>(nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001015 }
1016 return true;
1017}
1018
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001019void Monitor::Inflate(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code) {
Andreas Gampe74240812014-04-17 10:35:09 -07001020 DCHECK(self != nullptr);
1021 DCHECK(obj != nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -07001022 // Allocate and acquire a new monitor.
Andreas Gampe74240812014-04-17 10:35:09 -07001023 Monitor* m = MonitorPool::CreateMonitor(self, owner, obj, hash_code);
1024 DCHECK(m != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001025 if (m->Install(self)) {
Haifeng Li86ab7912014-05-16 10:47:59 +08001026 if (owner != nullptr) {
1027 VLOG(monitor) << "monitor: thread" << owner->GetThreadId()
Andreas Gampe74240812014-04-17 10:35:09 -07001028 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +08001029 } else {
1030 VLOG(monitor) << "monitor: Inflate with hashcode " << hash_code
Andreas Gampe74240812014-04-17 10:35:09 -07001031 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +08001032 }
Andreas Gampe74240812014-04-17 10:35:09 -07001033 Runtime::Current()->GetMonitorList()->Add(m);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001034 CHECK_EQ(obj->GetLockWord(true).GetState(), LockWord::kFatLocked);
Andreas Gampe74240812014-04-17 10:35:09 -07001035 } else {
1036 MonitorPool::ReleaseMonitor(self, m);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001037 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001038}
1039
Mathieu Chartier0cd81352014-05-22 16:48:55 -07001040void Monitor::InflateThinLocked(Thread* self, Handle<mirror::Object> obj, LockWord lock_word,
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001041 uint32_t hash_code) {
1042 DCHECK_EQ(lock_word.GetState(), LockWord::kThinLocked);
1043 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1044 if (owner_thread_id == self->GetThreadId()) {
1045 // We own the monitor, we can easily inflate it.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001046 Inflate(self, self, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001047 } else {
1048 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1049 // Suspend the owner, inflate. First change to blocked and give up mutator_lock_.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001050 self->SetMonitorEnterObject(obj.Get());
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -07001051 bool timed_out;
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07001052 Thread* owner;
1053 {
Alex Light77fee872017-09-05 14:51:49 -07001054 ScopedThreadSuspension sts(self, kWaitingForLockInflation);
Alex Light46f93402017-06-29 11:59:50 -07001055 owner = thread_list->SuspendThreadByThreadId(owner_thread_id,
1056 SuspendReason::kInternal,
1057 &timed_out);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07001058 }
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -07001059 if (owner != nullptr) {
1060 // We succeeded in suspending the thread, check the lock's status didn't change.
1061 lock_word = obj->GetLockWord(true);
1062 if (lock_word.GetState() == LockWord::kThinLocked &&
1063 lock_word.ThinLockOwner() == owner_thread_id) {
1064 // Go ahead and inflate the lock.
1065 Inflate(self, owner, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001066 }
Alex Light88fd7202017-06-30 08:31:59 -07001067 bool resumed = thread_list->Resume(owner, SuspendReason::kInternal);
1068 DCHECK(resumed);
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001069 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07001070 self->SetMonitorEnterObject(nullptr);
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001071 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001072}
1073
Ian Rogers719d1a32014-03-06 12:13:39 -08001074// Fool annotalysis into thinking that the lock on obj is acquired.
1075static mirror::Object* FakeLock(mirror::Object* obj)
1076 EXCLUSIVE_LOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
1077 return obj;
1078}
1079
1080// Fool annotalysis into thinking that the lock on obj is release.
1081static mirror::Object* FakeUnlock(mirror::Object* obj)
1082 UNLOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
1083 return obj;
1084}
1085
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07001086mirror::Object* Monitor::MonitorEnter(Thread* self, mirror::Object* obj, bool trylock) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001087 DCHECK(self != nullptr);
1088 DCHECK(obj != nullptr);
Mathieu Chartier2d096c92015-10-12 16:18:20 -07001089 self->AssertThreadSuspensionIsAllowable();
Ian Rogers719d1a32014-03-06 12:13:39 -08001090 obj = FakeLock(obj);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001091 uint32_t thread_id = self->GetThreadId();
1092 size_t contention_count = 0;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001093 StackHandleScope<1> hs(self);
1094 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001095 while (true) {
Hans Boehmb3da36c2016-12-15 13:12:59 -08001096 // We initially read the lockword with ordinary Java/relaxed semantics. When stronger
1097 // semantics are needed, we address it below. Since GetLockWord bottoms out to a relaxed load,
1098 // we can fix it later, in an infrequently executed case, with a fence.
1099 LockWord lock_word = h_obj->GetLockWord(false);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001100 switch (lock_word.GetState()) {
1101 case LockWord::kUnlocked: {
Hans Boehmb3da36c2016-12-15 13:12:59 -08001102 // No ordering required for preceding lockword read, since we retest.
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001103 LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0, lock_word.GCState()));
Mathieu Chartier42c2e502018-06-19 12:30:56 -07001104 if (h_obj->CasLockWord(lock_word, thin_locked, CASMode::kWeak, std::memory_order_acquire)) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001105 AtraceMonitorLock(self, h_obj.Get(), /* is_wait= */ false);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001106 return h_obj.Get(); // Success!
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001107 }
1108 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -07001109 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001110 case LockWord::kThinLocked: {
1111 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1112 if (owner_thread_id == thread_id) {
Hans Boehmb3da36c2016-12-15 13:12:59 -08001113 // No ordering required for initial lockword read.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001114 // We own the lock, increase the recursion count.
1115 uint32_t new_count = lock_word.ThinLockCount() + 1;
1116 if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001117 LockWord thin_locked(LockWord::FromThinLockId(thread_id,
1118 new_count,
1119 lock_word.GCState()));
Hans Boehmb3da36c2016-12-15 13:12:59 -08001120 // Only this thread pays attention to the count. Thus there is no need for stronger
1121 // than relaxed memory ordering.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001122 if (!kUseReadBarrier) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001123 h_obj->SetLockWord(thin_locked, /* as_volatile= */ false);
1124 AtraceMonitorLock(self, h_obj.Get(), /* is_wait= */ false);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001125 return h_obj.Get(); // Success!
1126 } else {
1127 // Use CAS to preserve the read barrier state.
Mathieu Chartier42c2e502018-06-19 12:30:56 -07001128 if (h_obj->CasLockWord(lock_word,
1129 thin_locked,
1130 CASMode::kWeak,
1131 std::memory_order_relaxed)) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001132 AtraceMonitorLock(self, h_obj.Get(), /* is_wait= */ false);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001133 return h_obj.Get(); // Success!
1134 }
1135 }
1136 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -07001137 } else {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001138 // We'd overflow the recursion count, so inflate the monitor.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001139 InflateThinLocked(self, h_obj, lock_word, 0);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001140 }
1141 } else {
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07001142 if (trylock) {
1143 return nullptr;
1144 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001145 // Contention.
1146 contention_count++;
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001147 Runtime* runtime = Runtime::Current();
Hans Boehmb3da36c2016-12-15 13:12:59 -08001148 if (contention_count <= runtime->GetMaxSpinsBeforeThinLockInflation()) {
Alex Light77fee872017-09-05 14:51:49 -07001149 // TODO: Consider switching the thread state to kWaitingForLockInflation when we are
1150 // yielding. Use sched_yield instead of NanoSleep since NanoSleep can wait much longer
1151 // than the parameter you pass in. This can cause thread suspension to take excessively
1152 // long and make long pauses. See b/16307460.
Hans Boehmb3da36c2016-12-15 13:12:59 -08001153 // TODO: We should literally spin first, without sched_yield. Sched_yield either does
1154 // nothing (at significant expense), or guarantees that we wait at least microseconds.
1155 // If the owner is running, I would expect the median lock hold time to be hundreds
1156 // of nanoseconds or less.
Mathieu Chartier251755c2014-07-15 18:10:25 -07001157 sched_yield();
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001158 } else {
1159 contention_count = 0;
Hans Boehmb3da36c2016-12-15 13:12:59 -08001160 // No ordering required for initial lockword read. Install rereads it anyway.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001161 InflateThinLocked(self, h_obj, lock_word, 0);
Elliott Hughes5f791332011-09-15 17:45:30 -07001162 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001163 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001164 continue; // Start from the beginning.
Elliott Hughes5f791332011-09-15 17:45:30 -07001165 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001166 case LockWord::kFatLocked: {
Hans Boehmb3da36c2016-12-15 13:12:59 -08001167 // We should have done an acquire read of the lockword initially, to ensure
1168 // visibility of the monitor data structure. Use an explicit fence instead.
Orion Hodson27b96762018-03-13 16:06:57 +00001169 std::atomic_thread_fence(std::memory_order_acquire);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001170 Monitor* mon = lock_word.FatLockMonitor();
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07001171 if (trylock) {
1172 return mon->TryLock(self) ? h_obj.Get() : nullptr;
1173 } else {
1174 mon->Lock(self);
1175 return h_obj.Get(); // Success!
1176 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001177 }
Ian Rogers719d1a32014-03-06 12:13:39 -08001178 case LockWord::kHashCode:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001179 // Inflate with the existing hashcode.
Hans Boehmb3da36c2016-12-15 13:12:59 -08001180 // Again no ordering required for initial lockword read, since we don't rely
1181 // on the visibility of any prior computation.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001182 Inflate(self, nullptr, h_obj.Get(), lock_word.GetHashCode());
Ian Rogers719d1a32014-03-06 12:13:39 -08001183 continue; // Start from the beginning.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001184 default: {
1185 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Andreas Gampec7ed09b2016-04-25 20:08:55 -07001186 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001187 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001188 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001189 }
1190}
1191
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001192bool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001193 DCHECK(self != nullptr);
1194 DCHECK(obj != nullptr);
Mathieu Chartier2d096c92015-10-12 16:18:20 -07001195 self->AssertThreadSuspensionIsAllowable();
Ian Rogers719d1a32014-03-06 12:13:39 -08001196 obj = FakeUnlock(obj);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001197 StackHandleScope<1> hs(self);
1198 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001199 while (true) {
1200 LockWord lock_word = obj->GetLockWord(true);
1201 switch (lock_word.GetState()) {
1202 case LockWord::kHashCode:
1203 // Fall-through.
1204 case LockWord::kUnlocked:
Mathieu Chartier61b3cd42016-04-18 11:43:29 -07001205 FailedUnlock(h_obj.Get(), self->GetThreadId(), 0u, nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001206 return false; // Failure.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001207 case LockWord::kThinLocked: {
1208 uint32_t thread_id = self->GetThreadId();
1209 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1210 if (owner_thread_id != thread_id) {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -07001211 FailedUnlock(h_obj.Get(), thread_id, owner_thread_id, nullptr);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001212 return false; // Failure.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001213 } else {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001214 // We own the lock, decrease the recursion count.
1215 LockWord new_lw = LockWord::Default();
1216 if (lock_word.ThinLockCount() != 0) {
1217 uint32_t new_count = lock_word.ThinLockCount() - 1;
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001218 new_lw = LockWord::FromThinLockId(thread_id, new_count, lock_word.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001219 } else {
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001220 new_lw = LockWord::FromDefault(lock_word.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001221 }
1222 if (!kUseReadBarrier) {
1223 DCHECK_EQ(new_lw.ReadBarrierState(), 0U);
Hans Boehmb3da36c2016-12-15 13:12:59 -08001224 // TODO: This really only needs memory_order_release, but we currently have
1225 // no way to specify that. In fact there seem to be no legitimate uses of SetLockWord
1226 // with a final argument of true. This slows down x86 and ARMv7, but probably not v8.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001227 h_obj->SetLockWord(new_lw, true);
Andreas Gampe6e759ad2016-05-17 10:13:10 -07001228 AtraceMonitorUnlock();
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001229 // Success!
1230 return true;
1231 } else {
1232 // Use CAS to preserve the read barrier state.
Mathieu Chartier42c2e502018-06-19 12:30:56 -07001233 if (h_obj->CasLockWord(lock_word, new_lw, CASMode::kWeak, std::memory_order_release)) {
Andreas Gampe6e759ad2016-05-17 10:13:10 -07001234 AtraceMonitorUnlock();
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001235 // Success!
1236 return true;
1237 }
1238 }
1239 continue; // Go again.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001240 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001241 }
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001242 case LockWord::kFatLocked: {
1243 Monitor* mon = lock_word.FatLockMonitor();
1244 return mon->Unlock(self);
1245 }
1246 default: {
1247 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1248 return false;
1249 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001250 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001251 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001252}
1253
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001254void Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
Elliott Hughes4cd121e2013-01-07 17:35:41 -08001255 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001256 DCHECK(self != nullptr);
1257 DCHECK(obj != nullptr);
Alex Light77fee872017-09-05 14:51:49 -07001258 StackHandleScope<1> hs(self);
1259 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
1260
1261 Runtime::Current()->GetRuntimeCallbacks()->ObjectWaitStart(h_obj, ms);
Alex Light848574c2017-09-25 16:59:39 -07001262 if (UNLIKELY(self->ObserveAsyncException() || self->IsExceptionPending())) {
Alex Light77fee872017-09-05 14:51:49 -07001263 // See b/65558434 for information on handling of exceptions here.
1264 return;
1265 }
1266
1267 LockWord lock_word = h_obj->GetLockWord(true);
Ian Rogers43c69cc2014-08-15 11:09:28 -07001268 while (lock_word.GetState() != LockWord::kFatLocked) {
1269 switch (lock_word.GetState()) {
1270 case LockWord::kHashCode:
1271 // Fall-through.
1272 case LockWord::kUnlocked:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001273 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
1274 return; // Failure.
Ian Rogers43c69cc2014-08-15 11:09:28 -07001275 case LockWord::kThinLocked: {
1276 uint32_t thread_id = self->GetThreadId();
1277 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1278 if (owner_thread_id != thread_id) {
1279 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
1280 return; // Failure.
1281 } else {
1282 // We own the lock, inflate to enqueue ourself on the Monitor. May fail spuriously so
1283 // re-load.
Alex Light77fee872017-09-05 14:51:49 -07001284 Inflate(self, self, h_obj.Get(), 0);
1285 lock_word = h_obj->GetLockWord(true);
Ian Rogers43c69cc2014-08-15 11:09:28 -07001286 }
1287 break;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001288 }
Ian Rogers43c69cc2014-08-15 11:09:28 -07001289 case LockWord::kFatLocked: // Unreachable given the loop condition above. Fall-through.
1290 default: {
1291 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1292 return;
1293 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001294 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001295 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001296 Monitor* mon = lock_word.FatLockMonitor();
1297 mon->Wait(self, ms, ns, interruptShouldThrow, why);
Elliott Hughes5f791332011-09-15 17:45:30 -07001298}
1299
Ian Rogers13c479e2013-10-11 07:59:01 -07001300void Monitor::DoNotify(Thread* self, mirror::Object* obj, bool notify_all) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001301 DCHECK(self != nullptr);
1302 DCHECK(obj != nullptr);
1303 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001304 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001305 case LockWord::kHashCode:
1306 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001307 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -08001308 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001309 return; // Failure.
1310 case LockWord::kThinLocked: {
1311 uint32_t thread_id = self->GetThreadId();
1312 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1313 if (owner_thread_id != thread_id) {
1314 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
1315 return; // Failure.
1316 } else {
1317 // We own the lock but there's no Monitor and therefore no waiters.
1318 return; // Success.
1319 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001320 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001321 case LockWord::kFatLocked: {
1322 Monitor* mon = lock_word.FatLockMonitor();
1323 if (notify_all) {
1324 mon->NotifyAll(self);
1325 } else {
1326 mon->Notify(self);
1327 }
1328 return; // Success.
1329 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001330 default: {
1331 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1332 return;
1333 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001334 }
1335}
1336
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001337uint32_t Monitor::GetLockOwnerThreadId(mirror::Object* obj) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001338 DCHECK(obj != nullptr);
1339 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001340 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001341 case LockWord::kHashCode:
1342 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001343 case LockWord::kUnlocked:
1344 return ThreadList::kInvalidThreadId;
1345 case LockWord::kThinLocked:
1346 return lock_word.ThinLockOwner();
1347 case LockWord::kFatLocked: {
1348 Monitor* mon = lock_word.FatLockMonitor();
1349 return mon->GetOwnerThreadId();
Elliott Hughes5f791332011-09-15 17:45:30 -07001350 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001351 default: {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001352 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001353 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001354 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001355 }
1356}
1357
Andreas Gampef3ebcce2017-12-11 20:40:23 -08001358ThreadState Monitor::FetchState(const Thread* thread,
1359 /* out */ mirror::Object** monitor_object,
1360 /* out */ uint32_t* lock_owner_tid) {
1361 DCHECK(monitor_object != nullptr);
1362 DCHECK(lock_owner_tid != nullptr);
1363
1364 *monitor_object = nullptr;
1365 *lock_owner_tid = ThreadList::kInvalidThreadId;
1366
1367 ThreadState state = thread->GetState();
1368
1369 switch (state) {
1370 case kWaiting:
1371 case kTimedWaiting:
1372 case kSleeping:
1373 {
1374 Thread* self = Thread::Current();
1375 MutexLock mu(self, *thread->GetWaitMutex());
1376 Monitor* monitor = thread->GetWaitMonitor();
1377 if (monitor != nullptr) {
1378 *monitor_object = monitor->GetObject();
Ian Rogersd803bc72014-04-01 15:33:03 -07001379 }
1380 }
Andreas Gampef3ebcce2017-12-11 20:40:23 -08001381 break;
1382
1383 case kBlocked:
1384 case kWaitingForLockInflation:
1385 {
1386 mirror::Object* lock_object = thread->GetMonitorEnterObject();
1387 if (lock_object != nullptr) {
1388 if (kUseReadBarrier && Thread::Current()->GetIsGcMarking()) {
1389 // We may call Thread::Dump() in the middle of the CC thread flip and this thread's stack
1390 // may have not been flipped yet and "pretty_object" may be a from-space (stale) ref, in
1391 // which case the GetLockOwnerThreadId() call below will crash. So explicitly mark/forward
1392 // it here.
1393 lock_object = ReadBarrier::Mark(lock_object);
1394 }
1395 *monitor_object = lock_object;
1396 *lock_owner_tid = lock_object->GetLockOwnerThreadId();
1397 }
Ian Rogersd803bc72014-04-01 15:33:03 -07001398 }
Andreas Gampef3ebcce2017-12-11 20:40:23 -08001399 break;
1400
1401 default:
1402 break;
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001403 }
Andreas Gampef3ebcce2017-12-11 20:40:23 -08001404
1405 return state;
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001406}
1407
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001408mirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -08001409 // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
1410 // definition of contended that includes a monitor a thread is trying to enter...
Ian Rogersdd7624d2014-03-14 17:43:00 -07001411 mirror::Object* result = thread->GetMonitorEnterObject();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001412 if (result == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001413 // ...but also a monitor that the thread is waiting on.
Ian Rogersdd7624d2014-03-14 17:43:00 -07001414 MutexLock mu(Thread::Current(), *thread->GetWaitMutex());
1415 Monitor* monitor = thread->GetWaitMonitor();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001416 if (monitor != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001417 result = monitor->GetObject();
Elliott Hughesf9501702013-01-11 11:22:27 -08001418 }
1419 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001420 return result;
Elliott Hughesf9501702013-01-11 11:22:27 -08001421}
1422
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001423void Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
Andreas Gampe760172c2014-08-16 13:41:10 -07001424 void* callback_context, bool abort_on_failure) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001425 ArtMethod* m = stack_visitor->GetMethod();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001426 CHECK(m != nullptr);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001427
1428 // Native methods are an easy special case.
1429 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
1430 if (m->IsNative()) {
1431 if (m->IsSynchronized()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001432 mirror::Object* jni_this =
1433 stack_visitor->GetCurrentHandleScope(sizeof(void*))->GetReference(0);
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001434 callback(jni_this, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001435 }
1436 return;
1437 }
1438
jeffhao61f916c2012-10-25 17:48:51 -07001439 // Proxy methods should not be synchronized.
1440 if (m->IsProxyMethod()) {
1441 CHECK(!m->IsSynchronized());
1442 return;
1443 }
1444
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001445 // Is there any reason to believe there's any synchronization in this method?
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001446 CHECK(m->GetCodeItem() != nullptr) << m->PrettyMethod();
David Sehr0225f8e2018-01-31 08:52:24 +00001447 CodeItemDataAccessor accessor(m->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001448 if (accessor.TriesSize() == 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001449 return; // No "tries" implies no synchronization, so no held locks to report.
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001450 }
1451
Andreas Gampe760172c2014-08-16 13:41:10 -07001452 // Get the dex pc. If abort_on_failure is false, GetDexPc will not abort in the case it cannot
1453 // find the dex pc, and instead return kDexNoIndex. Then bail out, as it indicates we have an
1454 // inconsistent stack anyways.
1455 uint32_t dex_pc = stack_visitor->GetDexPc(abort_on_failure);
Andreas Gampee2abbc62017-09-15 11:59:26 -07001456 if (!abort_on_failure && dex_pc == dex::kDexNoIndex) {
David Sehr709b0702016-10-13 09:12:37 -07001457 LOG(ERROR) << "Could not find dex_pc for " << m->PrettyMethod();
Andreas Gampe760172c2014-08-16 13:41:10 -07001458 return;
1459 }
1460
Elliott Hughes80537bb2013-01-04 16:37:26 -08001461 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
1462 // the locks held in this stack frame.
Andreas Gampeaaf0d382017-11-27 14:10:21 -08001463 std::vector<verifier::MethodVerifier::DexLockInfo> monitor_enter_dex_pcs;
Andreas Gampe6cc23ac2018-08-24 15:22:43 -07001464 verifier::MethodVerifier::FindLocksAtDexPc(m,
1465 dex_pc,
1466 &monitor_enter_dex_pcs,
1467 Runtime::Current()->GetTargetSdkVersion());
Andreas Gampeaaf0d382017-11-27 14:10:21 -08001468 for (verifier::MethodVerifier::DexLockInfo& dex_lock_info : monitor_enter_dex_pcs) {
1469 // As a debug check, check that dex PC corresponds to a monitor-enter.
1470 if (kIsDebugBuild) {
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001471 const Instruction& monitor_enter_instruction = accessor.InstructionAt(dex_lock_info.dex_pc);
1472 CHECK_EQ(monitor_enter_instruction.Opcode(), Instruction::MONITOR_ENTER)
Andreas Gampeaaf0d382017-11-27 14:10:21 -08001473 << "expected monitor-enter @" << dex_lock_info.dex_pc << "; was "
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001474 << reinterpret_cast<const void*>(&monitor_enter_instruction);
Andreas Gampeaaf0d382017-11-27 14:10:21 -08001475 }
Elliott Hughes80537bb2013-01-04 16:37:26 -08001476
Andreas Gampeaaf0d382017-11-27 14:10:21 -08001477 // Iterate through the set of dex registers, as the compiler may not have held all of them
1478 // live.
1479 bool success = false;
1480 for (uint32_t dex_reg : dex_lock_info.dex_registers) {
1481 uint32_t value;
1482 success = stack_visitor->GetVReg(m, dex_reg, kReferenceVReg, &value);
1483 if (success) {
1484 mirror::Object* o = reinterpret_cast<mirror::Object*>(value);
1485 callback(o, callback_context);
1486 break;
1487 }
1488 }
1489 DCHECK(success) << "Failed to find/read reference for monitor-enter at dex pc "
1490 << dex_lock_info.dex_pc
1491 << " in method "
1492 << m->PrettyMethod();
1493 if (!success) {
1494 LOG(WARNING) << "Had a lock reported for dex pc " << dex_lock_info.dex_pc
1495 << " but was not able to fetch a corresponding object!";
1496 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001497 }
1498}
1499
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001500bool Monitor::IsValidLockWord(LockWord lock_word) {
1501 switch (lock_word.GetState()) {
1502 case LockWord::kUnlocked:
1503 // Nothing to check.
1504 return true;
1505 case LockWord::kThinLocked:
1506 // Basic sanity check of owner.
1507 return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
1508 case LockWord::kFatLocked: {
1509 // Check the monitor appears in the monitor list.
1510 Monitor* mon = lock_word.FatLockMonitor();
1511 MonitorList* list = Runtime::Current()->GetMonitorList();
1512 MutexLock mu(Thread::Current(), list->monitor_list_lock_);
1513 for (Monitor* list_mon : list->list_) {
1514 if (mon == list_mon) {
1515 return true; // Found our monitor.
1516 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001517 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001518 return false; // Fail - unowned monitor in an object.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001519 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001520 case LockWord::kHashCode:
1521 return true;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001522 default:
1523 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001524 UNREACHABLE();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001525 }
1526}
1527
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001528bool Monitor::IsLocked() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001529 MutexLock mu(Thread::Current(), monitor_lock_);
1530 return owner_ != nullptr;
1531}
1532
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -07001533void Monitor::TranslateLocation(ArtMethod* method,
1534 uint32_t dex_pc,
1535 const char** source_file,
1536 int32_t* line_number) {
jeffhao33dc7712011-11-09 17:54:24 -08001537 // If method is null, location is unknown
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001538 if (method == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001539 *source_file = "";
1540 *line_number = 0;
jeffhao33dc7712011-11-09 17:54:24 -08001541 return;
1542 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001543 *source_file = method->GetDeclaringClassSourceFile();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001544 if (*source_file == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001545 *source_file = "";
Elliott Hughes12c51e32012-01-17 20:25:05 -08001546 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001547 *line_number = method->GetLineNumFromDexPC(dex_pc);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001548}
1549
1550uint32_t Monitor::GetOwnerThreadId() {
1551 MutexLock mu(Thread::Current(), monitor_lock_);
1552 Thread* owner = owner_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001553 if (owner != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001554 return owner->GetThreadId();
1555 } else {
1556 return ThreadList::kInvalidThreadId;
1557 }
jeffhao33dc7712011-11-09 17:54:24 -08001558}
1559
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001560MonitorList::MonitorList()
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001561 : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock", kMonitorListLock),
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001562 monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001563}
1564
1565MonitorList::~MonitorList() {
Andreas Gampe74240812014-04-17 10:35:09 -07001566 Thread* self = Thread::Current();
1567 MutexLock mu(self, monitor_list_lock_);
1568 // Release all monitors to the pool.
1569 // TODO: Is it an invariant that *all* open monitors are in the list? Then we could
1570 // clear faster in the pool.
1571 MonitorPool::ReleaseMonitors(self, &list_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001572}
1573
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001574void MonitorList::DisallowNewMonitors() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001575 CHECK(!kUseReadBarrier);
Ian Rogers50b35e22012-10-04 10:09:15 -07001576 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001577 allow_new_monitors_ = false;
1578}
1579
1580void MonitorList::AllowNewMonitors() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001581 CHECK(!kUseReadBarrier);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001582 Thread* self = Thread::Current();
1583 MutexLock mu(self, monitor_list_lock_);
1584 allow_new_monitors_ = true;
1585 monitor_add_condition_.Broadcast(self);
1586}
1587
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001588void MonitorList::BroadcastForNewMonitors() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001589 Thread* self = Thread::Current();
1590 MutexLock mu(self, monitor_list_lock_);
1591 monitor_add_condition_.Broadcast(self);
1592}
1593
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001594void MonitorList::Add(Monitor* m) {
1595 Thread* self = Thread::Current();
1596 MutexLock mu(self, monitor_list_lock_);
Hiroshi Yamauchif1c6f872017-01-06 12:23:47 -08001597 // CMS needs this to block for concurrent reference processing because an object allocated during
1598 // the GC won't be marked and concurrent reference processing would incorrectly clear the JNI weak
1599 // ref. But CC (kUseReadBarrier == true) doesn't because of the to-space invariant.
1600 while (!kUseReadBarrier && UNLIKELY(!allow_new_monitors_)) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -07001601 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
1602 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -08001603 self->CheckEmptyCheckpointFromWeakRefAccess(&monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001604 monitor_add_condition_.WaitHoldingLocks(self);
1605 }
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001606 list_.push_front(m);
1607}
1608
Mathieu Chartier97509952015-07-13 14:35:43 -07001609void MonitorList::SweepMonitorList(IsMarkedVisitor* visitor) {
Andreas Gampe74240812014-04-17 10:35:09 -07001610 Thread* self = Thread::Current();
1611 MutexLock mu(self, monitor_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001612 for (auto it = list_.begin(); it != list_.end(); ) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001613 Monitor* m = *it;
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001614 // Disable the read barrier in GetObject() as this is called by GC.
1615 mirror::Object* obj = m->GetObject<kWithoutReadBarrier>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001616 // The object of a monitor can be null if we have deflated it.
Mathieu Chartier97509952015-07-13 14:35:43 -07001617 mirror::Object* new_obj = obj != nullptr ? visitor->IsMarked(obj) : nullptr;
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001618 if (new_obj == nullptr) {
1619 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001620 << obj;
Andreas Gampe74240812014-04-17 10:35:09 -07001621 MonitorPool::ReleaseMonitor(self, m);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001622 it = list_.erase(it);
1623 } else {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001624 m->SetObject(new_obj);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001625 ++it;
1626 }
1627 }
1628}
1629
Hans Boehm6fe97e02016-05-04 18:35:57 -07001630size_t MonitorList::Size() {
1631 Thread* self = Thread::Current();
1632 MutexLock mu(self, monitor_list_lock_);
1633 return list_.size();
1634}
1635
Mathieu Chartier97509952015-07-13 14:35:43 -07001636class MonitorDeflateVisitor : public IsMarkedVisitor {
1637 public:
1638 MonitorDeflateVisitor() : self_(Thread::Current()), deflate_count_(0) {}
1639
Roland Levillainf73caca2018-08-24 17:19:07 +01001640 mirror::Object* IsMarked(mirror::Object* object) override
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001641 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001642 if (Monitor::Deflate(self_, object)) {
1643 DCHECK_NE(object->GetLockWord(true).GetState(), LockWord::kFatLocked);
1644 ++deflate_count_;
1645 // If we deflated, return null so that the monitor gets removed from the array.
1646 return nullptr;
1647 }
1648 return object; // Monitor was not deflated.
1649 }
1650
1651 Thread* const self_;
1652 size_t deflate_count_;
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001653};
1654
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001655size_t MonitorList::DeflateMonitors() {
Mathieu Chartier97509952015-07-13 14:35:43 -07001656 MonitorDeflateVisitor visitor;
1657 Locks::mutator_lock_->AssertExclusiveHeld(visitor.self_);
1658 SweepMonitorList(&visitor);
1659 return visitor.deflate_count_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001660}
1661
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001662MonitorInfo::MonitorInfo(mirror::Object* obj) : owner_(nullptr), entry_count_(0) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001663 DCHECK(obj != nullptr);
1664 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001665 switch (lock_word.GetState()) {
1666 case LockWord::kUnlocked:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001667 // Fall-through.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001668 case LockWord::kForwardingAddress:
1669 // Fall-through.
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001670 case LockWord::kHashCode:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001671 break;
1672 case LockWord::kThinLocked:
1673 owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
Alex Lightce568642017-09-05 16:54:25 -07001674 DCHECK(owner_ != nullptr) << "Thin-locked without owner!";
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001675 entry_count_ = 1 + lock_word.ThinLockCount();
1676 // Thin locks have no waiters.
1677 break;
1678 case LockWord::kFatLocked: {
1679 Monitor* mon = lock_word.FatLockMonitor();
1680 owner_ = mon->owner_;
Alex Lightce568642017-09-05 16:54:25 -07001681 // Here it is okay for the owner to be null since we don't reset the LockWord back to
1682 // kUnlocked until we get a GC. In cases where this hasn't happened yet we will have a fat
1683 // lock without an owner.
1684 if (owner_ != nullptr) {
1685 entry_count_ = 1 + mon->lock_count_;
1686 } else {
1687 DCHECK_EQ(mon->lock_count_, 0) << "Monitor is fat-locked without any owner!";
1688 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001689 for (Thread* waiter = mon->wait_set_; waiter != nullptr; waiter = waiter->GetWaitNext()) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001690 waiters_.push_back(waiter);
1691 }
1692 break;
Elliott Hughesf327e072013-01-09 16:01:26 -08001693 }
1694 }
1695}
1696
Elliott Hughes5f791332011-09-15 17:45:30 -07001697} // namespace art