blob: 0f0a378142d7aa2e4f5b8bcadf100d575b864072 [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),
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700100 hash_code_(hash_code),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700101 locking_method_(nullptr),
Ian Rogersef7d42f2014-01-06 12:55:46 -0800102 locking_dex_pc_(0),
Andreas Gampe74240812014-04-17 10:35:09 -0700103 monitor_id_(MonitorPool::ComputeMonitorId(this, self)) {
104#ifdef __LP64__
105 DCHECK(false) << "Should not be reached in 64b";
106 next_free_ = nullptr;
107#endif
108 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
109 // with the owner unlocking the thin-lock.
110 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
111 // The identity hash code is set for the life time of the monitor.
112}
113
114Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code,
115 MonitorId id)
116 : monitor_lock_("a monitor lock", kMonitorLock),
117 monitor_contenders_("monitor contenders", monitor_lock_),
118 num_waiters_(0),
119 owner_(owner),
120 lock_count_(0),
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700121 obj_(GcRoot<mirror::Object>(obj)),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700122 wait_set_(nullptr),
Andreas Gampe74240812014-04-17 10:35:09 -0700123 hash_code_(hash_code),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700124 locking_method_(nullptr),
Andreas Gampe74240812014-04-17 10:35:09 -0700125 locking_dex_pc_(0),
126 monitor_id_(id) {
127#ifdef __LP64__
128 next_free_ = nullptr;
129#endif
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700130 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
131 // with the owner unlocking the thin-lock.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800132 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700133 // The identity hash code is set for the life time of the monitor.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700134}
135
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700136int32_t Monitor::GetHashCode() {
Mathieu Chartier8bb3c682018-06-18 12:53:10 -0700137 int32_t hc = hash_code_.load(std::memory_order_relaxed);
138 if (!HasHashCode()) {
139 // Use a strong CAS to prevent spurious failures since these can make the boot image
140 // non-deterministic.
141 hash_code_.CompareAndSetStrongRelaxed(0, mirror::Object::GenerateIdentityHashCode());
142 hc = hash_code_.load(std::memory_order_relaxed);
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700143 }
144 DCHECK(HasHashCode());
Mathieu Chartier8bb3c682018-06-18 12:53:10 -0700145 return hc;
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700146}
147
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700148bool Monitor::Install(Thread* self) {
149 MutexLock mu(self, monitor_lock_); // Uncontended mutex acquisition as monitor isn't yet public.
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700150 CHECK(owner_ == nullptr || owner_ == self || owner_->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700151 // Propagate the lock state.
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700152 LockWord lw(GetObject()->GetLockWord(false));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700153 switch (lw.GetState()) {
154 case LockWord::kThinLocked: {
155 CHECK_EQ(owner_->GetThreadId(), lw.ThinLockOwner());
156 lock_count_ = lw.ThinLockCount();
157 break;
158 }
159 case LockWord::kHashCode: {
Orion Hodson88591fe2018-03-06 13:35:43 +0000160 CHECK_EQ(hash_code_.load(std::memory_order_relaxed), static_cast<int32_t>(lw.GetHashCode()));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700161 break;
162 }
163 case LockWord::kFatLocked: {
164 // The owner_ is suspended but another thread beat us to install a monitor.
165 return false;
166 }
167 case LockWord::kUnlocked: {
168 LOG(FATAL) << "Inflating unlocked lock word";
169 break;
170 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700171 default: {
172 LOG(FATAL) << "Invalid monitor state " << lw.GetState();
173 return false;
174 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700175 }
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700176 LockWord fat(this, lw.GCState());
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700177 // Publish the updated lock word, which may race with other threads.
Mathieu Chartier42c2e502018-06-19 12:30:56 -0700178 bool success = GetObject()->CasLockWord(lw, fat, CASMode::kWeak, std::memory_order_release);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700179 // Lock profiling.
Mathieu Chartier9728f912013-10-30 09:45:13 -0700180 if (success && owner_ != nullptr && lock_profiling_threshold_ != 0) {
Andreas Gampe6ec8ebd2014-07-25 13:36:56 -0700181 // Do not abort on dex pc errors. This can easily happen when we want to dump a stack trace on
182 // abort.
183 locking_method_ = owner_->GetCurrentMethod(&locking_dex_pc_, false);
Andreas Gampe5a387272017-11-06 19:47:16 -0800184 if (locking_method_ != nullptr && UNLIKELY(locking_method_->IsProxyMethod())) {
185 // Grab another frame. Proxy methods are not helpful for lock profiling. This should be rare
186 // enough that it's OK to walk the stack twice.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100187 struct NextMethodVisitor final : public StackVisitor {
Andreas Gampe5a387272017-11-06 19:47:16 -0800188 explicit NextMethodVisitor(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_)
189 : StackVisitor(thread,
190 nullptr,
191 StackVisitor::StackWalkKind::kIncludeInlinedFrames,
192 false),
193 count_(0),
194 method_(nullptr),
195 dex_pc_(0) {}
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100196 bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe5a387272017-11-06 19:47:16 -0800197 ArtMethod* m = GetMethod();
198 if (m->IsRuntimeMethod()) {
199 // Continue if this is a runtime method.
200 return true;
201 }
202 count_++;
203 if (count_ == 2u) {
204 method_ = m;
205 dex_pc_ = GetDexPc(false);
206 return false;
207 }
208 return true;
209 }
210 size_t count_;
211 ArtMethod* method_;
212 uint32_t dex_pc_;
213 };
214 NextMethodVisitor nmv(owner_);
215 nmv.WalkStack();
216 locking_method_ = nmv.method_;
217 locking_dex_pc_ = nmv.dex_pc_;
218 }
219 DCHECK(locking_method_ == nullptr || !locking_method_->IsProxyMethod());
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700220 }
221 return success;
Elliott Hughes5f791332011-09-15 17:45:30 -0700222}
223
224Monitor::~Monitor() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700225 // Deflated monitors have a null object.
Elliott Hughes5f791332011-09-15 17:45:30 -0700226}
227
Elliott Hughes5f791332011-09-15 17:45:30 -0700228void Monitor::AppendToWaitSet(Thread* thread) {
229 DCHECK(owner_ == Thread::Current());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700230 DCHECK(thread != nullptr);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700231 DCHECK(thread->GetWaitNext() == nullptr) << thread->GetWaitNext();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700232 if (wait_set_ == nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700233 wait_set_ = thread;
234 return;
235 }
236
237 // push_back.
238 Thread* t = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700239 while (t->GetWaitNext() != nullptr) {
240 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700241 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700242 t->SetWaitNext(thread);
Elliott Hughes5f791332011-09-15 17:45:30 -0700243}
244
Elliott Hughes5f791332011-09-15 17:45:30 -0700245void Monitor::RemoveFromWaitSet(Thread *thread) {
246 DCHECK(owner_ == Thread::Current());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700247 DCHECK(thread != nullptr);
248 if (wait_set_ == nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700249 return;
250 }
251 if (wait_set_ == thread) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700252 wait_set_ = thread->GetWaitNext();
253 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700254 return;
255 }
256
257 Thread* t = wait_set_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700258 while (t->GetWaitNext() != nullptr) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700259 if (t->GetWaitNext() == thread) {
260 t->SetWaitNext(thread->GetWaitNext());
261 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700262 return;
263 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700264 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700265 }
266}
267
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700268void Monitor::SetObject(mirror::Object* object) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700269 obj_ = GcRoot<mirror::Object>(object);
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700270}
271
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700272// Note: Adapted from CurrentMethodVisitor in thread.cc. We must not resolve here.
273
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100274struct NthCallerWithDexPcVisitor final : public StackVisitor {
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700275 explicit NthCallerWithDexPcVisitor(Thread* thread, size_t frame)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700276 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +0100277 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700278 method_(nullptr),
279 dex_pc_(0),
280 current_frame_number_(0),
281 wanted_frame_number_(frame) {}
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100282 bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700283 ArtMethod* m = GetMethod();
284 if (m == nullptr || m->IsRuntimeMethod()) {
285 // Runtime method, upcall, or resolution issue. Skip.
286 return true;
287 }
288
289 // Is this the requested frame?
290 if (current_frame_number_ == wanted_frame_number_) {
291 method_ = m;
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700292 dex_pc_ = GetDexPc(/* abort_on_failure=*/ false);
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700293 return false;
294 }
295
296 // Look for more.
297 current_frame_number_++;
298 return true;
299 }
300
301 ArtMethod* method_;
302 uint32_t dex_pc_;
303
304 private:
305 size_t current_frame_number_;
306 const size_t wanted_frame_number_;
307};
308
309// This function is inlined and just helps to not have the VLOG and ATRACE check at all the
310// potential tracing points.
311void Monitor::AtraceMonitorLock(Thread* self, mirror::Object* obj, bool is_wait) {
312 if (UNLIKELY(VLOG_IS_ON(systrace_lock_logging) && ATRACE_ENABLED())) {
313 AtraceMonitorLockImpl(self, obj, is_wait);
314 }
315}
316
317void Monitor::AtraceMonitorLockImpl(Thread* self, mirror::Object* obj, bool is_wait) {
318 // Wait() requires a deeper call stack to be useful. Otherwise you'll see "Waiting at
319 // Object.java". Assume that we'll wait a nontrivial amount, so it's OK to do a longer
320 // stack walk than if !is_wait.
321 NthCallerWithDexPcVisitor visitor(self, is_wait ? 1U : 0U);
322 visitor.WalkStack(false);
323 const char* prefix = is_wait ? "Waiting on " : "Locking ";
324
325 const char* filename;
326 int32_t line_number;
327 TranslateLocation(visitor.method_, visitor.dex_pc_, &filename, &line_number);
328
329 // It would be nice to have a stable "ID" for the object here. However, the only stable thing
330 // would be the identity hashcode. But we cannot use IdentityHashcode here: For one, there are
331 // times when it is unsafe to make that call (see stack dumping for an explanation). More
332 // importantly, we would have to give up on thin-locking when adding systrace locks, as the
333 // identity hashcode is stored in the lockword normally (so can't be used with thin-locks).
334 //
335 // Because of thin-locks we also cannot use the monitor id (as there is no monitor). Monitor ids
336 // also do not have to be stable, as the monitor may be deflated.
337 std::string tmp = StringPrintf("%s %d at %s:%d",
338 prefix,
339 (obj == nullptr ? -1 : static_cast<int32_t>(reinterpret_cast<uintptr_t>(obj))),
340 (filename != nullptr ? filename : "null"),
341 line_number);
342 ATRACE_BEGIN(tmp.c_str());
343}
344
345void Monitor::AtraceMonitorUnlock() {
346 if (UNLIKELY(VLOG_IS_ON(systrace_lock_logging))) {
347 ATRACE_END();
348 }
349}
350
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700351std::string Monitor::PrettyContentionInfo(const std::string& owner_name,
352 pid_t owner_tid,
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700353 ArtMethod* owners_method,
354 uint32_t owners_dex_pc,
355 size_t num_waiters) {
Hiroshi Yamauchi71cd68d2017-01-25 18:28:12 -0800356 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700357 const char* owners_filename;
Goran Jakovljevic49c882b2016-04-19 10:27:21 +0200358 int32_t owners_line_number = 0;
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700359 if (owners_method != nullptr) {
360 TranslateLocation(owners_method, owners_dex_pc, &owners_filename, &owners_line_number);
361 }
362 std::ostringstream oss;
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700363 oss << "monitor contention with owner " << owner_name << " (" << owner_tid << ")";
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700364 if (owners_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700365 oss << " at " << owners_method->PrettyMethod();
Mathieu Chartier36891fe2016-04-28 17:21:08 -0700366 oss << "(" << owners_filename << ":" << owners_line_number << ")";
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700367 }
368 oss << " waiters=" << num_waiters;
369 return oss.str();
370}
371
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700372bool Monitor::TryLockLocked(Thread* self) {
373 if (owner_ == nullptr) { // Unowned.
374 owner_ = self;
375 CHECK_EQ(lock_count_, 0);
376 // When debugging, save the current monitor holder for future
377 // acquisition failures to use in sampled logging.
378 if (lock_profiling_threshold_ != 0) {
379 locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
Andreas Gampe5a387272017-11-06 19:47:16 -0800380 // We don't expect a proxy method here.
381 DCHECK(locking_method_ == nullptr || !locking_method_->IsProxyMethod());
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700382 }
383 } else if (owner_ == self) { // Recursive.
384 lock_count_++;
385 } else {
386 return false;
387 }
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700388 AtraceMonitorLock(self, GetObject(), /* is_wait= */ false);
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700389 return true;
390}
391
392bool Monitor::TryLock(Thread* self) {
393 MutexLock mu(self, monitor_lock_);
394 return TryLockLocked(self);
395}
396
Alex Light77fee872017-09-05 14:51:49 -0700397// Asserts that a mutex isn't held when the class comes into and out of scope.
398class ScopedAssertNotHeld {
399 public:
400 ScopedAssertNotHeld(Thread* self, Mutex& mu) : self_(self), mu_(mu) {
401 mu_.AssertNotHeld(self_);
402 }
403
404 ~ScopedAssertNotHeld() {
405 mu_.AssertNotHeld(self_);
406 }
407
408 private:
409 Thread* const self_;
410 Mutex& mu_;
411 DISALLOW_COPY_AND_ASSIGN(ScopedAssertNotHeld);
412};
413
414template <LockReason reason>
Elliott Hughes5f791332011-09-15 17:45:30 -0700415void Monitor::Lock(Thread* self) {
Alex Light77fee872017-09-05 14:51:49 -0700416 ScopedAssertNotHeld sanh(self, monitor_lock_);
417 bool called_monitors_callback = false;
418 monitor_lock_.Lock(self);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700419 while (true) {
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700420 if (TryLockLocked(self)) {
Alex Light77fee872017-09-05 14:51:49 -0700421 break;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700422 }
423 // Contended.
424 const bool log_contention = (lock_profiling_threshold_ != 0);
Xin Guanb894a192014-08-22 11:55:37 -0500425 uint64_t wait_start_ms = log_contention ? MilliTime() : 0;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700426 ArtMethod* owners_method = locking_method_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700427 uint32_t owners_dex_pc = locking_dex_pc_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700428 // Do this before releasing the lock so that we don't get deflated.
Mathieu Chartierb9001ab2014-10-03 13:28:46 -0700429 size_t num_waiters = num_waiters_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700430 ++num_waiters_;
Andreas Gampe2702d562017-02-06 09:48:00 -0800431
432 // If systrace logging is enabled, first look at the lock owner. Acquiring the monitor's
433 // lock and then re-acquiring the mutator lock can deadlock.
434 bool started_trace = false;
435 if (ATRACE_ENABLED()) {
436 if (owner_ != nullptr) { // Did the owner_ give the lock up?
437 std::ostringstream oss;
438 std::string name;
439 owner_->GetThreadName(name);
440 oss << PrettyContentionInfo(name,
441 owner_->GetTid(),
442 owners_method,
443 owners_dex_pc,
444 num_waiters);
445 // Add info for contending thread.
446 uint32_t pc;
447 ArtMethod* m = self->GetCurrentMethod(&pc);
448 const char* filename;
449 int32_t line_number;
450 TranslateLocation(m, pc, &filename, &line_number);
451 oss << " blocking from "
452 << ArtMethod::PrettyMethod(m) << "(" << (filename != nullptr ? filename : "null")
453 << ":" << line_number << ")";
454 ATRACE_BEGIN(oss.str().c_str());
455 started_trace = true;
456 }
457 }
458
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700459 monitor_lock_.Unlock(self); // Let go of locks in order.
Alex Light77fee872017-09-05 14:51:49 -0700460 // Call the contended locking cb once and only once. Also only call it if we are locking for
461 // the first time, not during a Wait wakeup.
462 if (reason == LockReason::kForLock && !called_monitors_callback) {
463 called_monitors_callback = true;
464 Runtime::Current()->GetRuntimeCallbacks()->MonitorContendedLocking(this);
465 }
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700466 self->SetMonitorEnterObject(GetObject());
Elliott Hughes5f791332011-09-15 17:45:30 -0700467 {
Hiroshi Yamauchi71cd68d2017-01-25 18:28:12 -0800468 ScopedThreadSuspension tsc(self, kBlocked); // Change to blocked and give up mutator_lock_.
Andreas Gampe2702d562017-02-06 09:48:00 -0800469 uint32_t original_owner_thread_id = 0u;
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700470 {
471 // Reacquire monitor_lock_ without mutator_lock_ for Wait.
472 MutexLock mu2(self, monitor_lock_);
473 if (owner_ != nullptr) { // Did the owner_ give the lock up?
474 original_owner_thread_id = owner_->GetThreadId();
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700475 monitor_contenders_.Wait(self); // Still contended so wait.
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800476 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700477 }
478 if (original_owner_thread_id != 0u) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700479 // Woken from contention.
480 if (log_contention) {
Andreas Gampe111b1092017-06-22 20:28:23 -0700481 uint64_t wait_ms = MilliTime() - wait_start_ms;
482 uint32_t sample_percent;
483 if (wait_ms >= lock_profiling_threshold_) {
484 sample_percent = 100;
485 } else {
486 sample_percent = 100 * wait_ms / lock_profiling_threshold_;
487 }
488 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
489 // Reacquire mutator_lock_ for logging.
490 ScopedObjectAccess soa(self);
Andreas Gampe111b1092017-06-22 20:28:23 -0700491
Andreas Gamped0210e52017-06-23 13:38:09 -0700492 bool owner_alive = false;
493 pid_t original_owner_tid = 0;
494 std::string original_owner_name;
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700495
Andreas Gamped0210e52017-06-23 13:38:09 -0700496 const bool should_dump_stacks = stack_dump_lock_profiling_threshold_ > 0 &&
497 wait_ms > stack_dump_lock_profiling_threshold_;
498 std::string owner_stack_dump;
Andreas Gampe111b1092017-06-22 20:28:23 -0700499
Andreas Gamped0210e52017-06-23 13:38:09 -0700500 // Acquire thread-list lock to find thread and keep it from dying until we've got all
501 // the info we need.
502 {
Alex Lightb1e31a82017-10-04 16:57:36 -0700503 Locks::thread_list_lock_->ExclusiveLock(Thread::Current());
Andreas Gamped0210e52017-06-23 13:38:09 -0700504
505 // Re-find the owner in case the thread got killed.
506 Thread* original_owner = Runtime::Current()->GetThreadList()->FindThreadByThreadId(
507 original_owner_thread_id);
508
509 if (original_owner != nullptr) {
510 owner_alive = true;
511 original_owner_tid = original_owner->GetTid();
512 original_owner->GetThreadName(original_owner_name);
513
514 if (should_dump_stacks) {
515 // Very long contention. Dump stacks.
516 struct CollectStackTrace : public Closure {
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100517 void Run(art::Thread* thread) override
Andreas Gamped0210e52017-06-23 13:38:09 -0700518 REQUIRES_SHARED(art::Locks::mutator_lock_) {
519 thread->DumpJavaStack(oss);
520 }
521
522 std::ostringstream oss;
523 };
524 CollectStackTrace owner_trace;
Alex Lightb1e31a82017-10-04 16:57:36 -0700525 // RequestSynchronousCheckpoint releases the thread_list_lock_ as a part of its
526 // execution.
Andreas Gamped0210e52017-06-23 13:38:09 -0700527 original_owner->RequestSynchronousCheckpoint(&owner_trace);
528 owner_stack_dump = owner_trace.oss.str();
Alex Lightb1e31a82017-10-04 16:57:36 -0700529 } else {
530 Locks::thread_list_lock_->ExclusiveUnlock(Thread::Current());
Andreas Gamped0210e52017-06-23 13:38:09 -0700531 }
Alex Lightb1e31a82017-10-04 16:57:36 -0700532 } else {
533 Locks::thread_list_lock_->ExclusiveUnlock(Thread::Current());
Andreas Gamped0210e52017-06-23 13:38:09 -0700534 }
535 // This is all the data we need. Now drop the thread-list lock, it's OK for the
536 // owner to go away now.
537 }
538
539 // If we found the owner (and thus have owner data), go and log now.
540 if (owner_alive) {
541 // Give the detailed traces for really long contention.
542 if (should_dump_stacks) {
543 // This must be here (and not above) because we cannot hold the thread-list lock
544 // while running the checkpoint.
545 std::ostringstream self_trace_oss;
546 self->DumpJavaStack(self_trace_oss);
547
548 uint32_t pc;
549 ArtMethod* m = self->GetCurrentMethod(&pc);
550
551 LOG(WARNING) << "Long "
552 << PrettyContentionInfo(original_owner_name,
553 original_owner_tid,
554 owners_method,
555 owners_dex_pc,
556 num_waiters)
557 << " in " << ArtMethod::PrettyMethod(m) << " for "
558 << PrettyDuration(MsToNs(wait_ms)) << "\n"
559 << "Current owner stack:\n" << owner_stack_dump
560 << "Contender stack:\n" << self_trace_oss.str();
561 } else if (wait_ms > kLongWaitMs && owners_method != nullptr) {
Mathieu Chartier36891fe2016-04-28 17:21:08 -0700562 uint32_t pc;
563 ArtMethod* m = self->GetCurrentMethod(&pc);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700564 // TODO: We should maybe check that original_owner is still a live thread.
565 LOG(WARNING) << "Long "
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700566 << PrettyContentionInfo(original_owner_name,
567 original_owner_tid,
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700568 owners_method,
569 owners_dex_pc,
570 num_waiters)
David Sehr709b0702016-10-13 09:12:37 -0700571 << " in " << ArtMethod::PrettyMethod(m) << " for "
572 << PrettyDuration(MsToNs(wait_ms));
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700573 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700574 LogContentionEvent(self,
Alex Light77fee872017-09-05 14:51:49 -0700575 wait_ms,
576 sample_percent,
577 owners_method,
578 owners_dex_pc);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700579 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700580 }
581 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700582 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700583 }
Andreas Gampe2702d562017-02-06 09:48:00 -0800584 if (started_trace) {
585 ATRACE_END();
586 }
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700587 self->SetMonitorEnterObject(nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700588 monitor_lock_.Lock(self); // Reacquire locks in order.
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700589 --num_waiters_;
Elliott Hughesfc861622011-10-17 17:57:47 -0700590 }
Alex Light77fee872017-09-05 14:51:49 -0700591 monitor_lock_.Unlock(self);
592 // We need to pair this with a single contended locking call. NB we match the RI behavior and call
593 // this even if MonitorEnter failed.
594 if (called_monitors_callback) {
595 CHECK(reason == LockReason::kForLock);
596 Runtime::Current()->GetRuntimeCallbacks()->MonitorContendedLocked(this);
597 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700598}
599
Alex Light77fee872017-09-05 14:51:49 -0700600template void Monitor::Lock<LockReason::kForLock>(Thread* self);
601template void Monitor::Lock<LockReason::kForWait>(Thread* self);
602
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800603static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
604 __attribute__((format(printf, 1, 2)));
605
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700606static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700607 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800608 va_list args;
609 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800610 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000611 self->ThrowNewExceptionV("Ljava/lang/IllegalMonitorStateException;", fmt, args);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700612 if (!Runtime::Current()->IsStarted() || VLOG_IS_ON(monitor)) {
Brian Carlstrom64277f32012-03-26 23:53:34 -0700613 std::ostringstream ss;
Ian Rogers62d6c772013-02-27 08:32:07 -0800614 self->Dump(ss);
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700615 LOG(Runtime::Current()->IsStarted() ? ::android::base::INFO : ::android::base::ERROR)
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000616 << self->GetException()->Dump() << "\n" << ss.str();
Brian Carlstrom64277f32012-03-26 23:53:34 -0700617 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800618 va_end(args);
619}
620
Elliott Hughesd4237412012-02-21 11:24:45 -0800621static std::string ThreadToString(Thread* thread) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700622 if (thread == nullptr) {
623 return "nullptr";
Elliott Hughesd4237412012-02-21 11:24:45 -0800624 }
625 std::ostringstream oss;
626 // TODO: alternatively, we could just return the thread's name.
627 oss << *thread;
628 return oss.str();
629}
630
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700631void Monitor::FailedUnlock(mirror::Object* o,
632 uint32_t expected_owner_thread_id,
633 uint32_t found_owner_thread_id,
Elliott Hughesffb465f2012-03-01 18:46:05 -0800634 Monitor* monitor) {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700635 // Acquire thread list lock so threads won't disappear from under us.
Elliott Hughesffb465f2012-03-01 18:46:05 -0800636 std::string current_owner_string;
637 std::string expected_owner_string;
638 std::string found_owner_string;
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700639 uint32_t current_owner_thread_id = 0u;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800640 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700641 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700642 ThreadList* const thread_list = Runtime::Current()->GetThreadList();
643 Thread* expected_owner = thread_list->FindThreadByThreadId(expected_owner_thread_id);
644 Thread* found_owner = thread_list->FindThreadByThreadId(found_owner_thread_id);
645
Elliott Hughesffb465f2012-03-01 18:46:05 -0800646 // Re-read owner now that we hold lock.
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700647 Thread* current_owner = (monitor != nullptr) ? monitor->GetOwner() : nullptr;
648 if (current_owner != nullptr) {
649 current_owner_thread_id = current_owner->GetThreadId();
650 }
Elliott Hughesffb465f2012-03-01 18:46:05 -0800651 // Get short descriptions of the threads involved.
652 current_owner_string = ThreadToString(current_owner);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700653 expected_owner_string = expected_owner != nullptr ? ThreadToString(expected_owner) : "unnamed";
654 found_owner_string = found_owner != nullptr ? ThreadToString(found_owner) : "unnamed";
Elliott Hughesffb465f2012-03-01 18:46:05 -0800655 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700656
657 if (current_owner_thread_id == 0u) {
658 if (found_owner_thread_id == 0u) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800659 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
660 " on thread '%s'",
David Sehr709b0702016-10-13 09:12:37 -0700661 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800662 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800663 } else {
664 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800665 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
666 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800667 found_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700668 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800669 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800670 }
671 } else {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700672 if (found_owner_thread_id == 0u) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800673 // Race: originally there was no owner, there is now
674 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
675 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800676 current_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700677 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800678 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800679 } else {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700680 if (found_owner_thread_id != current_owner_thread_id) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800681 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800682 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
683 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800684 found_owner_string.c_str(),
685 current_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700686 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800687 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800688 } else {
689 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
690 " on thread '%s",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800691 current_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700692 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800693 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800694 }
695 }
696 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700697}
698
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700699bool Monitor::Unlock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700700 DCHECK(self != nullptr);
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700701 uint32_t owner_thread_id = 0u;
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700702 {
703 MutexLock mu(self, monitor_lock_);
704 Thread* owner = owner_;
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700705 if (owner != nullptr) {
706 owner_thread_id = owner->GetThreadId();
707 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700708 if (owner == self) {
709 // We own the monitor, so nobody else can be in here.
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700710 AtraceMonitorUnlock();
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700711 if (lock_count_ == 0) {
712 owner_ = nullptr;
713 locking_method_ = nullptr;
714 locking_dex_pc_ = 0;
715 // Wake a contender.
716 monitor_contenders_.Signal(self);
717 } else {
718 --lock_count_;
719 }
720 return true;
Elliott Hughes5f791332011-09-15 17:45:30 -0700721 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700722 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700723 // We don't own this, so we're not allowed to unlock it.
724 // The JNI spec says that we should throw IllegalMonitorStateException in this case.
725 FailedUnlock(GetObject(), self->GetThreadId(), owner_thread_id, this);
726 return false;
Elliott Hughes5f791332011-09-15 17:45:30 -0700727}
728
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800729void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
730 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700731 DCHECK(self != nullptr);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800732 DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
Elliott Hughes5f791332011-09-15 17:45:30 -0700733
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700734 monitor_lock_.Lock(self);
735
Elliott Hughes5f791332011-09-15 17:45:30 -0700736 // Make sure that we hold the lock.
737 if (owner_ != self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700738 monitor_lock_.Unlock(self);
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700739 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700740 return;
741 }
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800742
Elliott Hughesdf42c482013-01-09 12:49:02 -0800743 // We need to turn a zero-length timed wait into a regular wait because
744 // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
745 if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
746 why = kWaiting;
747 }
748
Elliott Hughes5f791332011-09-15 17:45:30 -0700749 // Enforce the timeout range.
750 if (ms < 0 || ns < 0 || ns > 999999) {
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700751 monitor_lock_.Unlock(self);
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000752 self->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
Ian Rogersef7d42f2014-01-06 12:55:46 -0800753 "timeout arguments out of range: ms=%" PRId64 " ns=%d", ms, ns);
Elliott Hughes5f791332011-09-15 17:45:30 -0700754 return;
755 }
756
Elliott Hughes5f791332011-09-15 17:45:30 -0700757 /*
758 * Add ourselves to the set of threads waiting on this monitor, and
759 * release our hold. We need to let it go even if we're a few levels
760 * deep in a recursive lock, and we need to restore that later.
761 *
762 * We append to the wait set ahead of clearing the count and owner
763 * fields so the subroutine can check that the calling thread owns
764 * the monitor. Aside from that, the order of member updates is
765 * not order sensitive as we hold the pthread mutex.
766 */
767 AppendToWaitSet(self);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700768 ++num_waiters_;
Ian Rogers0399dde2012-06-06 17:09:28 -0700769 int prev_lock_count = lock_count_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700770 lock_count_ = 0;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700771 owner_ = nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700772 ArtMethod* saved_method = locking_method_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700773 locking_method_ = nullptr;
Ian Rogers0399dde2012-06-06 17:09:28 -0700774 uintptr_t saved_dex_pc = locking_dex_pc_;
775 locking_dex_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700776
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700777 AtraceMonitorUnlock(); // For the implict Unlock() just above. This will only end the deepest
778 // nesting, but that is enough for the visualization, and corresponds to
779 // the single Lock() we do afterwards.
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700780 AtraceMonitorLock(self, GetObject(), /* is_wait= */ true);
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700781
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800782 bool was_interrupted = false;
Alex Light77fee872017-09-05 14:51:49 -0700783 bool timed_out = false;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700784 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700785 // Update thread state. If the GC wakes up, it'll ignore us, knowing
786 // that we won't touch any references in this state, and we'll check
787 // our suspend mode before we transition out.
788 ScopedThreadSuspension sts(self, why);
789
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700790 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700791 MutexLock mu(self, *self->GetWaitMutex());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700792
793 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700794 // non-null a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700795 // up.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700796 DCHECK(self->GetWaitMonitor() == nullptr);
797 self->SetWaitMonitor(this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700798
799 // Release the monitor lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700800 monitor_contenders_.Signal(self);
801 monitor_lock_.Unlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700802
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800803 // Handle the case where the thread was interrupted before we called wait().
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000804 if (self->IsInterrupted()) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800805 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700806 } else {
807 // Wait for a notification or a timeout to occur.
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800808 if (why == kWaiting) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700809 self->GetWaitConditionVariable()->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700810 } else {
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800811 DCHECK(why == kTimedWaiting || why == kSleeping) << why;
Alex Light77fee872017-09-05 14:51:49 -0700812 timed_out = self->GetWaitConditionVariable()->TimedWait(self, ms, ns);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700813 }
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000814 was_interrupted = self->IsInterrupted();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700815 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700816 }
817
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800818 {
819 // We reset the thread's wait_monitor_ field after transitioning back to runnable so
820 // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
821 // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
822 // are waiting on "null".)
Ian Rogersdd7624d2014-03-14 17:43:00 -0700823 MutexLock mu(self, *self->GetWaitMutex());
824 DCHECK(self->GetWaitMonitor() != nullptr);
825 self->SetWaitMonitor(nullptr);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800826 }
827
Mathieu Chartierdaed5d82016-03-10 10:49:35 -0800828 // Allocate the interrupted exception not holding the monitor lock since it may cause a GC.
829 // If the GC requires acquiring the monitor for enqueuing cleared references, this would
830 // cause a deadlock if the monitor is held.
831 if (was_interrupted && interruptShouldThrow) {
832 /*
833 * We were interrupted while waiting, or somebody interrupted an
834 * un-interruptible thread earlier and we're bailing out immediately.
835 *
836 * The doc sayeth: "The interrupted status of the current thread is
837 * cleared when this exception is thrown."
838 */
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000839 self->SetInterrupted(false);
Mathieu Chartierdaed5d82016-03-10 10:49:35 -0800840 self->ThrowNewException("Ljava/lang/InterruptedException;", nullptr);
841 }
842
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700843 AtraceMonitorUnlock(); // End Wait().
844
Alex Light77fee872017-09-05 14:51:49 -0700845 // We just slept, tell the runtime callbacks about this.
846 Runtime::Current()->GetRuntimeCallbacks()->MonitorWaitFinished(this, timed_out);
847
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700848 // Re-acquire the monitor and lock.
Alex Light77fee872017-09-05 14:51:49 -0700849 Lock<LockReason::kForWait>(self);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700850 monitor_lock_.Lock(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700851 self->GetWaitMutex()->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700852
Elliott Hughes5f791332011-09-15 17:45:30 -0700853 /*
854 * We remove our thread from wait set after restoring the count
855 * and owner fields so the subroutine can check that the calling
856 * thread owns the monitor. Aside from that, the order of member
857 * updates is not order sensitive as we hold the pthread mutex.
858 */
859 owner_ = self;
Ian Rogers0399dde2012-06-06 17:09:28 -0700860 lock_count_ = prev_lock_count;
861 locking_method_ = saved_method;
862 locking_dex_pc_ = saved_dex_pc;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700863 --num_waiters_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700864 RemoveFromWaitSet(self);
865
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700866 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700867}
868
869void Monitor::Notify(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700870 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700871 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700872 // Make sure that we hold the lock.
873 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800874 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700875 return;
876 }
877 // Signal the first waiting thread in the wait set.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700878 while (wait_set_ != nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700879 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700880 wait_set_ = thread->GetWaitNext();
881 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700882
883 // Check to see if the thread is still waiting.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800884 MutexLock wait_mu(self, *thread->GetWaitMutex());
Ian Rogersdd7624d2014-03-14 17:43:00 -0700885 if (thread->GetWaitMonitor() != nullptr) {
886 thread->GetWaitConditionVariable()->Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700887 return;
888 }
889 }
890}
891
892void Monitor::NotifyAll(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700893 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700894 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700895 // Make sure that we hold the lock.
896 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800897 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700898 return;
899 }
900 // Signal all threads in the wait set.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700901 while (wait_set_ != nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700902 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700903 wait_set_ = thread->GetWaitNext();
904 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700905 thread->Notify();
906 }
907}
908
Mathieu Chartier590fee92013-09-13 13:46:47 -0700909bool Monitor::Deflate(Thread* self, mirror::Object* obj) {
910 DCHECK(obj != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700911 // Don't need volatile since we only deflate with mutators suspended.
912 LockWord lw(obj->GetLockWord(false));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700913 // If the lock isn't an inflated monitor, then we don't need to deflate anything.
914 if (lw.GetState() == LockWord::kFatLocked) {
915 Monitor* monitor = lw.FatLockMonitor();
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700916 DCHECK(monitor != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700917 MutexLock mu(self, monitor->monitor_lock_);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700918 // Can't deflate if we have anybody waiting on the CV.
919 if (monitor->num_waiters_ > 0) {
920 return false;
921 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700922 Thread* owner = monitor->owner_;
923 if (owner != nullptr) {
924 // Can't deflate if we are locked and have a hash code.
925 if (monitor->HasHashCode()) {
926 return false;
927 }
928 // Can't deflate if our lock count is too high.
Mathieu Chartier1cf194f2016-11-01 20:13:24 -0700929 if (static_cast<uint32_t>(monitor->lock_count_) > LockWord::kThinLockMaxCount) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700930 return false;
931 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700932 // Deflate to a thin lock.
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700933 LockWord new_lw = LockWord::FromThinLockId(owner->GetThreadId(),
934 monitor->lock_count_,
935 lw.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800936 // Assume no concurrent read barrier state changes as mutators are suspended.
937 obj->SetLockWord(new_lw, false);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700938 VLOG(monitor) << "Deflated " << obj << " to thin lock " << owner->GetTid() << " / "
939 << monitor->lock_count_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700940 } else if (monitor->HasHashCode()) {
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700941 LockWord new_lw = LockWord::FromHashCode(monitor->GetHashCode(), lw.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800942 // Assume no concurrent read barrier state changes as mutators are suspended.
943 obj->SetLockWord(new_lw, false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700944 VLOG(monitor) << "Deflated " << obj << " to hash monitor " << monitor->GetHashCode();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700945 } else {
946 // No lock and no hash, just put an empty lock word inside the object.
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700947 LockWord new_lw = LockWord::FromDefault(lw.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800948 // Assume no concurrent read barrier state changes as mutators are suspended.
949 obj->SetLockWord(new_lw, false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700950 VLOG(monitor) << "Deflated" << obj << " to empty lock word";
Mathieu Chartier590fee92013-09-13 13:46:47 -0700951 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700952 // 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 -0700953 // next GC.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700954 monitor->obj_ = GcRoot<mirror::Object>(nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700955 }
956 return true;
957}
958
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700959void Monitor::Inflate(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code) {
Andreas Gampe74240812014-04-17 10:35:09 -0700960 DCHECK(self != nullptr);
961 DCHECK(obj != nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700962 // Allocate and acquire a new monitor.
Andreas Gampe74240812014-04-17 10:35:09 -0700963 Monitor* m = MonitorPool::CreateMonitor(self, owner, obj, hash_code);
964 DCHECK(m != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700965 if (m->Install(self)) {
Haifeng Li86ab7912014-05-16 10:47:59 +0800966 if (owner != nullptr) {
967 VLOG(monitor) << "monitor: thread" << owner->GetThreadId()
Andreas Gampe74240812014-04-17 10:35:09 -0700968 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800969 } else {
970 VLOG(monitor) << "monitor: Inflate with hashcode " << hash_code
Andreas Gampe74240812014-04-17 10:35:09 -0700971 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800972 }
Andreas Gampe74240812014-04-17 10:35:09 -0700973 Runtime::Current()->GetMonitorList()->Add(m);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700974 CHECK_EQ(obj->GetLockWord(true).GetState(), LockWord::kFatLocked);
Andreas Gampe74240812014-04-17 10:35:09 -0700975 } else {
976 MonitorPool::ReleaseMonitor(self, m);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700977 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700978}
979
Mathieu Chartier0cd81352014-05-22 16:48:55 -0700980void Monitor::InflateThinLocked(Thread* self, Handle<mirror::Object> obj, LockWord lock_word,
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700981 uint32_t hash_code) {
982 DCHECK_EQ(lock_word.GetState(), LockWord::kThinLocked);
983 uint32_t owner_thread_id = lock_word.ThinLockOwner();
984 if (owner_thread_id == self->GetThreadId()) {
985 // We own the monitor, we can easily inflate it.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700986 Inflate(self, self, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700987 } else {
988 ThreadList* thread_list = Runtime::Current()->GetThreadList();
989 // Suspend the owner, inflate. First change to blocked and give up mutator_lock_.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700990 self->SetMonitorEnterObject(obj.Get());
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700991 bool timed_out;
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700992 Thread* owner;
993 {
Alex Light77fee872017-09-05 14:51:49 -0700994 ScopedThreadSuspension sts(self, kWaitingForLockInflation);
Alex Light46f93402017-06-29 11:59:50 -0700995 owner = thread_list->SuspendThreadByThreadId(owner_thread_id,
996 SuspendReason::kInternal,
997 &timed_out);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700998 }
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700999 if (owner != nullptr) {
1000 // We succeeded in suspending the thread, check the lock's status didn't change.
1001 lock_word = obj->GetLockWord(true);
1002 if (lock_word.GetState() == LockWord::kThinLocked &&
1003 lock_word.ThinLockOwner() == owner_thread_id) {
1004 // Go ahead and inflate the lock.
1005 Inflate(self, owner, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001006 }
Alex Light88fd7202017-06-30 08:31:59 -07001007 bool resumed = thread_list->Resume(owner, SuspendReason::kInternal);
1008 DCHECK(resumed);
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001009 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07001010 self->SetMonitorEnterObject(nullptr);
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001011 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001012}
1013
Ian Rogers719d1a32014-03-06 12:13:39 -08001014// Fool annotalysis into thinking that the lock on obj is acquired.
1015static mirror::Object* FakeLock(mirror::Object* obj)
1016 EXCLUSIVE_LOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
1017 return obj;
1018}
1019
1020// Fool annotalysis into thinking that the lock on obj is release.
1021static mirror::Object* FakeUnlock(mirror::Object* obj)
1022 UNLOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
1023 return obj;
1024}
1025
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07001026mirror::Object* Monitor::MonitorEnter(Thread* self, mirror::Object* obj, bool trylock) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001027 DCHECK(self != nullptr);
1028 DCHECK(obj != nullptr);
Mathieu Chartier2d096c92015-10-12 16:18:20 -07001029 self->AssertThreadSuspensionIsAllowable();
Ian Rogers719d1a32014-03-06 12:13:39 -08001030 obj = FakeLock(obj);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001031 uint32_t thread_id = self->GetThreadId();
1032 size_t contention_count = 0;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001033 StackHandleScope<1> hs(self);
1034 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001035 while (true) {
Hans Boehmb3da36c2016-12-15 13:12:59 -08001036 // We initially read the lockword with ordinary Java/relaxed semantics. When stronger
1037 // semantics are needed, we address it below. Since GetLockWord bottoms out to a relaxed load,
1038 // we can fix it later, in an infrequently executed case, with a fence.
1039 LockWord lock_word = h_obj->GetLockWord(false);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001040 switch (lock_word.GetState()) {
1041 case LockWord::kUnlocked: {
Hans Boehmb3da36c2016-12-15 13:12:59 -08001042 // No ordering required for preceding lockword read, since we retest.
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001043 LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0, lock_word.GCState()));
Mathieu Chartier42c2e502018-06-19 12:30:56 -07001044 if (h_obj->CasLockWord(lock_word, thin_locked, CASMode::kWeak, std::memory_order_acquire)) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001045 AtraceMonitorLock(self, h_obj.Get(), /* is_wait= */ false);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001046 return h_obj.Get(); // Success!
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001047 }
1048 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -07001049 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001050 case LockWord::kThinLocked: {
1051 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1052 if (owner_thread_id == thread_id) {
Hans Boehmb3da36c2016-12-15 13:12:59 -08001053 // No ordering required for initial lockword read.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001054 // We own the lock, increase the recursion count.
1055 uint32_t new_count = lock_word.ThinLockCount() + 1;
1056 if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001057 LockWord thin_locked(LockWord::FromThinLockId(thread_id,
1058 new_count,
1059 lock_word.GCState()));
Hans Boehmb3da36c2016-12-15 13:12:59 -08001060 // Only this thread pays attention to the count. Thus there is no need for stronger
1061 // than relaxed memory ordering.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001062 if (!kUseReadBarrier) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001063 h_obj->SetLockWord(thin_locked, /* as_volatile= */ false);
1064 AtraceMonitorLock(self, h_obj.Get(), /* is_wait= */ false);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001065 return h_obj.Get(); // Success!
1066 } else {
1067 // Use CAS to preserve the read barrier state.
Mathieu Chartier42c2e502018-06-19 12:30:56 -07001068 if (h_obj->CasLockWord(lock_word,
1069 thin_locked,
1070 CASMode::kWeak,
1071 std::memory_order_relaxed)) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001072 AtraceMonitorLock(self, h_obj.Get(), /* is_wait= */ false);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001073 return h_obj.Get(); // Success!
1074 }
1075 }
1076 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -07001077 } else {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001078 // We'd overflow the recursion count, so inflate the monitor.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001079 InflateThinLocked(self, h_obj, lock_word, 0);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001080 }
1081 } else {
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07001082 if (trylock) {
1083 return nullptr;
1084 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001085 // Contention.
1086 contention_count++;
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001087 Runtime* runtime = Runtime::Current();
Hans Boehmb3da36c2016-12-15 13:12:59 -08001088 if (contention_count <= runtime->GetMaxSpinsBeforeThinLockInflation()) {
Alex Light77fee872017-09-05 14:51:49 -07001089 // TODO: Consider switching the thread state to kWaitingForLockInflation when we are
1090 // yielding. Use sched_yield instead of NanoSleep since NanoSleep can wait much longer
1091 // than the parameter you pass in. This can cause thread suspension to take excessively
1092 // long and make long pauses. See b/16307460.
Hans Boehmb3da36c2016-12-15 13:12:59 -08001093 // TODO: We should literally spin first, without sched_yield. Sched_yield either does
1094 // nothing (at significant expense), or guarantees that we wait at least microseconds.
1095 // If the owner is running, I would expect the median lock hold time to be hundreds
1096 // of nanoseconds or less.
Mathieu Chartier251755c2014-07-15 18:10:25 -07001097 sched_yield();
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001098 } else {
1099 contention_count = 0;
Hans Boehmb3da36c2016-12-15 13:12:59 -08001100 // No ordering required for initial lockword read. Install rereads it anyway.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001101 InflateThinLocked(self, h_obj, lock_word, 0);
Elliott Hughes5f791332011-09-15 17:45:30 -07001102 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001103 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001104 continue; // Start from the beginning.
Elliott Hughes5f791332011-09-15 17:45:30 -07001105 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001106 case LockWord::kFatLocked: {
Hans Boehmb3da36c2016-12-15 13:12:59 -08001107 // We should have done an acquire read of the lockword initially, to ensure
1108 // visibility of the monitor data structure. Use an explicit fence instead.
Orion Hodson27b96762018-03-13 16:06:57 +00001109 std::atomic_thread_fence(std::memory_order_acquire);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001110 Monitor* mon = lock_word.FatLockMonitor();
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07001111 if (trylock) {
1112 return mon->TryLock(self) ? h_obj.Get() : nullptr;
1113 } else {
1114 mon->Lock(self);
1115 return h_obj.Get(); // Success!
1116 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001117 }
Ian Rogers719d1a32014-03-06 12:13:39 -08001118 case LockWord::kHashCode:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001119 // Inflate with the existing hashcode.
Hans Boehmb3da36c2016-12-15 13:12:59 -08001120 // Again no ordering required for initial lockword read, since we don't rely
1121 // on the visibility of any prior computation.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001122 Inflate(self, nullptr, h_obj.Get(), lock_word.GetHashCode());
Ian Rogers719d1a32014-03-06 12:13:39 -08001123 continue; // Start from the beginning.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001124 default: {
1125 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Andreas Gampec7ed09b2016-04-25 20:08:55 -07001126 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001127 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001128 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001129 }
1130}
1131
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001132bool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001133 DCHECK(self != nullptr);
1134 DCHECK(obj != nullptr);
Mathieu Chartier2d096c92015-10-12 16:18:20 -07001135 self->AssertThreadSuspensionIsAllowable();
Ian Rogers719d1a32014-03-06 12:13:39 -08001136 obj = FakeUnlock(obj);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001137 StackHandleScope<1> hs(self);
1138 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001139 while (true) {
1140 LockWord lock_word = obj->GetLockWord(true);
1141 switch (lock_word.GetState()) {
1142 case LockWord::kHashCode:
1143 // Fall-through.
1144 case LockWord::kUnlocked:
Mathieu Chartier61b3cd42016-04-18 11:43:29 -07001145 FailedUnlock(h_obj.Get(), self->GetThreadId(), 0u, nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001146 return false; // Failure.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001147 case LockWord::kThinLocked: {
1148 uint32_t thread_id = self->GetThreadId();
1149 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1150 if (owner_thread_id != thread_id) {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -07001151 FailedUnlock(h_obj.Get(), thread_id, owner_thread_id, nullptr);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001152 return false; // Failure.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001153 } else {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001154 // We own the lock, decrease the recursion count.
1155 LockWord new_lw = LockWord::Default();
1156 if (lock_word.ThinLockCount() != 0) {
1157 uint32_t new_count = lock_word.ThinLockCount() - 1;
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001158 new_lw = LockWord::FromThinLockId(thread_id, new_count, lock_word.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001159 } else {
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001160 new_lw = LockWord::FromDefault(lock_word.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001161 }
1162 if (!kUseReadBarrier) {
1163 DCHECK_EQ(new_lw.ReadBarrierState(), 0U);
Hans Boehmb3da36c2016-12-15 13:12:59 -08001164 // TODO: This really only needs memory_order_release, but we currently have
1165 // no way to specify that. In fact there seem to be no legitimate uses of SetLockWord
1166 // with a final argument of true. This slows down x86 and ARMv7, but probably not v8.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001167 h_obj->SetLockWord(new_lw, true);
Andreas Gampe6e759ad2016-05-17 10:13:10 -07001168 AtraceMonitorUnlock();
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001169 // Success!
1170 return true;
1171 } else {
1172 // Use CAS to preserve the read barrier state.
Mathieu Chartier42c2e502018-06-19 12:30:56 -07001173 if (h_obj->CasLockWord(lock_word, new_lw, CASMode::kWeak, std::memory_order_release)) {
Andreas Gampe6e759ad2016-05-17 10:13:10 -07001174 AtraceMonitorUnlock();
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001175 // Success!
1176 return true;
1177 }
1178 }
1179 continue; // Go again.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001180 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001181 }
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001182 case LockWord::kFatLocked: {
1183 Monitor* mon = lock_word.FatLockMonitor();
1184 return mon->Unlock(self);
1185 }
1186 default: {
1187 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1188 return false;
1189 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001190 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001191 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001192}
1193
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001194void Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
Elliott Hughes4cd121e2013-01-07 17:35:41 -08001195 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001196 DCHECK(self != nullptr);
1197 DCHECK(obj != nullptr);
Alex Light77fee872017-09-05 14:51:49 -07001198 StackHandleScope<1> hs(self);
1199 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
1200
1201 Runtime::Current()->GetRuntimeCallbacks()->ObjectWaitStart(h_obj, ms);
Alex Light848574c2017-09-25 16:59:39 -07001202 if (UNLIKELY(self->ObserveAsyncException() || self->IsExceptionPending())) {
Alex Light77fee872017-09-05 14:51:49 -07001203 // See b/65558434 for information on handling of exceptions here.
1204 return;
1205 }
1206
1207 LockWord lock_word = h_obj->GetLockWord(true);
Ian Rogers43c69cc2014-08-15 11:09:28 -07001208 while (lock_word.GetState() != LockWord::kFatLocked) {
1209 switch (lock_word.GetState()) {
1210 case LockWord::kHashCode:
1211 // Fall-through.
1212 case LockWord::kUnlocked:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001213 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
1214 return; // Failure.
Ian Rogers43c69cc2014-08-15 11:09:28 -07001215 case LockWord::kThinLocked: {
1216 uint32_t thread_id = self->GetThreadId();
1217 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1218 if (owner_thread_id != thread_id) {
1219 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
1220 return; // Failure.
1221 } else {
1222 // We own the lock, inflate to enqueue ourself on the Monitor. May fail spuriously so
1223 // re-load.
Alex Light77fee872017-09-05 14:51:49 -07001224 Inflate(self, self, h_obj.Get(), 0);
1225 lock_word = h_obj->GetLockWord(true);
Ian Rogers43c69cc2014-08-15 11:09:28 -07001226 }
1227 break;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001228 }
Ian Rogers43c69cc2014-08-15 11:09:28 -07001229 case LockWord::kFatLocked: // Unreachable given the loop condition above. Fall-through.
1230 default: {
1231 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1232 return;
1233 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001234 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001235 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001236 Monitor* mon = lock_word.FatLockMonitor();
1237 mon->Wait(self, ms, ns, interruptShouldThrow, why);
Elliott Hughes5f791332011-09-15 17:45:30 -07001238}
1239
Ian Rogers13c479e2013-10-11 07:59:01 -07001240void Monitor::DoNotify(Thread* self, mirror::Object* obj, bool notify_all) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001241 DCHECK(self != nullptr);
1242 DCHECK(obj != nullptr);
1243 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001244 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001245 case LockWord::kHashCode:
1246 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001247 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -08001248 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001249 return; // Failure.
1250 case LockWord::kThinLocked: {
1251 uint32_t thread_id = self->GetThreadId();
1252 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1253 if (owner_thread_id != thread_id) {
1254 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
1255 return; // Failure.
1256 } else {
1257 // We own the lock but there's no Monitor and therefore no waiters.
1258 return; // Success.
1259 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001260 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001261 case LockWord::kFatLocked: {
1262 Monitor* mon = lock_word.FatLockMonitor();
1263 if (notify_all) {
1264 mon->NotifyAll(self);
1265 } else {
1266 mon->Notify(self);
1267 }
1268 return; // Success.
1269 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001270 default: {
1271 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1272 return;
1273 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001274 }
1275}
1276
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001277uint32_t Monitor::GetLockOwnerThreadId(mirror::Object* obj) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001278 DCHECK(obj != nullptr);
1279 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001280 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001281 case LockWord::kHashCode:
1282 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001283 case LockWord::kUnlocked:
1284 return ThreadList::kInvalidThreadId;
1285 case LockWord::kThinLocked:
1286 return lock_word.ThinLockOwner();
1287 case LockWord::kFatLocked: {
1288 Monitor* mon = lock_word.FatLockMonitor();
1289 return mon->GetOwnerThreadId();
Elliott Hughes5f791332011-09-15 17:45:30 -07001290 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001291 default: {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001292 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001293 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001294 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001295 }
1296}
1297
Andreas Gampef3ebcce2017-12-11 20:40:23 -08001298ThreadState Monitor::FetchState(const Thread* thread,
1299 /* out */ mirror::Object** monitor_object,
1300 /* out */ uint32_t* lock_owner_tid) {
1301 DCHECK(monitor_object != nullptr);
1302 DCHECK(lock_owner_tid != nullptr);
1303
1304 *monitor_object = nullptr;
1305 *lock_owner_tid = ThreadList::kInvalidThreadId;
1306
1307 ThreadState state = thread->GetState();
1308
1309 switch (state) {
1310 case kWaiting:
1311 case kTimedWaiting:
1312 case kSleeping:
1313 {
1314 Thread* self = Thread::Current();
1315 MutexLock mu(self, *thread->GetWaitMutex());
1316 Monitor* monitor = thread->GetWaitMonitor();
1317 if (monitor != nullptr) {
1318 *monitor_object = monitor->GetObject();
Ian Rogersd803bc72014-04-01 15:33:03 -07001319 }
1320 }
Andreas Gampef3ebcce2017-12-11 20:40:23 -08001321 break;
1322
1323 case kBlocked:
1324 case kWaitingForLockInflation:
1325 {
1326 mirror::Object* lock_object = thread->GetMonitorEnterObject();
1327 if (lock_object != nullptr) {
1328 if (kUseReadBarrier && Thread::Current()->GetIsGcMarking()) {
1329 // We may call Thread::Dump() in the middle of the CC thread flip and this thread's stack
1330 // may have not been flipped yet and "pretty_object" may be a from-space (stale) ref, in
1331 // which case the GetLockOwnerThreadId() call below will crash. So explicitly mark/forward
1332 // it here.
1333 lock_object = ReadBarrier::Mark(lock_object);
1334 }
1335 *monitor_object = lock_object;
1336 *lock_owner_tid = lock_object->GetLockOwnerThreadId();
1337 }
Ian Rogersd803bc72014-04-01 15:33:03 -07001338 }
Andreas Gampef3ebcce2017-12-11 20:40:23 -08001339 break;
1340
1341 default:
1342 break;
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001343 }
Andreas Gampef3ebcce2017-12-11 20:40:23 -08001344
1345 return state;
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001346}
1347
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001348mirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -08001349 // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
1350 // definition of contended that includes a monitor a thread is trying to enter...
Ian Rogersdd7624d2014-03-14 17:43:00 -07001351 mirror::Object* result = thread->GetMonitorEnterObject();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001352 if (result == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001353 // ...but also a monitor that the thread is waiting on.
Ian Rogersdd7624d2014-03-14 17:43:00 -07001354 MutexLock mu(Thread::Current(), *thread->GetWaitMutex());
1355 Monitor* monitor = thread->GetWaitMonitor();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001356 if (monitor != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001357 result = monitor->GetObject();
Elliott Hughesf9501702013-01-11 11:22:27 -08001358 }
1359 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001360 return result;
Elliott Hughesf9501702013-01-11 11:22:27 -08001361}
1362
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001363void Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
Andreas Gampe760172c2014-08-16 13:41:10 -07001364 void* callback_context, bool abort_on_failure) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001365 ArtMethod* m = stack_visitor->GetMethod();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001366 CHECK(m != nullptr);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001367
1368 // Native methods are an easy special case.
1369 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
1370 if (m->IsNative()) {
1371 if (m->IsSynchronized()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001372 mirror::Object* jni_this =
1373 stack_visitor->GetCurrentHandleScope(sizeof(void*))->GetReference(0);
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001374 callback(jni_this, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001375 }
1376 return;
1377 }
1378
jeffhao61f916c2012-10-25 17:48:51 -07001379 // Proxy methods should not be synchronized.
1380 if (m->IsProxyMethod()) {
1381 CHECK(!m->IsSynchronized());
1382 return;
1383 }
1384
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001385 // Is there any reason to believe there's any synchronization in this method?
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001386 CHECK(m->GetCodeItem() != nullptr) << m->PrettyMethod();
David Sehr0225f8e2018-01-31 08:52:24 +00001387 CodeItemDataAccessor accessor(m->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001388 if (accessor.TriesSize() == 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001389 return; // No "tries" implies no synchronization, so no held locks to report.
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001390 }
1391
Andreas Gampe760172c2014-08-16 13:41:10 -07001392 // Get the dex pc. If abort_on_failure is false, GetDexPc will not abort in the case it cannot
1393 // find the dex pc, and instead return kDexNoIndex. Then bail out, as it indicates we have an
1394 // inconsistent stack anyways.
1395 uint32_t dex_pc = stack_visitor->GetDexPc(abort_on_failure);
Andreas Gampee2abbc62017-09-15 11:59:26 -07001396 if (!abort_on_failure && dex_pc == dex::kDexNoIndex) {
David Sehr709b0702016-10-13 09:12:37 -07001397 LOG(ERROR) << "Could not find dex_pc for " << m->PrettyMethod();
Andreas Gampe760172c2014-08-16 13:41:10 -07001398 return;
1399 }
1400
Elliott Hughes80537bb2013-01-04 16:37:26 -08001401 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
1402 // the locks held in this stack frame.
Andreas Gampeaaf0d382017-11-27 14:10:21 -08001403 std::vector<verifier::MethodVerifier::DexLockInfo> monitor_enter_dex_pcs;
Andreas Gampe6cc23ac2018-08-24 15:22:43 -07001404 verifier::MethodVerifier::FindLocksAtDexPc(m,
1405 dex_pc,
1406 &monitor_enter_dex_pcs,
1407 Runtime::Current()->GetTargetSdkVersion());
Andreas Gampeaaf0d382017-11-27 14:10:21 -08001408 for (verifier::MethodVerifier::DexLockInfo& dex_lock_info : monitor_enter_dex_pcs) {
1409 // As a debug check, check that dex PC corresponds to a monitor-enter.
1410 if (kIsDebugBuild) {
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001411 const Instruction& monitor_enter_instruction = accessor.InstructionAt(dex_lock_info.dex_pc);
1412 CHECK_EQ(monitor_enter_instruction.Opcode(), Instruction::MONITOR_ENTER)
Andreas Gampeaaf0d382017-11-27 14:10:21 -08001413 << "expected monitor-enter @" << dex_lock_info.dex_pc << "; was "
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001414 << reinterpret_cast<const void*>(&monitor_enter_instruction);
Andreas Gampeaaf0d382017-11-27 14:10:21 -08001415 }
Elliott Hughes80537bb2013-01-04 16:37:26 -08001416
Andreas Gampeaaf0d382017-11-27 14:10:21 -08001417 // Iterate through the set of dex registers, as the compiler may not have held all of them
1418 // live.
1419 bool success = false;
1420 for (uint32_t dex_reg : dex_lock_info.dex_registers) {
1421 uint32_t value;
1422 success = stack_visitor->GetVReg(m, dex_reg, kReferenceVReg, &value);
1423 if (success) {
1424 mirror::Object* o = reinterpret_cast<mirror::Object*>(value);
1425 callback(o, callback_context);
1426 break;
1427 }
1428 }
1429 DCHECK(success) << "Failed to find/read reference for monitor-enter at dex pc "
1430 << dex_lock_info.dex_pc
1431 << " in method "
1432 << m->PrettyMethod();
1433 if (!success) {
1434 LOG(WARNING) << "Had a lock reported for dex pc " << dex_lock_info.dex_pc
1435 << " but was not able to fetch a corresponding object!";
1436 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001437 }
1438}
1439
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001440bool Monitor::IsValidLockWord(LockWord lock_word) {
1441 switch (lock_word.GetState()) {
1442 case LockWord::kUnlocked:
1443 // Nothing to check.
1444 return true;
1445 case LockWord::kThinLocked:
1446 // Basic sanity check of owner.
1447 return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
1448 case LockWord::kFatLocked: {
1449 // Check the monitor appears in the monitor list.
1450 Monitor* mon = lock_word.FatLockMonitor();
1451 MonitorList* list = Runtime::Current()->GetMonitorList();
1452 MutexLock mu(Thread::Current(), list->monitor_list_lock_);
1453 for (Monitor* list_mon : list->list_) {
1454 if (mon == list_mon) {
1455 return true; // Found our monitor.
1456 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001457 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001458 return false; // Fail - unowned monitor in an object.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001459 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001460 case LockWord::kHashCode:
1461 return true;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001462 default:
1463 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001464 UNREACHABLE();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001465 }
1466}
1467
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001468bool Monitor::IsLocked() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001469 MutexLock mu(Thread::Current(), monitor_lock_);
1470 return owner_ != nullptr;
1471}
1472
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -07001473void Monitor::TranslateLocation(ArtMethod* method,
1474 uint32_t dex_pc,
1475 const char** source_file,
1476 int32_t* line_number) {
jeffhao33dc7712011-11-09 17:54:24 -08001477 // If method is null, location is unknown
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001478 if (method == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001479 *source_file = "";
1480 *line_number = 0;
jeffhao33dc7712011-11-09 17:54:24 -08001481 return;
1482 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001483 *source_file = method->GetDeclaringClassSourceFile();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001484 if (*source_file == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001485 *source_file = "";
Elliott Hughes12c51e32012-01-17 20:25:05 -08001486 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001487 *line_number = method->GetLineNumFromDexPC(dex_pc);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001488}
1489
1490uint32_t Monitor::GetOwnerThreadId() {
1491 MutexLock mu(Thread::Current(), monitor_lock_);
1492 Thread* owner = owner_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001493 if (owner != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001494 return owner->GetThreadId();
1495 } else {
1496 return ThreadList::kInvalidThreadId;
1497 }
jeffhao33dc7712011-11-09 17:54:24 -08001498}
1499
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001500MonitorList::MonitorList()
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001501 : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock", kMonitorListLock),
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001502 monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001503}
1504
1505MonitorList::~MonitorList() {
Andreas Gampe74240812014-04-17 10:35:09 -07001506 Thread* self = Thread::Current();
1507 MutexLock mu(self, monitor_list_lock_);
1508 // Release all monitors to the pool.
1509 // TODO: Is it an invariant that *all* open monitors are in the list? Then we could
1510 // clear faster in the pool.
1511 MonitorPool::ReleaseMonitors(self, &list_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001512}
1513
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001514void MonitorList::DisallowNewMonitors() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001515 CHECK(!kUseReadBarrier);
Ian Rogers50b35e22012-10-04 10:09:15 -07001516 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001517 allow_new_monitors_ = false;
1518}
1519
1520void MonitorList::AllowNewMonitors() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001521 CHECK(!kUseReadBarrier);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001522 Thread* self = Thread::Current();
1523 MutexLock mu(self, monitor_list_lock_);
1524 allow_new_monitors_ = true;
1525 monitor_add_condition_.Broadcast(self);
1526}
1527
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001528void MonitorList::BroadcastForNewMonitors() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001529 Thread* self = Thread::Current();
1530 MutexLock mu(self, monitor_list_lock_);
1531 monitor_add_condition_.Broadcast(self);
1532}
1533
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001534void MonitorList::Add(Monitor* m) {
1535 Thread* self = Thread::Current();
1536 MutexLock mu(self, monitor_list_lock_);
Hiroshi Yamauchif1c6f872017-01-06 12:23:47 -08001537 // CMS needs this to block for concurrent reference processing because an object allocated during
1538 // the GC won't be marked and concurrent reference processing would incorrectly clear the JNI weak
1539 // ref. But CC (kUseReadBarrier == true) doesn't because of the to-space invariant.
1540 while (!kUseReadBarrier && UNLIKELY(!allow_new_monitors_)) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -07001541 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
1542 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -08001543 self->CheckEmptyCheckpointFromWeakRefAccess(&monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001544 monitor_add_condition_.WaitHoldingLocks(self);
1545 }
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001546 list_.push_front(m);
1547}
1548
Mathieu Chartier97509952015-07-13 14:35:43 -07001549void MonitorList::SweepMonitorList(IsMarkedVisitor* visitor) {
Andreas Gampe74240812014-04-17 10:35:09 -07001550 Thread* self = Thread::Current();
1551 MutexLock mu(self, monitor_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001552 for (auto it = list_.begin(); it != list_.end(); ) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001553 Monitor* m = *it;
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001554 // Disable the read barrier in GetObject() as this is called by GC.
1555 mirror::Object* obj = m->GetObject<kWithoutReadBarrier>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001556 // The object of a monitor can be null if we have deflated it.
Mathieu Chartier97509952015-07-13 14:35:43 -07001557 mirror::Object* new_obj = obj != nullptr ? visitor->IsMarked(obj) : nullptr;
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001558 if (new_obj == nullptr) {
1559 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001560 << obj;
Andreas Gampe74240812014-04-17 10:35:09 -07001561 MonitorPool::ReleaseMonitor(self, m);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001562 it = list_.erase(it);
1563 } else {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001564 m->SetObject(new_obj);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001565 ++it;
1566 }
1567 }
1568}
1569
Hans Boehm6fe97e02016-05-04 18:35:57 -07001570size_t MonitorList::Size() {
1571 Thread* self = Thread::Current();
1572 MutexLock mu(self, monitor_list_lock_);
1573 return list_.size();
1574}
1575
Mathieu Chartier97509952015-07-13 14:35:43 -07001576class MonitorDeflateVisitor : public IsMarkedVisitor {
1577 public:
1578 MonitorDeflateVisitor() : self_(Thread::Current()), deflate_count_(0) {}
1579
Roland Levillainf73caca2018-08-24 17:19:07 +01001580 mirror::Object* IsMarked(mirror::Object* object) override
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001581 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001582 if (Monitor::Deflate(self_, object)) {
1583 DCHECK_NE(object->GetLockWord(true).GetState(), LockWord::kFatLocked);
1584 ++deflate_count_;
1585 // If we deflated, return null so that the monitor gets removed from the array.
1586 return nullptr;
1587 }
1588 return object; // Monitor was not deflated.
1589 }
1590
1591 Thread* const self_;
1592 size_t deflate_count_;
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001593};
1594
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001595size_t MonitorList::DeflateMonitors() {
Mathieu Chartier97509952015-07-13 14:35:43 -07001596 MonitorDeflateVisitor visitor;
1597 Locks::mutator_lock_->AssertExclusiveHeld(visitor.self_);
1598 SweepMonitorList(&visitor);
1599 return visitor.deflate_count_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001600}
1601
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001602MonitorInfo::MonitorInfo(mirror::Object* obj) : owner_(nullptr), entry_count_(0) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001603 DCHECK(obj != nullptr);
1604 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001605 switch (lock_word.GetState()) {
1606 case LockWord::kUnlocked:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001607 // Fall-through.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001608 case LockWord::kForwardingAddress:
1609 // Fall-through.
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001610 case LockWord::kHashCode:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001611 break;
1612 case LockWord::kThinLocked:
1613 owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
Alex Lightce568642017-09-05 16:54:25 -07001614 DCHECK(owner_ != nullptr) << "Thin-locked without owner!";
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001615 entry_count_ = 1 + lock_word.ThinLockCount();
1616 // Thin locks have no waiters.
1617 break;
1618 case LockWord::kFatLocked: {
1619 Monitor* mon = lock_word.FatLockMonitor();
1620 owner_ = mon->owner_;
Alex Lightce568642017-09-05 16:54:25 -07001621 // Here it is okay for the owner to be null since we don't reset the LockWord back to
1622 // kUnlocked until we get a GC. In cases where this hasn't happened yet we will have a fat
1623 // lock without an owner.
1624 if (owner_ != nullptr) {
1625 entry_count_ = 1 + mon->lock_count_;
1626 } else {
1627 DCHECK_EQ(mon->lock_count_, 0) << "Monitor is fat-locked without any owner!";
1628 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001629 for (Thread* waiter = mon->wait_set_; waiter != nullptr; waiter = waiter->GetWaitNext()) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001630 waiters_.push_back(waiter);
1631 }
1632 break;
Elliott Hughesf327e072013-01-09 16:01:26 -08001633 }
1634 }
1635}
1636
Elliott Hughes5f791332011-09-15 17:45:30 -07001637} // namespace art