blob: 0c9c65a40154ec321614c4ef296c8d7c143250ee [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"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080026#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080027#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010028#include "base/time_utils.h"
jeffhao33dc7712011-11-09 17:54:24 -080029#include "class_linker.h"
David Sehr9e734c72018-01-04 17:56:19 -080030#include "dex/dex_file-inl.h"
31#include "dex/dex_file_types.h"
32#include "dex/dex_instruction-inl.h"
Ian Rogersd9c4fc92013-10-01 19:45:43 -070033#include "lock_word-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070034#include "mirror/class-inl.h"
Ian Rogers05f30572013-02-20 12:13:11 -080035#include "mirror/object-inl.h"
Andreas Gampe5d08fcc2017-06-05 17:56:46 -070036#include "object_callbacks.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070037#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070038#include "stack.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070039#include "thread.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070040#include "thread_list.h"
Elliott Hughes08fc03a2012-06-26 17:34:00 -070041#include "verifier/method_verifier.h"
Elliott Hughes044288f2012-06-25 14:46:39 -070042#include "well_known_classes.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070043
44namespace art {
45
Andreas Gampe46ee31b2016-12-14 10:11:49 -080046using android::base::StringPrintf;
47
Andreas Gampe5d689142017-10-19 13:03:29 -070048static constexpr uint64_t kDebugThresholdFudgeFactor = kIsDebugBuild ? 10 : 1;
49static constexpr uint64_t kLongWaitMs = 100 * kDebugThresholdFudgeFactor;
Mathieu Chartierb9001ab2014-10-03 13:28:46 -070050
Elliott Hughes5f791332011-09-15 17:45:30 -070051/*
Ian Rogersd9c4fc92013-10-01 19:45:43 -070052 * Every Object has a monitor associated with it, but not every Object is actually locked. Even
53 * the ones that are locked do not need a full-fledged monitor until a) there is actual contention
54 * or b) wait() is called on the Object.
Elliott Hughes5f791332011-09-15 17:45:30 -070055 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070056 * For Android, we have implemented a scheme similar to the one described in Bacon et al.'s
57 * "Thin locks: featherweight synchronization for Java" (ACM 1998). Things are even easier for us,
58 * though, because we have a full 32 bits to work with.
Elliott Hughes5f791332011-09-15 17:45:30 -070059 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070060 * The two states of an Object's lock are referred to as "thin" and "fat". A lock may transition
61 * from the "thin" state to the "fat" state and this transition is referred to as inflation. Once
62 * a lock has been inflated it remains in the "fat" state indefinitely.
Elliott Hughes5f791332011-09-15 17:45:30 -070063 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070064 * The lock value itself is stored in mirror::Object::monitor_ and the representation is described
65 * in the LockWord value type.
Elliott Hughes54e7df12011-09-16 11:47:04 -070066 *
Elliott Hughes5f791332011-09-15 17:45:30 -070067 * Monitors provide:
68 * - mutually exclusive access to resources
69 * - a way for multiple threads to wait for notification
70 *
71 * In effect, they fill the role of both mutexes and condition variables.
72 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070073 * Only one thread can own the monitor at any time. There may be several threads waiting on it
74 * (the wait call unlocks it). One or more waiting threads may be getting interrupted or notified
75 * at any given time.
Elliott Hughes5f791332011-09-15 17:45:30 -070076 */
Elliott Hughes54e7df12011-09-16 11:47:04 -070077
Elliott Hughesfc861622011-10-17 17:57:47 -070078uint32_t Monitor::lock_profiling_threshold_ = 0;
Andreas Gamped0210e52017-06-23 13:38:09 -070079uint32_t Monitor::stack_dump_lock_profiling_threshold_ = 0;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070080
Andreas Gamped0210e52017-06-23 13:38:09 -070081void Monitor::Init(uint32_t lock_profiling_threshold,
82 uint32_t stack_dump_lock_profiling_threshold) {
Andreas Gampe5d689142017-10-19 13:03:29 -070083 // It isn't great to always include the debug build fudge factor for command-
84 // line driven arguments, but it's easier to adjust here than in the build.
85 lock_profiling_threshold_ =
86 lock_profiling_threshold * kDebugThresholdFudgeFactor;
87 stack_dump_lock_profiling_threshold_ =
88 stack_dump_lock_profiling_threshold * kDebugThresholdFudgeFactor;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070089}
90
Ian Rogersef7d42f2014-01-06 12:55:46 -080091Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code)
Ian Rogers00f7d0e2012-07-19 15:28:27 -070092 : monitor_lock_("a monitor lock", kMonitorLock),
Ian Rogersd9c4fc92013-10-01 19:45:43 -070093 monitor_contenders_("monitor contenders", monitor_lock_),
Mathieu Chartier46bc7782013-11-12 17:03:02 -080094 num_waiters_(0),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070095 owner_(owner),
Elliott Hughes5f791332011-09-15 17:45:30 -070096 lock_count_(0),
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070097 obj_(GcRoot<mirror::Object>(obj)),
Mathieu Chartier2cebb242015-04-21 16:50:40 -070098 wait_set_(nullptr),
Mathieu Chartierad2541a2013-10-25 10:05:23 -070099 hash_code_(hash_code),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700100 locking_method_(nullptr),
Ian Rogersef7d42f2014-01-06 12:55:46 -0800101 locking_dex_pc_(0),
Andreas Gampe74240812014-04-17 10:35:09 -0700102 monitor_id_(MonitorPool::ComputeMonitorId(this, self)) {
103#ifdef __LP64__
104 DCHECK(false) << "Should not be reached in 64b";
105 next_free_ = nullptr;
106#endif
107 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
108 // with the owner unlocking the thin-lock.
109 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
110 // The identity hash code is set for the life time of the monitor.
111}
112
113Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code,
114 MonitorId id)
115 : monitor_lock_("a monitor lock", kMonitorLock),
116 monitor_contenders_("monitor contenders", monitor_lock_),
117 num_waiters_(0),
118 owner_(owner),
119 lock_count_(0),
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700120 obj_(GcRoot<mirror::Object>(obj)),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700121 wait_set_(nullptr),
Andreas Gampe74240812014-04-17 10:35:09 -0700122 hash_code_(hash_code),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700123 locking_method_(nullptr),
Andreas Gampe74240812014-04-17 10:35:09 -0700124 locking_dex_pc_(0),
125 monitor_id_(id) {
126#ifdef __LP64__
127 next_free_ = nullptr;
128#endif
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700129 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
130 // with the owner unlocking the thin-lock.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800131 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700132 // The identity hash code is set for the life time of the monitor.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700133}
134
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700135int32_t Monitor::GetHashCode() {
136 while (!HasHashCode()) {
Orion Hodson4557b382018-01-03 11:47:54 +0000137 if (hash_code_.CompareAndSetWeakRelaxed(0, mirror::Object::GenerateIdentityHashCode())) {
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700138 break;
139 }
140 }
141 DCHECK(HasHashCode());
Ian Rogers3e5cf302014-05-20 16:40:37 -0700142 return hash_code_.LoadRelaxed();
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700143}
144
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700145bool Monitor::Install(Thread* self) {
146 MutexLock mu(self, monitor_lock_); // Uncontended mutex acquisition as monitor isn't yet public.
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700147 CHECK(owner_ == nullptr || owner_ == self || owner_->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700148 // Propagate the lock state.
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700149 LockWord lw(GetObject()->GetLockWord(false));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700150 switch (lw.GetState()) {
151 case LockWord::kThinLocked: {
152 CHECK_EQ(owner_->GetThreadId(), lw.ThinLockOwner());
153 lock_count_ = lw.ThinLockCount();
154 break;
155 }
156 case LockWord::kHashCode: {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700157 CHECK_EQ(hash_code_.LoadRelaxed(), static_cast<int32_t>(lw.GetHashCode()));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700158 break;
159 }
160 case LockWord::kFatLocked: {
161 // The owner_ is suspended but another thread beat us to install a monitor.
162 return false;
163 }
164 case LockWord::kUnlocked: {
165 LOG(FATAL) << "Inflating unlocked lock word";
166 break;
167 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700168 default: {
169 LOG(FATAL) << "Invalid monitor state " << lw.GetState();
170 return false;
171 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700172 }
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700173 LockWord fat(this, lw.GCState());
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700174 // Publish the updated lock word, which may race with other threads.
Hans Boehmb3da36c2016-12-15 13:12:59 -0800175 bool success = GetObject()->CasLockWordWeakRelease(lw, fat);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700176 // Lock profiling.
Mathieu Chartier9728f912013-10-30 09:45:13 -0700177 if (success && owner_ != nullptr && lock_profiling_threshold_ != 0) {
Andreas Gampe6ec8ebd2014-07-25 13:36:56 -0700178 // Do not abort on dex pc errors. This can easily happen when we want to dump a stack trace on
179 // abort.
180 locking_method_ = owner_->GetCurrentMethod(&locking_dex_pc_, false);
Andreas Gampe5a387272017-11-06 19:47:16 -0800181 if (locking_method_ != nullptr && UNLIKELY(locking_method_->IsProxyMethod())) {
182 // Grab another frame. Proxy methods are not helpful for lock profiling. This should be rare
183 // enough that it's OK to walk the stack twice.
184 struct NextMethodVisitor FINAL : public StackVisitor {
185 explicit NextMethodVisitor(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_)
186 : StackVisitor(thread,
187 nullptr,
188 StackVisitor::StackWalkKind::kIncludeInlinedFrames,
189 false),
190 count_(0),
191 method_(nullptr),
192 dex_pc_(0) {}
193 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
194 ArtMethod* m = GetMethod();
195 if (m->IsRuntimeMethod()) {
196 // Continue if this is a runtime method.
197 return true;
198 }
199 count_++;
200 if (count_ == 2u) {
201 method_ = m;
202 dex_pc_ = GetDexPc(false);
203 return false;
204 }
205 return true;
206 }
207 size_t count_;
208 ArtMethod* method_;
209 uint32_t dex_pc_;
210 };
211 NextMethodVisitor nmv(owner_);
212 nmv.WalkStack();
213 locking_method_ = nmv.method_;
214 locking_dex_pc_ = nmv.dex_pc_;
215 }
216 DCHECK(locking_method_ == nullptr || !locking_method_->IsProxyMethod());
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700217 }
218 return success;
Elliott Hughes5f791332011-09-15 17:45:30 -0700219}
220
221Monitor::~Monitor() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700222 // Deflated monitors have a null object.
Elliott Hughes5f791332011-09-15 17:45:30 -0700223}
224
Elliott Hughes5f791332011-09-15 17:45:30 -0700225void Monitor::AppendToWaitSet(Thread* thread) {
226 DCHECK(owner_ == Thread::Current());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700227 DCHECK(thread != nullptr);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700228 DCHECK(thread->GetWaitNext() == nullptr) << thread->GetWaitNext();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700229 if (wait_set_ == nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700230 wait_set_ = thread;
231 return;
232 }
233
234 // push_back.
235 Thread* t = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700236 while (t->GetWaitNext() != nullptr) {
237 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700238 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700239 t->SetWaitNext(thread);
Elliott Hughes5f791332011-09-15 17:45:30 -0700240}
241
Elliott Hughes5f791332011-09-15 17:45:30 -0700242void Monitor::RemoveFromWaitSet(Thread *thread) {
243 DCHECK(owner_ == Thread::Current());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700244 DCHECK(thread != nullptr);
245 if (wait_set_ == nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700246 return;
247 }
248 if (wait_set_ == thread) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700249 wait_set_ = thread->GetWaitNext();
250 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700251 return;
252 }
253
254 Thread* t = wait_set_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700255 while (t->GetWaitNext() != nullptr) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700256 if (t->GetWaitNext() == thread) {
257 t->SetWaitNext(thread->GetWaitNext());
258 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700259 return;
260 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700261 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700262 }
263}
264
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700265void Monitor::SetObject(mirror::Object* object) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700266 obj_ = GcRoot<mirror::Object>(object);
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700267}
268
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700269// Note: Adapted from CurrentMethodVisitor in thread.cc. We must not resolve here.
270
271struct NthCallerWithDexPcVisitor FINAL : public StackVisitor {
272 explicit NthCallerWithDexPcVisitor(Thread* thread, size_t frame)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700273 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +0100274 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700275 method_(nullptr),
276 dex_pc_(0),
277 current_frame_number_(0),
278 wanted_frame_number_(frame) {}
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700279 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700280 ArtMethod* m = GetMethod();
281 if (m == nullptr || m->IsRuntimeMethod()) {
282 // Runtime method, upcall, or resolution issue. Skip.
283 return true;
284 }
285
286 // Is this the requested frame?
287 if (current_frame_number_ == wanted_frame_number_) {
288 method_ = m;
289 dex_pc_ = GetDexPc(false /* abort_on_error*/);
290 return false;
291 }
292
293 // Look for more.
294 current_frame_number_++;
295 return true;
296 }
297
298 ArtMethod* method_;
299 uint32_t dex_pc_;
300
301 private:
302 size_t current_frame_number_;
303 const size_t wanted_frame_number_;
304};
305
306// This function is inlined and just helps to not have the VLOG and ATRACE check at all the
307// potential tracing points.
308void Monitor::AtraceMonitorLock(Thread* self, mirror::Object* obj, bool is_wait) {
309 if (UNLIKELY(VLOG_IS_ON(systrace_lock_logging) && ATRACE_ENABLED())) {
310 AtraceMonitorLockImpl(self, obj, is_wait);
311 }
312}
313
314void Monitor::AtraceMonitorLockImpl(Thread* self, mirror::Object* obj, bool is_wait) {
315 // Wait() requires a deeper call stack to be useful. Otherwise you'll see "Waiting at
316 // Object.java". Assume that we'll wait a nontrivial amount, so it's OK to do a longer
317 // stack walk than if !is_wait.
318 NthCallerWithDexPcVisitor visitor(self, is_wait ? 1U : 0U);
319 visitor.WalkStack(false);
320 const char* prefix = is_wait ? "Waiting on " : "Locking ";
321
322 const char* filename;
323 int32_t line_number;
324 TranslateLocation(visitor.method_, visitor.dex_pc_, &filename, &line_number);
325
326 // It would be nice to have a stable "ID" for the object here. However, the only stable thing
327 // would be the identity hashcode. But we cannot use IdentityHashcode here: For one, there are
328 // times when it is unsafe to make that call (see stack dumping for an explanation). More
329 // importantly, we would have to give up on thin-locking when adding systrace locks, as the
330 // identity hashcode is stored in the lockword normally (so can't be used with thin-locks).
331 //
332 // Because of thin-locks we also cannot use the monitor id (as there is no monitor). Monitor ids
333 // also do not have to be stable, as the monitor may be deflated.
334 std::string tmp = StringPrintf("%s %d at %s:%d",
335 prefix,
336 (obj == nullptr ? -1 : static_cast<int32_t>(reinterpret_cast<uintptr_t>(obj))),
337 (filename != nullptr ? filename : "null"),
338 line_number);
339 ATRACE_BEGIN(tmp.c_str());
340}
341
342void Monitor::AtraceMonitorUnlock() {
343 if (UNLIKELY(VLOG_IS_ON(systrace_lock_logging))) {
344 ATRACE_END();
345 }
346}
347
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700348std::string Monitor::PrettyContentionInfo(const std::string& owner_name,
349 pid_t owner_tid,
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700350 ArtMethod* owners_method,
351 uint32_t owners_dex_pc,
352 size_t num_waiters) {
Hiroshi Yamauchi71cd68d2017-01-25 18:28:12 -0800353 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700354 const char* owners_filename;
Goran Jakovljevic49c882b2016-04-19 10:27:21 +0200355 int32_t owners_line_number = 0;
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700356 if (owners_method != nullptr) {
357 TranslateLocation(owners_method, owners_dex_pc, &owners_filename, &owners_line_number);
358 }
359 std::ostringstream oss;
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700360 oss << "monitor contention with owner " << owner_name << " (" << owner_tid << ")";
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700361 if (owners_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700362 oss << " at " << owners_method->PrettyMethod();
Mathieu Chartier36891fe2016-04-28 17:21:08 -0700363 oss << "(" << owners_filename << ":" << owners_line_number << ")";
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700364 }
365 oss << " waiters=" << num_waiters;
366 return oss.str();
367}
368
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700369bool Monitor::TryLockLocked(Thread* self) {
370 if (owner_ == nullptr) { // Unowned.
371 owner_ = self;
372 CHECK_EQ(lock_count_, 0);
373 // When debugging, save the current monitor holder for future
374 // acquisition failures to use in sampled logging.
375 if (lock_profiling_threshold_ != 0) {
376 locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
Andreas Gampe5a387272017-11-06 19:47:16 -0800377 // We don't expect a proxy method here.
378 DCHECK(locking_method_ == nullptr || !locking_method_->IsProxyMethod());
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700379 }
380 } else if (owner_ == self) { // Recursive.
381 lock_count_++;
382 } else {
383 return false;
384 }
385 AtraceMonitorLock(self, GetObject(), false /* is_wait */);
386 return true;
387}
388
389bool Monitor::TryLock(Thread* self) {
390 MutexLock mu(self, monitor_lock_);
391 return TryLockLocked(self);
392}
393
Alex Light77fee872017-09-05 14:51:49 -0700394// Asserts that a mutex isn't held when the class comes into and out of scope.
395class ScopedAssertNotHeld {
396 public:
397 ScopedAssertNotHeld(Thread* self, Mutex& mu) : self_(self), mu_(mu) {
398 mu_.AssertNotHeld(self_);
399 }
400
401 ~ScopedAssertNotHeld() {
402 mu_.AssertNotHeld(self_);
403 }
404
405 private:
406 Thread* const self_;
407 Mutex& mu_;
408 DISALLOW_COPY_AND_ASSIGN(ScopedAssertNotHeld);
409};
410
411template <LockReason reason>
Elliott Hughes5f791332011-09-15 17:45:30 -0700412void Monitor::Lock(Thread* self) {
Alex Light77fee872017-09-05 14:51:49 -0700413 ScopedAssertNotHeld sanh(self, monitor_lock_);
414 bool called_monitors_callback = false;
415 monitor_lock_.Lock(self);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700416 while (true) {
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700417 if (TryLockLocked(self)) {
Alex Light77fee872017-09-05 14:51:49 -0700418 break;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700419 }
420 // Contended.
421 const bool log_contention = (lock_profiling_threshold_ != 0);
Xin Guanb894a192014-08-22 11:55:37 -0500422 uint64_t wait_start_ms = log_contention ? MilliTime() : 0;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700423 ArtMethod* owners_method = locking_method_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700424 uint32_t owners_dex_pc = locking_dex_pc_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700425 // Do this before releasing the lock so that we don't get deflated.
Mathieu Chartierb9001ab2014-10-03 13:28:46 -0700426 size_t num_waiters = num_waiters_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700427 ++num_waiters_;
Andreas Gampe2702d562017-02-06 09:48:00 -0800428
429 // If systrace logging is enabled, first look at the lock owner. Acquiring the monitor's
430 // lock and then re-acquiring the mutator lock can deadlock.
431 bool started_trace = false;
432 if (ATRACE_ENABLED()) {
433 if (owner_ != nullptr) { // Did the owner_ give the lock up?
434 std::ostringstream oss;
435 std::string name;
436 owner_->GetThreadName(name);
437 oss << PrettyContentionInfo(name,
438 owner_->GetTid(),
439 owners_method,
440 owners_dex_pc,
441 num_waiters);
442 // Add info for contending thread.
443 uint32_t pc;
444 ArtMethod* m = self->GetCurrentMethod(&pc);
445 const char* filename;
446 int32_t line_number;
447 TranslateLocation(m, pc, &filename, &line_number);
448 oss << " blocking from "
449 << ArtMethod::PrettyMethod(m) << "(" << (filename != nullptr ? filename : "null")
450 << ":" << line_number << ")";
451 ATRACE_BEGIN(oss.str().c_str());
452 started_trace = true;
453 }
454 }
455
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700456 monitor_lock_.Unlock(self); // Let go of locks in order.
Alex Light77fee872017-09-05 14:51:49 -0700457 // Call the contended locking cb once and only once. Also only call it if we are locking for
458 // the first time, not during a Wait wakeup.
459 if (reason == LockReason::kForLock && !called_monitors_callback) {
460 called_monitors_callback = true;
461 Runtime::Current()->GetRuntimeCallbacks()->MonitorContendedLocking(this);
462 }
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700463 self->SetMonitorEnterObject(GetObject());
Elliott Hughes5f791332011-09-15 17:45:30 -0700464 {
Hiroshi Yamauchi71cd68d2017-01-25 18:28:12 -0800465 ScopedThreadSuspension tsc(self, kBlocked); // Change to blocked and give up mutator_lock_.
Andreas Gampe2702d562017-02-06 09:48:00 -0800466 uint32_t original_owner_thread_id = 0u;
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700467 {
468 // Reacquire monitor_lock_ without mutator_lock_ for Wait.
469 MutexLock mu2(self, monitor_lock_);
470 if (owner_ != nullptr) { // Did the owner_ give the lock up?
471 original_owner_thread_id = owner_->GetThreadId();
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700472 monitor_contenders_.Wait(self); // Still contended so wait.
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800473 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700474 }
475 if (original_owner_thread_id != 0u) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700476 // Woken from contention.
477 if (log_contention) {
Andreas Gampe111b1092017-06-22 20:28:23 -0700478 uint64_t wait_ms = MilliTime() - wait_start_ms;
479 uint32_t sample_percent;
480 if (wait_ms >= lock_profiling_threshold_) {
481 sample_percent = 100;
482 } else {
483 sample_percent = 100 * wait_ms / lock_profiling_threshold_;
484 }
485 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
486 // Reacquire mutator_lock_ for logging.
487 ScopedObjectAccess soa(self);
Andreas Gampe111b1092017-06-22 20:28:23 -0700488
Andreas Gamped0210e52017-06-23 13:38:09 -0700489 bool owner_alive = false;
490 pid_t original_owner_tid = 0;
491 std::string original_owner_name;
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700492
Andreas Gamped0210e52017-06-23 13:38:09 -0700493 const bool should_dump_stacks = stack_dump_lock_profiling_threshold_ > 0 &&
494 wait_ms > stack_dump_lock_profiling_threshold_;
495 std::string owner_stack_dump;
Andreas Gampe111b1092017-06-22 20:28:23 -0700496
Andreas Gamped0210e52017-06-23 13:38:09 -0700497 // Acquire thread-list lock to find thread and keep it from dying until we've got all
498 // the info we need.
499 {
Alex Lightb1e31a82017-10-04 16:57:36 -0700500 Locks::thread_list_lock_->ExclusiveLock(Thread::Current());
Andreas Gamped0210e52017-06-23 13:38:09 -0700501
502 // Re-find the owner in case the thread got killed.
503 Thread* original_owner = Runtime::Current()->GetThreadList()->FindThreadByThreadId(
504 original_owner_thread_id);
505
506 if (original_owner != nullptr) {
507 owner_alive = true;
508 original_owner_tid = original_owner->GetTid();
509 original_owner->GetThreadName(original_owner_name);
510
511 if (should_dump_stacks) {
512 // Very long contention. Dump stacks.
513 struct CollectStackTrace : public Closure {
514 void Run(art::Thread* thread) OVERRIDE
515 REQUIRES_SHARED(art::Locks::mutator_lock_) {
516 thread->DumpJavaStack(oss);
517 }
518
519 std::ostringstream oss;
520 };
521 CollectStackTrace owner_trace;
Alex Lightb1e31a82017-10-04 16:57:36 -0700522 // RequestSynchronousCheckpoint releases the thread_list_lock_ as a part of its
523 // execution.
Andreas Gamped0210e52017-06-23 13:38:09 -0700524 original_owner->RequestSynchronousCheckpoint(&owner_trace);
525 owner_stack_dump = owner_trace.oss.str();
Alex Lightb1e31a82017-10-04 16:57:36 -0700526 } else {
527 Locks::thread_list_lock_->ExclusiveUnlock(Thread::Current());
Andreas Gamped0210e52017-06-23 13:38:09 -0700528 }
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 }
532 // This is all the data we need. Now drop the thread-list lock, it's OK for the
533 // owner to go away now.
534 }
535
536 // If we found the owner (and thus have owner data), go and log now.
537 if (owner_alive) {
538 // Give the detailed traces for really long contention.
539 if (should_dump_stacks) {
540 // This must be here (and not above) because we cannot hold the thread-list lock
541 // while running the checkpoint.
542 std::ostringstream self_trace_oss;
543 self->DumpJavaStack(self_trace_oss);
544
545 uint32_t pc;
546 ArtMethod* m = self->GetCurrentMethod(&pc);
547
548 LOG(WARNING) << "Long "
549 << PrettyContentionInfo(original_owner_name,
550 original_owner_tid,
551 owners_method,
552 owners_dex_pc,
553 num_waiters)
554 << " in " << ArtMethod::PrettyMethod(m) << " for "
555 << PrettyDuration(MsToNs(wait_ms)) << "\n"
556 << "Current owner stack:\n" << owner_stack_dump
557 << "Contender stack:\n" << self_trace_oss.str();
558 } else if (wait_ms > kLongWaitMs && owners_method != nullptr) {
Mathieu Chartier36891fe2016-04-28 17:21:08 -0700559 uint32_t pc;
560 ArtMethod* m = self->GetCurrentMethod(&pc);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700561 // TODO: We should maybe check that original_owner is still a live thread.
562 LOG(WARNING) << "Long "
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700563 << PrettyContentionInfo(original_owner_name,
564 original_owner_tid,
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700565 owners_method,
566 owners_dex_pc,
567 num_waiters)
David Sehr709b0702016-10-13 09:12:37 -0700568 << " in " << ArtMethod::PrettyMethod(m) << " for "
569 << PrettyDuration(MsToNs(wait_ms));
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700570 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700571 LogContentionEvent(self,
Alex Light77fee872017-09-05 14:51:49 -0700572 wait_ms,
573 sample_percent,
574 owners_method,
575 owners_dex_pc);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700576 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700577 }
578 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700579 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700580 }
Andreas Gampe2702d562017-02-06 09:48:00 -0800581 if (started_trace) {
582 ATRACE_END();
583 }
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700584 self->SetMonitorEnterObject(nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700585 monitor_lock_.Lock(self); // Reacquire locks in order.
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700586 --num_waiters_;
Elliott Hughesfc861622011-10-17 17:57:47 -0700587 }
Alex Light77fee872017-09-05 14:51:49 -0700588 monitor_lock_.Unlock(self);
589 // We need to pair this with a single contended locking call. NB we match the RI behavior and call
590 // this even if MonitorEnter failed.
591 if (called_monitors_callback) {
592 CHECK(reason == LockReason::kForLock);
593 Runtime::Current()->GetRuntimeCallbacks()->MonitorContendedLocked(this);
594 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700595}
596
Alex Light77fee872017-09-05 14:51:49 -0700597template void Monitor::Lock<LockReason::kForLock>(Thread* self);
598template void Monitor::Lock<LockReason::kForWait>(Thread* self);
599
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800600static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
601 __attribute__((format(printf, 1, 2)));
602
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700603static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700604 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800605 va_list args;
606 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800607 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000608 self->ThrowNewExceptionV("Ljava/lang/IllegalMonitorStateException;", fmt, args);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700609 if (!Runtime::Current()->IsStarted() || VLOG_IS_ON(monitor)) {
Brian Carlstrom64277f32012-03-26 23:53:34 -0700610 std::ostringstream ss;
Ian Rogers62d6c772013-02-27 08:32:07 -0800611 self->Dump(ss);
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700612 LOG(Runtime::Current()->IsStarted() ? ::android::base::INFO : ::android::base::ERROR)
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000613 << self->GetException()->Dump() << "\n" << ss.str();
Brian Carlstrom64277f32012-03-26 23:53:34 -0700614 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800615 va_end(args);
616}
617
Elliott Hughesd4237412012-02-21 11:24:45 -0800618static std::string ThreadToString(Thread* thread) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700619 if (thread == nullptr) {
620 return "nullptr";
Elliott Hughesd4237412012-02-21 11:24:45 -0800621 }
622 std::ostringstream oss;
623 // TODO: alternatively, we could just return the thread's name.
624 oss << *thread;
625 return oss.str();
626}
627
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700628void Monitor::FailedUnlock(mirror::Object* o,
629 uint32_t expected_owner_thread_id,
630 uint32_t found_owner_thread_id,
Elliott Hughesffb465f2012-03-01 18:46:05 -0800631 Monitor* monitor) {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700632 // Acquire thread list lock so threads won't disappear from under us.
Elliott Hughesffb465f2012-03-01 18:46:05 -0800633 std::string current_owner_string;
634 std::string expected_owner_string;
635 std::string found_owner_string;
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700636 uint32_t current_owner_thread_id = 0u;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800637 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700638 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700639 ThreadList* const thread_list = Runtime::Current()->GetThreadList();
640 Thread* expected_owner = thread_list->FindThreadByThreadId(expected_owner_thread_id);
641 Thread* found_owner = thread_list->FindThreadByThreadId(found_owner_thread_id);
642
Elliott Hughesffb465f2012-03-01 18:46:05 -0800643 // Re-read owner now that we hold lock.
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700644 Thread* current_owner = (monitor != nullptr) ? monitor->GetOwner() : nullptr;
645 if (current_owner != nullptr) {
646 current_owner_thread_id = current_owner->GetThreadId();
647 }
Elliott Hughesffb465f2012-03-01 18:46:05 -0800648 // Get short descriptions of the threads involved.
649 current_owner_string = ThreadToString(current_owner);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700650 expected_owner_string = expected_owner != nullptr ? ThreadToString(expected_owner) : "unnamed";
651 found_owner_string = found_owner != nullptr ? ThreadToString(found_owner) : "unnamed";
Elliott Hughesffb465f2012-03-01 18:46:05 -0800652 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700653
654 if (current_owner_thread_id == 0u) {
655 if (found_owner_thread_id == 0u) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800656 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
657 " on thread '%s'",
David Sehr709b0702016-10-13 09:12:37 -0700658 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800659 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800660 } else {
661 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800662 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
663 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800664 found_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700665 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800666 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800667 }
668 } else {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700669 if (found_owner_thread_id == 0u) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800670 // Race: originally there was no owner, there is now
671 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
672 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800673 current_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700674 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800675 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800676 } else {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700677 if (found_owner_thread_id != current_owner_thread_id) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800678 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800679 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
680 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800681 found_owner_string.c_str(),
682 current_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700683 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800684 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800685 } else {
686 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
687 " on thread '%s",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800688 current_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700689 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800690 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800691 }
692 }
693 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700694}
695
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700696bool Monitor::Unlock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700697 DCHECK(self != nullptr);
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700698 uint32_t owner_thread_id = 0u;
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700699 {
700 MutexLock mu(self, monitor_lock_);
701 Thread* owner = owner_;
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700702 if (owner != nullptr) {
703 owner_thread_id = owner->GetThreadId();
704 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700705 if (owner == self) {
706 // We own the monitor, so nobody else can be in here.
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700707 AtraceMonitorUnlock();
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700708 if (lock_count_ == 0) {
709 owner_ = nullptr;
710 locking_method_ = nullptr;
711 locking_dex_pc_ = 0;
712 // Wake a contender.
713 monitor_contenders_.Signal(self);
714 } else {
715 --lock_count_;
716 }
717 return true;
Elliott Hughes5f791332011-09-15 17:45:30 -0700718 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700719 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700720 // We don't own this, so we're not allowed to unlock it.
721 // The JNI spec says that we should throw IllegalMonitorStateException in this case.
722 FailedUnlock(GetObject(), self->GetThreadId(), owner_thread_id, this);
723 return false;
Elliott Hughes5f791332011-09-15 17:45:30 -0700724}
725
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800726void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
727 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700728 DCHECK(self != nullptr);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800729 DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
Elliott Hughes5f791332011-09-15 17:45:30 -0700730
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700731 monitor_lock_.Lock(self);
732
Elliott Hughes5f791332011-09-15 17:45:30 -0700733 // Make sure that we hold the lock.
734 if (owner_ != self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700735 monitor_lock_.Unlock(self);
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700736 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700737 return;
738 }
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800739
Elliott Hughesdf42c482013-01-09 12:49:02 -0800740 // We need to turn a zero-length timed wait into a regular wait because
741 // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
742 if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
743 why = kWaiting;
744 }
745
Elliott Hughes5f791332011-09-15 17:45:30 -0700746 // Enforce the timeout range.
747 if (ms < 0 || ns < 0 || ns > 999999) {
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700748 monitor_lock_.Unlock(self);
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000749 self->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
Ian Rogersef7d42f2014-01-06 12:55:46 -0800750 "timeout arguments out of range: ms=%" PRId64 " ns=%d", ms, ns);
Elliott Hughes5f791332011-09-15 17:45:30 -0700751 return;
752 }
753
Elliott Hughes5f791332011-09-15 17:45:30 -0700754 /*
755 * Add ourselves to the set of threads waiting on this monitor, and
756 * release our hold. We need to let it go even if we're a few levels
757 * deep in a recursive lock, and we need to restore that later.
758 *
759 * We append to the wait set ahead of clearing the count and owner
760 * fields so the subroutine can check that the calling thread owns
761 * the monitor. Aside from that, the order of member updates is
762 * not order sensitive as we hold the pthread mutex.
763 */
764 AppendToWaitSet(self);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700765 ++num_waiters_;
Ian Rogers0399dde2012-06-06 17:09:28 -0700766 int prev_lock_count = lock_count_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700767 lock_count_ = 0;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700768 owner_ = nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700769 ArtMethod* saved_method = locking_method_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700770 locking_method_ = nullptr;
Ian Rogers0399dde2012-06-06 17:09:28 -0700771 uintptr_t saved_dex_pc = locking_dex_pc_;
772 locking_dex_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700773
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700774 AtraceMonitorUnlock(); // For the implict Unlock() just above. This will only end the deepest
775 // nesting, but that is enough for the visualization, and corresponds to
776 // the single Lock() we do afterwards.
777 AtraceMonitorLock(self, GetObject(), true /* is_wait */);
778
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800779 bool was_interrupted = false;
Alex Light77fee872017-09-05 14:51:49 -0700780 bool timed_out = false;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700781 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700782 // Update thread state. If the GC wakes up, it'll ignore us, knowing
783 // that we won't touch any references in this state, and we'll check
784 // our suspend mode before we transition out.
785 ScopedThreadSuspension sts(self, why);
786
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700787 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700788 MutexLock mu(self, *self->GetWaitMutex());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700789
790 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700791 // non-null a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700792 // up.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700793 DCHECK(self->GetWaitMonitor() == nullptr);
794 self->SetWaitMonitor(this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700795
796 // Release the monitor lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700797 monitor_contenders_.Signal(self);
798 monitor_lock_.Unlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700799
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800800 // Handle the case where the thread was interrupted before we called wait().
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000801 if (self->IsInterrupted()) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800802 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700803 } else {
804 // Wait for a notification or a timeout to occur.
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800805 if (why == kWaiting) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700806 self->GetWaitConditionVariable()->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700807 } else {
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800808 DCHECK(why == kTimedWaiting || why == kSleeping) << why;
Alex Light77fee872017-09-05 14:51:49 -0700809 timed_out = self->GetWaitConditionVariable()->TimedWait(self, ms, ns);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700810 }
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000811 was_interrupted = self->IsInterrupted();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700812 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700813 }
814
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800815 {
816 // We reset the thread's wait_monitor_ field after transitioning back to runnable so
817 // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
818 // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
819 // are waiting on "null".)
Ian Rogersdd7624d2014-03-14 17:43:00 -0700820 MutexLock mu(self, *self->GetWaitMutex());
821 DCHECK(self->GetWaitMonitor() != nullptr);
822 self->SetWaitMonitor(nullptr);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800823 }
824
Mathieu Chartierdaed5d82016-03-10 10:49:35 -0800825 // Allocate the interrupted exception not holding the monitor lock since it may cause a GC.
826 // If the GC requires acquiring the monitor for enqueuing cleared references, this would
827 // cause a deadlock if the monitor is held.
828 if (was_interrupted && interruptShouldThrow) {
829 /*
830 * We were interrupted while waiting, or somebody interrupted an
831 * un-interruptible thread earlier and we're bailing out immediately.
832 *
833 * The doc sayeth: "The interrupted status of the current thread is
834 * cleared when this exception is thrown."
835 */
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000836 self->SetInterrupted(false);
Mathieu Chartierdaed5d82016-03-10 10:49:35 -0800837 self->ThrowNewException("Ljava/lang/InterruptedException;", nullptr);
838 }
839
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700840 AtraceMonitorUnlock(); // End Wait().
841
Alex Light77fee872017-09-05 14:51:49 -0700842 // We just slept, tell the runtime callbacks about this.
843 Runtime::Current()->GetRuntimeCallbacks()->MonitorWaitFinished(this, timed_out);
844
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700845 // Re-acquire the monitor and lock.
Alex Light77fee872017-09-05 14:51:49 -0700846 Lock<LockReason::kForWait>(self);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700847 monitor_lock_.Lock(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700848 self->GetWaitMutex()->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700849
Elliott Hughes5f791332011-09-15 17:45:30 -0700850 /*
851 * We remove our thread from wait set after restoring the count
852 * and owner fields so the subroutine can check that the calling
853 * thread owns the monitor. Aside from that, the order of member
854 * updates is not order sensitive as we hold the pthread mutex.
855 */
856 owner_ = self;
Ian Rogers0399dde2012-06-06 17:09:28 -0700857 lock_count_ = prev_lock_count;
858 locking_method_ = saved_method;
859 locking_dex_pc_ = saved_dex_pc;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700860 --num_waiters_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700861 RemoveFromWaitSet(self);
862
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700863 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700864}
865
866void Monitor::Notify(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700867 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700868 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700869 // Make sure that we hold the lock.
870 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800871 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700872 return;
873 }
874 // Signal the first waiting thread in the wait set.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700875 while (wait_set_ != nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700876 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700877 wait_set_ = thread->GetWaitNext();
878 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700879
880 // Check to see if the thread is still waiting.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800881 MutexLock wait_mu(self, *thread->GetWaitMutex());
Ian Rogersdd7624d2014-03-14 17:43:00 -0700882 if (thread->GetWaitMonitor() != nullptr) {
883 thread->GetWaitConditionVariable()->Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700884 return;
885 }
886 }
887}
888
889void Monitor::NotifyAll(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700890 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700891 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700892 // Make sure that we hold the lock.
893 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800894 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700895 return;
896 }
897 // Signal all threads in the wait set.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700898 while (wait_set_ != nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700899 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700900 wait_set_ = thread->GetWaitNext();
901 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700902 thread->Notify();
903 }
904}
905
Mathieu Chartier590fee92013-09-13 13:46:47 -0700906bool Monitor::Deflate(Thread* self, mirror::Object* obj) {
907 DCHECK(obj != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700908 // Don't need volatile since we only deflate with mutators suspended.
909 LockWord lw(obj->GetLockWord(false));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700910 // If the lock isn't an inflated monitor, then we don't need to deflate anything.
911 if (lw.GetState() == LockWord::kFatLocked) {
912 Monitor* monitor = lw.FatLockMonitor();
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700913 DCHECK(monitor != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700914 MutexLock mu(self, monitor->monitor_lock_);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700915 // Can't deflate if we have anybody waiting on the CV.
916 if (monitor->num_waiters_ > 0) {
917 return false;
918 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700919 Thread* owner = monitor->owner_;
920 if (owner != nullptr) {
921 // Can't deflate if we are locked and have a hash code.
922 if (monitor->HasHashCode()) {
923 return false;
924 }
925 // Can't deflate if our lock count is too high.
Mathieu Chartier1cf194f2016-11-01 20:13:24 -0700926 if (static_cast<uint32_t>(monitor->lock_count_) > LockWord::kThinLockMaxCount) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700927 return false;
928 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700929 // Deflate to a thin lock.
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700930 LockWord new_lw = LockWord::FromThinLockId(owner->GetThreadId(),
931 monitor->lock_count_,
932 lw.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800933 // Assume no concurrent read barrier state changes as mutators are suspended.
934 obj->SetLockWord(new_lw, false);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700935 VLOG(monitor) << "Deflated " << obj << " to thin lock " << owner->GetTid() << " / "
936 << monitor->lock_count_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700937 } else if (monitor->HasHashCode()) {
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700938 LockWord new_lw = LockWord::FromHashCode(monitor->GetHashCode(), lw.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800939 // Assume no concurrent read barrier state changes as mutators are suspended.
940 obj->SetLockWord(new_lw, false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700941 VLOG(monitor) << "Deflated " << obj << " to hash monitor " << monitor->GetHashCode();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700942 } else {
943 // No lock and no hash, just put an empty lock word inside the object.
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700944 LockWord new_lw = LockWord::FromDefault(lw.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800945 // Assume no concurrent read barrier state changes as mutators are suspended.
946 obj->SetLockWord(new_lw, false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700947 VLOG(monitor) << "Deflated" << obj << " to empty lock word";
Mathieu Chartier590fee92013-09-13 13:46:47 -0700948 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700949 // 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 -0700950 // next GC.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700951 monitor->obj_ = GcRoot<mirror::Object>(nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700952 }
953 return true;
954}
955
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700956void Monitor::Inflate(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code) {
Andreas Gampe74240812014-04-17 10:35:09 -0700957 DCHECK(self != nullptr);
958 DCHECK(obj != nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700959 // Allocate and acquire a new monitor.
Andreas Gampe74240812014-04-17 10:35:09 -0700960 Monitor* m = MonitorPool::CreateMonitor(self, owner, obj, hash_code);
961 DCHECK(m != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700962 if (m->Install(self)) {
Haifeng Li86ab7912014-05-16 10:47:59 +0800963 if (owner != nullptr) {
964 VLOG(monitor) << "monitor: thread" << owner->GetThreadId()
Andreas Gampe74240812014-04-17 10:35:09 -0700965 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800966 } else {
967 VLOG(monitor) << "monitor: Inflate with hashcode " << hash_code
Andreas Gampe74240812014-04-17 10:35:09 -0700968 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800969 }
Andreas Gampe74240812014-04-17 10:35:09 -0700970 Runtime::Current()->GetMonitorList()->Add(m);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700971 CHECK_EQ(obj->GetLockWord(true).GetState(), LockWord::kFatLocked);
Andreas Gampe74240812014-04-17 10:35:09 -0700972 } else {
973 MonitorPool::ReleaseMonitor(self, m);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700974 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700975}
976
Mathieu Chartier0cd81352014-05-22 16:48:55 -0700977void Monitor::InflateThinLocked(Thread* self, Handle<mirror::Object> obj, LockWord lock_word,
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700978 uint32_t hash_code) {
979 DCHECK_EQ(lock_word.GetState(), LockWord::kThinLocked);
980 uint32_t owner_thread_id = lock_word.ThinLockOwner();
981 if (owner_thread_id == self->GetThreadId()) {
982 // We own the monitor, we can easily inflate it.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700983 Inflate(self, self, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700984 } else {
985 ThreadList* thread_list = Runtime::Current()->GetThreadList();
986 // Suspend the owner, inflate. First change to blocked and give up mutator_lock_.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700987 self->SetMonitorEnterObject(obj.Get());
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700988 bool timed_out;
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700989 Thread* owner;
990 {
Alex Light77fee872017-09-05 14:51:49 -0700991 ScopedThreadSuspension sts(self, kWaitingForLockInflation);
Alex Light46f93402017-06-29 11:59:50 -0700992 owner = thread_list->SuspendThreadByThreadId(owner_thread_id,
993 SuspendReason::kInternal,
994 &timed_out);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700995 }
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700996 if (owner != nullptr) {
997 // We succeeded in suspending the thread, check the lock's status didn't change.
998 lock_word = obj->GetLockWord(true);
999 if (lock_word.GetState() == LockWord::kThinLocked &&
1000 lock_word.ThinLockOwner() == owner_thread_id) {
1001 // Go ahead and inflate the lock.
1002 Inflate(self, owner, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001003 }
Alex Light88fd7202017-06-30 08:31:59 -07001004 bool resumed = thread_list->Resume(owner, SuspendReason::kInternal);
1005 DCHECK(resumed);
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001006 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07001007 self->SetMonitorEnterObject(nullptr);
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001008 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001009}
1010
Ian Rogers719d1a32014-03-06 12:13:39 -08001011// Fool annotalysis into thinking that the lock on obj is acquired.
1012static mirror::Object* FakeLock(mirror::Object* obj)
1013 EXCLUSIVE_LOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
1014 return obj;
1015}
1016
1017// Fool annotalysis into thinking that the lock on obj is release.
1018static mirror::Object* FakeUnlock(mirror::Object* obj)
1019 UNLOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
1020 return obj;
1021}
1022
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07001023mirror::Object* Monitor::MonitorEnter(Thread* self, mirror::Object* obj, bool trylock) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001024 DCHECK(self != nullptr);
1025 DCHECK(obj != nullptr);
Mathieu Chartier2d096c92015-10-12 16:18:20 -07001026 self->AssertThreadSuspensionIsAllowable();
Ian Rogers719d1a32014-03-06 12:13:39 -08001027 obj = FakeLock(obj);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001028 uint32_t thread_id = self->GetThreadId();
1029 size_t contention_count = 0;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001030 StackHandleScope<1> hs(self);
1031 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001032 while (true) {
Hans Boehmb3da36c2016-12-15 13:12:59 -08001033 // We initially read the lockword with ordinary Java/relaxed semantics. When stronger
1034 // semantics are needed, we address it below. Since GetLockWord bottoms out to a relaxed load,
1035 // we can fix it later, in an infrequently executed case, with a fence.
1036 LockWord lock_word = h_obj->GetLockWord(false);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001037 switch (lock_word.GetState()) {
1038 case LockWord::kUnlocked: {
Hans Boehmb3da36c2016-12-15 13:12:59 -08001039 // No ordering required for preceding lockword read, since we retest.
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001040 LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0, lock_word.GCState()));
Hans Boehmb3da36c2016-12-15 13:12:59 -08001041 if (h_obj->CasLockWordWeakAcquire(lock_word, thin_locked)) {
Andreas Gampec7ed09b2016-04-25 20:08:55 -07001042 AtraceMonitorLock(self, h_obj.Get(), false /* is_wait */);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001043 return h_obj.Get(); // Success!
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001044 }
1045 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -07001046 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001047 case LockWord::kThinLocked: {
1048 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1049 if (owner_thread_id == thread_id) {
Hans Boehmb3da36c2016-12-15 13:12:59 -08001050 // No ordering required for initial lockword read.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001051 // We own the lock, increase the recursion count.
1052 uint32_t new_count = lock_word.ThinLockCount() + 1;
1053 if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001054 LockWord thin_locked(LockWord::FromThinLockId(thread_id,
1055 new_count,
1056 lock_word.GCState()));
Hans Boehmb3da36c2016-12-15 13:12:59 -08001057 // Only this thread pays attention to the count. Thus there is no need for stronger
1058 // than relaxed memory ordering.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001059 if (!kUseReadBarrier) {
Hans Boehmb3da36c2016-12-15 13:12:59 -08001060 h_obj->SetLockWord(thin_locked, false /* volatile */);
Andreas Gampec7ed09b2016-04-25 20:08:55 -07001061 AtraceMonitorLock(self, h_obj.Get(), false /* is_wait */);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001062 return h_obj.Get(); // Success!
1063 } else {
1064 // Use CAS to preserve the read barrier state.
Hans Boehmb3da36c2016-12-15 13:12:59 -08001065 if (h_obj->CasLockWordWeakRelaxed(lock_word, thin_locked)) {
Andreas Gampec7ed09b2016-04-25 20:08:55 -07001066 AtraceMonitorLock(self, h_obj.Get(), false /* is_wait */);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001067 return h_obj.Get(); // Success!
1068 }
1069 }
1070 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -07001071 } else {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001072 // We'd overflow the recursion count, so inflate the monitor.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001073 InflateThinLocked(self, h_obj, lock_word, 0);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001074 }
1075 } else {
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07001076 if (trylock) {
1077 return nullptr;
1078 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001079 // Contention.
1080 contention_count++;
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001081 Runtime* runtime = Runtime::Current();
Hans Boehmb3da36c2016-12-15 13:12:59 -08001082 if (contention_count <= runtime->GetMaxSpinsBeforeThinLockInflation()) {
Alex Light77fee872017-09-05 14:51:49 -07001083 // TODO: Consider switching the thread state to kWaitingForLockInflation when we are
1084 // yielding. Use sched_yield instead of NanoSleep since NanoSleep can wait much longer
1085 // than the parameter you pass in. This can cause thread suspension to take excessively
1086 // long and make long pauses. See b/16307460.
Hans Boehmb3da36c2016-12-15 13:12:59 -08001087 // TODO: We should literally spin first, without sched_yield. Sched_yield either does
1088 // nothing (at significant expense), or guarantees that we wait at least microseconds.
1089 // If the owner is running, I would expect the median lock hold time to be hundreds
1090 // of nanoseconds or less.
Mathieu Chartier251755c2014-07-15 18:10:25 -07001091 sched_yield();
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001092 } else {
1093 contention_count = 0;
Hans Boehmb3da36c2016-12-15 13:12:59 -08001094 // No ordering required for initial lockword read. Install rereads it anyway.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001095 InflateThinLocked(self, h_obj, lock_word, 0);
Elliott Hughes5f791332011-09-15 17:45:30 -07001096 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001097 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001098 continue; // Start from the beginning.
Elliott Hughes5f791332011-09-15 17:45:30 -07001099 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001100 case LockWord::kFatLocked: {
Hans Boehmb3da36c2016-12-15 13:12:59 -08001101 // We should have done an acquire read of the lockword initially, to ensure
1102 // visibility of the monitor data structure. Use an explicit fence instead.
1103 QuasiAtomic::ThreadFenceAcquire();
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001104 Monitor* mon = lock_word.FatLockMonitor();
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07001105 if (trylock) {
1106 return mon->TryLock(self) ? h_obj.Get() : nullptr;
1107 } else {
1108 mon->Lock(self);
1109 return h_obj.Get(); // Success!
1110 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001111 }
Ian Rogers719d1a32014-03-06 12:13:39 -08001112 case LockWord::kHashCode:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001113 // Inflate with the existing hashcode.
Hans Boehmb3da36c2016-12-15 13:12:59 -08001114 // Again no ordering required for initial lockword read, since we don't rely
1115 // on the visibility of any prior computation.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001116 Inflate(self, nullptr, h_obj.Get(), lock_word.GetHashCode());
Ian Rogers719d1a32014-03-06 12:13:39 -08001117 continue; // Start from the beginning.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001118 default: {
1119 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Andreas Gampec7ed09b2016-04-25 20:08:55 -07001120 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001121 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001122 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001123 }
1124}
1125
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001126bool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001127 DCHECK(self != nullptr);
1128 DCHECK(obj != nullptr);
Mathieu Chartier2d096c92015-10-12 16:18:20 -07001129 self->AssertThreadSuspensionIsAllowable();
Ian Rogers719d1a32014-03-06 12:13:39 -08001130 obj = FakeUnlock(obj);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001131 StackHandleScope<1> hs(self);
1132 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001133 while (true) {
1134 LockWord lock_word = obj->GetLockWord(true);
1135 switch (lock_word.GetState()) {
1136 case LockWord::kHashCode:
1137 // Fall-through.
1138 case LockWord::kUnlocked:
Mathieu Chartier61b3cd42016-04-18 11:43:29 -07001139 FailedUnlock(h_obj.Get(), self->GetThreadId(), 0u, nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001140 return false; // Failure.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001141 case LockWord::kThinLocked: {
1142 uint32_t thread_id = self->GetThreadId();
1143 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1144 if (owner_thread_id != thread_id) {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -07001145 FailedUnlock(h_obj.Get(), thread_id, owner_thread_id, nullptr);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001146 return false; // Failure.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001147 } else {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001148 // We own the lock, decrease the recursion count.
1149 LockWord new_lw = LockWord::Default();
1150 if (lock_word.ThinLockCount() != 0) {
1151 uint32_t new_count = lock_word.ThinLockCount() - 1;
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001152 new_lw = LockWord::FromThinLockId(thread_id, new_count, lock_word.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001153 } else {
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001154 new_lw = LockWord::FromDefault(lock_word.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001155 }
1156 if (!kUseReadBarrier) {
1157 DCHECK_EQ(new_lw.ReadBarrierState(), 0U);
Hans Boehmb3da36c2016-12-15 13:12:59 -08001158 // TODO: This really only needs memory_order_release, but we currently have
1159 // no way to specify that. In fact there seem to be no legitimate uses of SetLockWord
1160 // with a final argument of true. This slows down x86 and ARMv7, but probably not v8.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001161 h_obj->SetLockWord(new_lw, true);
Andreas Gampe6e759ad2016-05-17 10:13:10 -07001162 AtraceMonitorUnlock();
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001163 // Success!
1164 return true;
1165 } else {
1166 // Use CAS to preserve the read barrier state.
Hans Boehmb3da36c2016-12-15 13:12:59 -08001167 if (h_obj->CasLockWordWeakRelease(lock_word, new_lw)) {
Andreas Gampe6e759ad2016-05-17 10:13:10 -07001168 AtraceMonitorUnlock();
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001169 // Success!
1170 return true;
1171 }
1172 }
1173 continue; // Go again.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001174 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001175 }
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001176 case LockWord::kFatLocked: {
1177 Monitor* mon = lock_word.FatLockMonitor();
1178 return mon->Unlock(self);
1179 }
1180 default: {
1181 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1182 return false;
1183 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001184 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001185 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001186}
1187
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001188void Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
Elliott Hughes4cd121e2013-01-07 17:35:41 -08001189 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001190 DCHECK(self != nullptr);
1191 DCHECK(obj != nullptr);
Alex Light77fee872017-09-05 14:51:49 -07001192 StackHandleScope<1> hs(self);
1193 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
1194
1195 Runtime::Current()->GetRuntimeCallbacks()->ObjectWaitStart(h_obj, ms);
Alex Light848574c2017-09-25 16:59:39 -07001196 if (UNLIKELY(self->ObserveAsyncException() || self->IsExceptionPending())) {
Alex Light77fee872017-09-05 14:51:49 -07001197 // See b/65558434 for information on handling of exceptions here.
1198 return;
1199 }
1200
1201 LockWord lock_word = h_obj->GetLockWord(true);
Ian Rogers43c69cc2014-08-15 11:09:28 -07001202 while (lock_word.GetState() != LockWord::kFatLocked) {
1203 switch (lock_word.GetState()) {
1204 case LockWord::kHashCode:
1205 // Fall-through.
1206 case LockWord::kUnlocked:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001207 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
1208 return; // Failure.
Ian Rogers43c69cc2014-08-15 11:09:28 -07001209 case LockWord::kThinLocked: {
1210 uint32_t thread_id = self->GetThreadId();
1211 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1212 if (owner_thread_id != thread_id) {
1213 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
1214 return; // Failure.
1215 } else {
1216 // We own the lock, inflate to enqueue ourself on the Monitor. May fail spuriously so
1217 // re-load.
Alex Light77fee872017-09-05 14:51:49 -07001218 Inflate(self, self, h_obj.Get(), 0);
1219 lock_word = h_obj->GetLockWord(true);
Ian Rogers43c69cc2014-08-15 11:09:28 -07001220 }
1221 break;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001222 }
Ian Rogers43c69cc2014-08-15 11:09:28 -07001223 case LockWord::kFatLocked: // Unreachable given the loop condition above. Fall-through.
1224 default: {
1225 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1226 return;
1227 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001228 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001229 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001230 Monitor* mon = lock_word.FatLockMonitor();
1231 mon->Wait(self, ms, ns, interruptShouldThrow, why);
Elliott Hughes5f791332011-09-15 17:45:30 -07001232}
1233
Ian Rogers13c479e2013-10-11 07:59:01 -07001234void Monitor::DoNotify(Thread* self, mirror::Object* obj, bool notify_all) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001235 DCHECK(self != nullptr);
1236 DCHECK(obj != nullptr);
1237 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001238 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001239 case LockWord::kHashCode:
1240 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001241 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -08001242 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001243 return; // Failure.
1244 case LockWord::kThinLocked: {
1245 uint32_t thread_id = self->GetThreadId();
1246 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1247 if (owner_thread_id != thread_id) {
1248 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
1249 return; // Failure.
1250 } else {
1251 // We own the lock but there's no Monitor and therefore no waiters.
1252 return; // Success.
1253 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001254 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001255 case LockWord::kFatLocked: {
1256 Monitor* mon = lock_word.FatLockMonitor();
1257 if (notify_all) {
1258 mon->NotifyAll(self);
1259 } else {
1260 mon->Notify(self);
1261 }
1262 return; // Success.
1263 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001264 default: {
1265 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1266 return;
1267 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001268 }
1269}
1270
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001271uint32_t Monitor::GetLockOwnerThreadId(mirror::Object* obj) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001272 DCHECK(obj != nullptr);
1273 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001274 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001275 case LockWord::kHashCode:
1276 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001277 case LockWord::kUnlocked:
1278 return ThreadList::kInvalidThreadId;
1279 case LockWord::kThinLocked:
1280 return lock_word.ThinLockOwner();
1281 case LockWord::kFatLocked: {
1282 Monitor* mon = lock_word.FatLockMonitor();
1283 return mon->GetOwnerThreadId();
Elliott Hughes5f791332011-09-15 17:45:30 -07001284 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001285 default: {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001286 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001287 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001288 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001289 }
1290}
1291
Andreas Gampef3ebcce2017-12-11 20:40:23 -08001292ThreadState Monitor::FetchState(const Thread* thread,
1293 /* out */ mirror::Object** monitor_object,
1294 /* out */ uint32_t* lock_owner_tid) {
1295 DCHECK(monitor_object != nullptr);
1296 DCHECK(lock_owner_tid != nullptr);
1297
1298 *monitor_object = nullptr;
1299 *lock_owner_tid = ThreadList::kInvalidThreadId;
1300
1301 ThreadState state = thread->GetState();
1302
1303 switch (state) {
1304 case kWaiting:
1305 case kTimedWaiting:
1306 case kSleeping:
1307 {
1308 Thread* self = Thread::Current();
1309 MutexLock mu(self, *thread->GetWaitMutex());
1310 Monitor* monitor = thread->GetWaitMonitor();
1311 if (monitor != nullptr) {
1312 *monitor_object = monitor->GetObject();
Ian Rogersd803bc72014-04-01 15:33:03 -07001313 }
1314 }
Andreas Gampef3ebcce2017-12-11 20:40:23 -08001315 break;
1316
1317 case kBlocked:
1318 case kWaitingForLockInflation:
1319 {
1320 mirror::Object* lock_object = thread->GetMonitorEnterObject();
1321 if (lock_object != nullptr) {
1322 if (kUseReadBarrier && Thread::Current()->GetIsGcMarking()) {
1323 // We may call Thread::Dump() in the middle of the CC thread flip and this thread's stack
1324 // may have not been flipped yet and "pretty_object" may be a from-space (stale) ref, in
1325 // which case the GetLockOwnerThreadId() call below will crash. So explicitly mark/forward
1326 // it here.
1327 lock_object = ReadBarrier::Mark(lock_object);
1328 }
1329 *monitor_object = lock_object;
1330 *lock_owner_tid = lock_object->GetLockOwnerThreadId();
1331 }
Ian Rogersd803bc72014-04-01 15:33:03 -07001332 }
Andreas Gampef3ebcce2017-12-11 20:40:23 -08001333 break;
1334
1335 default:
1336 break;
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001337 }
Andreas Gampef3ebcce2017-12-11 20:40:23 -08001338
1339 return state;
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001340}
1341
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001342mirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -08001343 // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
1344 // definition of contended that includes a monitor a thread is trying to enter...
Ian Rogersdd7624d2014-03-14 17:43:00 -07001345 mirror::Object* result = thread->GetMonitorEnterObject();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001346 if (result == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001347 // ...but also a monitor that the thread is waiting on.
Ian Rogersdd7624d2014-03-14 17:43:00 -07001348 MutexLock mu(Thread::Current(), *thread->GetWaitMutex());
1349 Monitor* monitor = thread->GetWaitMonitor();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001350 if (monitor != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001351 result = monitor->GetObject();
Elliott Hughesf9501702013-01-11 11:22:27 -08001352 }
1353 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001354 return result;
Elliott Hughesf9501702013-01-11 11:22:27 -08001355}
1356
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001357void Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
Andreas Gampe760172c2014-08-16 13:41:10 -07001358 void* callback_context, bool abort_on_failure) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001359 ArtMethod* m = stack_visitor->GetMethod();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001360 CHECK(m != nullptr);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001361
1362 // Native methods are an easy special case.
1363 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
1364 if (m->IsNative()) {
1365 if (m->IsSynchronized()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001366 mirror::Object* jni_this =
1367 stack_visitor->GetCurrentHandleScope(sizeof(void*))->GetReference(0);
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001368 callback(jni_this, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001369 }
1370 return;
1371 }
1372
jeffhao61f916c2012-10-25 17:48:51 -07001373 // Proxy methods should not be synchronized.
1374 if (m->IsProxyMethod()) {
1375 CHECK(!m->IsSynchronized());
1376 return;
1377 }
1378
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001379 // Is there any reason to believe there's any synchronization in this method?
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001380 CHECK(m->GetCodeItem() != nullptr) << m->PrettyMethod();
David Sehr0225f8e2018-01-31 08:52:24 +00001381 CodeItemDataAccessor accessor(m->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001382 if (accessor.TriesSize() == 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001383 return; // No "tries" implies no synchronization, so no held locks to report.
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001384 }
1385
Andreas Gampe760172c2014-08-16 13:41:10 -07001386 // Get the dex pc. If abort_on_failure is false, GetDexPc will not abort in the case it cannot
1387 // find the dex pc, and instead return kDexNoIndex. Then bail out, as it indicates we have an
1388 // inconsistent stack anyways.
1389 uint32_t dex_pc = stack_visitor->GetDexPc(abort_on_failure);
Andreas Gampee2abbc62017-09-15 11:59:26 -07001390 if (!abort_on_failure && dex_pc == dex::kDexNoIndex) {
David Sehr709b0702016-10-13 09:12:37 -07001391 LOG(ERROR) << "Could not find dex_pc for " << m->PrettyMethod();
Andreas Gampe760172c2014-08-16 13:41:10 -07001392 return;
1393 }
1394
Elliott Hughes80537bb2013-01-04 16:37:26 -08001395 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
1396 // the locks held in this stack frame.
Andreas Gampeaaf0d382017-11-27 14:10:21 -08001397 std::vector<verifier::MethodVerifier::DexLockInfo> monitor_enter_dex_pcs;
Andreas Gampe760172c2014-08-16 13:41:10 -07001398 verifier::MethodVerifier::FindLocksAtDexPc(m, dex_pc, &monitor_enter_dex_pcs);
Andreas Gampeaaf0d382017-11-27 14:10:21 -08001399 for (verifier::MethodVerifier::DexLockInfo& dex_lock_info : monitor_enter_dex_pcs) {
1400 // As a debug check, check that dex PC corresponds to a monitor-enter.
1401 if (kIsDebugBuild) {
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001402 const Instruction& monitor_enter_instruction = accessor.InstructionAt(dex_lock_info.dex_pc);
1403 CHECK_EQ(monitor_enter_instruction.Opcode(), Instruction::MONITOR_ENTER)
Andreas Gampeaaf0d382017-11-27 14:10:21 -08001404 << "expected monitor-enter @" << dex_lock_info.dex_pc << "; was "
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001405 << reinterpret_cast<const void*>(&monitor_enter_instruction);
Andreas Gampeaaf0d382017-11-27 14:10:21 -08001406 }
Elliott Hughes80537bb2013-01-04 16:37:26 -08001407
Andreas Gampeaaf0d382017-11-27 14:10:21 -08001408 // Iterate through the set of dex registers, as the compiler may not have held all of them
1409 // live.
1410 bool success = false;
1411 for (uint32_t dex_reg : dex_lock_info.dex_registers) {
1412 uint32_t value;
1413 success = stack_visitor->GetVReg(m, dex_reg, kReferenceVReg, &value);
1414 if (success) {
1415 mirror::Object* o = reinterpret_cast<mirror::Object*>(value);
1416 callback(o, callback_context);
1417 break;
1418 }
1419 }
1420 DCHECK(success) << "Failed to find/read reference for monitor-enter at dex pc "
1421 << dex_lock_info.dex_pc
1422 << " in method "
1423 << m->PrettyMethod();
1424 if (!success) {
1425 LOG(WARNING) << "Had a lock reported for dex pc " << dex_lock_info.dex_pc
1426 << " but was not able to fetch a corresponding object!";
1427 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001428 }
1429}
1430
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001431bool Monitor::IsValidLockWord(LockWord lock_word) {
1432 switch (lock_word.GetState()) {
1433 case LockWord::kUnlocked:
1434 // Nothing to check.
1435 return true;
1436 case LockWord::kThinLocked:
1437 // Basic sanity check of owner.
1438 return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
1439 case LockWord::kFatLocked: {
1440 // Check the monitor appears in the monitor list.
1441 Monitor* mon = lock_word.FatLockMonitor();
1442 MonitorList* list = Runtime::Current()->GetMonitorList();
1443 MutexLock mu(Thread::Current(), list->monitor_list_lock_);
1444 for (Monitor* list_mon : list->list_) {
1445 if (mon == list_mon) {
1446 return true; // Found our monitor.
1447 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001448 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001449 return false; // Fail - unowned monitor in an object.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001450 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001451 case LockWord::kHashCode:
1452 return true;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001453 default:
1454 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001455 UNREACHABLE();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001456 }
1457}
1458
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001459bool Monitor::IsLocked() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001460 MutexLock mu(Thread::Current(), monitor_lock_);
1461 return owner_ != nullptr;
1462}
1463
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -07001464void Monitor::TranslateLocation(ArtMethod* method,
1465 uint32_t dex_pc,
1466 const char** source_file,
1467 int32_t* line_number) {
jeffhao33dc7712011-11-09 17:54:24 -08001468 // If method is null, location is unknown
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001469 if (method == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001470 *source_file = "";
1471 *line_number = 0;
jeffhao33dc7712011-11-09 17:54:24 -08001472 return;
1473 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001474 *source_file = method->GetDeclaringClassSourceFile();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001475 if (*source_file == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001476 *source_file = "";
Elliott Hughes12c51e32012-01-17 20:25:05 -08001477 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001478 *line_number = method->GetLineNumFromDexPC(dex_pc);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001479}
1480
1481uint32_t Monitor::GetOwnerThreadId() {
1482 MutexLock mu(Thread::Current(), monitor_lock_);
1483 Thread* owner = owner_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001484 if (owner != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001485 return owner->GetThreadId();
1486 } else {
1487 return ThreadList::kInvalidThreadId;
1488 }
jeffhao33dc7712011-11-09 17:54:24 -08001489}
1490
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001491MonitorList::MonitorList()
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001492 : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock", kMonitorListLock),
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001493 monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001494}
1495
1496MonitorList::~MonitorList() {
Andreas Gampe74240812014-04-17 10:35:09 -07001497 Thread* self = Thread::Current();
1498 MutexLock mu(self, monitor_list_lock_);
1499 // Release all monitors to the pool.
1500 // TODO: Is it an invariant that *all* open monitors are in the list? Then we could
1501 // clear faster in the pool.
1502 MonitorPool::ReleaseMonitors(self, &list_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001503}
1504
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001505void MonitorList::DisallowNewMonitors() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001506 CHECK(!kUseReadBarrier);
Ian Rogers50b35e22012-10-04 10:09:15 -07001507 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001508 allow_new_monitors_ = false;
1509}
1510
1511void MonitorList::AllowNewMonitors() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001512 CHECK(!kUseReadBarrier);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001513 Thread* self = Thread::Current();
1514 MutexLock mu(self, monitor_list_lock_);
1515 allow_new_monitors_ = true;
1516 monitor_add_condition_.Broadcast(self);
1517}
1518
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001519void MonitorList::BroadcastForNewMonitors() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001520 Thread* self = Thread::Current();
1521 MutexLock mu(self, monitor_list_lock_);
1522 monitor_add_condition_.Broadcast(self);
1523}
1524
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001525void MonitorList::Add(Monitor* m) {
1526 Thread* self = Thread::Current();
1527 MutexLock mu(self, monitor_list_lock_);
Hiroshi Yamauchif1c6f872017-01-06 12:23:47 -08001528 // CMS needs this to block for concurrent reference processing because an object allocated during
1529 // the GC won't be marked and concurrent reference processing would incorrectly clear the JNI weak
1530 // ref. But CC (kUseReadBarrier == true) doesn't because of the to-space invariant.
1531 while (!kUseReadBarrier && UNLIKELY(!allow_new_monitors_)) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -07001532 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
1533 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -08001534 self->CheckEmptyCheckpointFromWeakRefAccess(&monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001535 monitor_add_condition_.WaitHoldingLocks(self);
1536 }
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001537 list_.push_front(m);
1538}
1539
Mathieu Chartier97509952015-07-13 14:35:43 -07001540void MonitorList::SweepMonitorList(IsMarkedVisitor* visitor) {
Andreas Gampe74240812014-04-17 10:35:09 -07001541 Thread* self = Thread::Current();
1542 MutexLock mu(self, monitor_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001543 for (auto it = list_.begin(); it != list_.end(); ) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001544 Monitor* m = *it;
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001545 // Disable the read barrier in GetObject() as this is called by GC.
1546 mirror::Object* obj = m->GetObject<kWithoutReadBarrier>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001547 // The object of a monitor can be null if we have deflated it.
Mathieu Chartier97509952015-07-13 14:35:43 -07001548 mirror::Object* new_obj = obj != nullptr ? visitor->IsMarked(obj) : nullptr;
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001549 if (new_obj == nullptr) {
1550 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001551 << obj;
Andreas Gampe74240812014-04-17 10:35:09 -07001552 MonitorPool::ReleaseMonitor(self, m);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001553 it = list_.erase(it);
1554 } else {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001555 m->SetObject(new_obj);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001556 ++it;
1557 }
1558 }
1559}
1560
Hans Boehm6fe97e02016-05-04 18:35:57 -07001561size_t MonitorList::Size() {
1562 Thread* self = Thread::Current();
1563 MutexLock mu(self, monitor_list_lock_);
1564 return list_.size();
1565}
1566
Mathieu Chartier97509952015-07-13 14:35:43 -07001567class MonitorDeflateVisitor : public IsMarkedVisitor {
1568 public:
1569 MonitorDeflateVisitor() : self_(Thread::Current()), deflate_count_(0) {}
1570
1571 virtual mirror::Object* IsMarked(mirror::Object* object) OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001572 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001573 if (Monitor::Deflate(self_, object)) {
1574 DCHECK_NE(object->GetLockWord(true).GetState(), LockWord::kFatLocked);
1575 ++deflate_count_;
1576 // If we deflated, return null so that the monitor gets removed from the array.
1577 return nullptr;
1578 }
1579 return object; // Monitor was not deflated.
1580 }
1581
1582 Thread* const self_;
1583 size_t deflate_count_;
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001584};
1585
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001586size_t MonitorList::DeflateMonitors() {
Mathieu Chartier97509952015-07-13 14:35:43 -07001587 MonitorDeflateVisitor visitor;
1588 Locks::mutator_lock_->AssertExclusiveHeld(visitor.self_);
1589 SweepMonitorList(&visitor);
1590 return visitor.deflate_count_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001591}
1592
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001593MonitorInfo::MonitorInfo(mirror::Object* obj) : owner_(nullptr), entry_count_(0) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001594 DCHECK(obj != nullptr);
1595 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001596 switch (lock_word.GetState()) {
1597 case LockWord::kUnlocked:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001598 // Fall-through.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001599 case LockWord::kForwardingAddress:
1600 // Fall-through.
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001601 case LockWord::kHashCode:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001602 break;
1603 case LockWord::kThinLocked:
1604 owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
Alex Lightce568642017-09-05 16:54:25 -07001605 DCHECK(owner_ != nullptr) << "Thin-locked without owner!";
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001606 entry_count_ = 1 + lock_word.ThinLockCount();
1607 // Thin locks have no waiters.
1608 break;
1609 case LockWord::kFatLocked: {
1610 Monitor* mon = lock_word.FatLockMonitor();
1611 owner_ = mon->owner_;
Alex Lightce568642017-09-05 16:54:25 -07001612 // Here it is okay for the owner to be null since we don't reset the LockWord back to
1613 // kUnlocked until we get a GC. In cases where this hasn't happened yet we will have a fat
1614 // lock without an owner.
1615 if (owner_ != nullptr) {
1616 entry_count_ = 1 + mon->lock_count_;
1617 } else {
1618 DCHECK_EQ(mon->lock_count_, 0) << "Monitor is fat-locked without any owner!";
1619 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001620 for (Thread* waiter = mon->wait_set_; waiter != nullptr; waiter = waiter->GetWaitNext()) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001621 waiters_.push_back(waiter);
1622 }
1623 break;
Elliott Hughesf327e072013-01-09 16:01:26 -08001624 }
1625 }
1626}
1627
Elliott Hughes5f791332011-09-15 17:45:30 -07001628} // namespace art