blob: 051e015d804eabaae1214c11808e3a525adff949 [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"
Elliott Hughes76b61672012-12-12 17:47:30 -080024#include "base/mutex.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080025#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080026#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010027#include "base/time_utils.h"
jeffhao33dc7712011-11-09 17:54:24 -080028#include "class_linker.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070029#include "dex_file-inl.h"
Sebastien Hertz0f7c9332015-11-05 15:57:30 +010030#include "dex_instruction-inl.h"
Ian Rogersd9c4fc92013-10-01 19:45:43 -070031#include "lock_word-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070032#include "mirror/class-inl.h"
Ian Rogers05f30572013-02-20 12:13:11 -080033#include "mirror/object-inl.h"
Andreas Gampe5d08fcc2017-06-05 17:56:46 -070034#include "object_callbacks.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070035#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070036#include "stack.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070037#include "thread.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070038#include "thread_list.h"
Elliott Hughes08fc03a2012-06-26 17:34:00 -070039#include "verifier/method_verifier.h"
Elliott Hughes044288f2012-06-25 14:46:39 -070040#include "well_known_classes.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070041
42namespace art {
43
Andreas Gampe46ee31b2016-12-14 10:11:49 -080044using android::base::StringPrintf;
45
Mathieu Chartierb9001ab2014-10-03 13:28:46 -070046static constexpr uint64_t kLongWaitMs = 100;
47
Elliott Hughes5f791332011-09-15 17:45:30 -070048/*
Ian Rogersd9c4fc92013-10-01 19:45:43 -070049 * Every Object has a monitor associated with it, but not every Object is actually locked. Even
50 * the ones that are locked do not need a full-fledged monitor until a) there is actual contention
51 * or b) wait() is called on the Object.
Elliott Hughes5f791332011-09-15 17:45:30 -070052 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070053 * For Android, we have implemented a scheme similar to the one described in Bacon et al.'s
54 * "Thin locks: featherweight synchronization for Java" (ACM 1998). Things are even easier for us,
55 * though, because we have a full 32 bits to work with.
Elliott Hughes5f791332011-09-15 17:45:30 -070056 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070057 * The two states of an Object's lock are referred to as "thin" and "fat". A lock may transition
58 * from the "thin" state to the "fat" state and this transition is referred to as inflation. Once
59 * a lock has been inflated it remains in the "fat" state indefinitely.
Elliott Hughes5f791332011-09-15 17:45:30 -070060 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070061 * The lock value itself is stored in mirror::Object::monitor_ and the representation is described
62 * in the LockWord value type.
Elliott Hughes54e7df12011-09-16 11:47:04 -070063 *
Elliott Hughes5f791332011-09-15 17:45:30 -070064 * Monitors provide:
65 * - mutually exclusive access to resources
66 * - a way for multiple threads to wait for notification
67 *
68 * In effect, they fill the role of both mutexes and condition variables.
69 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070070 * Only one thread can own the monitor at any time. There may be several threads waiting on it
71 * (the wait call unlocks it). One or more waiting threads may be getting interrupted or notified
72 * at any given time.
Elliott Hughes5f791332011-09-15 17:45:30 -070073 */
Elliott Hughes54e7df12011-09-16 11:47:04 -070074
Elliott Hughesfc861622011-10-17 17:57:47 -070075uint32_t Monitor::lock_profiling_threshold_ = 0;
Andreas Gamped0210e52017-06-23 13:38:09 -070076uint32_t Monitor::stack_dump_lock_profiling_threshold_ = 0;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070077
Andreas Gamped0210e52017-06-23 13:38:09 -070078void Monitor::Init(uint32_t lock_profiling_threshold,
79 uint32_t stack_dump_lock_profiling_threshold) {
Elliott Hughesfc861622011-10-17 17:57:47 -070080 lock_profiling_threshold_ = lock_profiling_threshold;
Andreas Gamped0210e52017-06-23 13:38:09 -070081 stack_dump_lock_profiling_threshold_ = stack_dump_lock_profiling_threshold;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070082}
83
Ian Rogersef7d42f2014-01-06 12:55:46 -080084Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code)
Ian Rogers00f7d0e2012-07-19 15:28:27 -070085 : monitor_lock_("a monitor lock", kMonitorLock),
Ian Rogersd9c4fc92013-10-01 19:45:43 -070086 monitor_contenders_("monitor contenders", monitor_lock_),
Mathieu Chartier46bc7782013-11-12 17:03:02 -080087 num_waiters_(0),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070088 owner_(owner),
Elliott Hughes5f791332011-09-15 17:45:30 -070089 lock_count_(0),
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070090 obj_(GcRoot<mirror::Object>(obj)),
Mathieu Chartier2cebb242015-04-21 16:50:40 -070091 wait_set_(nullptr),
Mathieu Chartierad2541a2013-10-25 10:05:23 -070092 hash_code_(hash_code),
Mathieu Chartier2cebb242015-04-21 16:50:40 -070093 locking_method_(nullptr),
Ian Rogersef7d42f2014-01-06 12:55:46 -080094 locking_dex_pc_(0),
Andreas Gampe74240812014-04-17 10:35:09 -070095 monitor_id_(MonitorPool::ComputeMonitorId(this, self)) {
96#ifdef __LP64__
97 DCHECK(false) << "Should not be reached in 64b";
98 next_free_ = nullptr;
99#endif
100 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
101 // with the owner unlocking the thin-lock.
102 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
103 // The identity hash code is set for the life time of the monitor.
104}
105
106Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code,
107 MonitorId id)
108 : monitor_lock_("a monitor lock", kMonitorLock),
109 monitor_contenders_("monitor contenders", monitor_lock_),
110 num_waiters_(0),
111 owner_(owner),
112 lock_count_(0),
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700113 obj_(GcRoot<mirror::Object>(obj)),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700114 wait_set_(nullptr),
Andreas Gampe74240812014-04-17 10:35:09 -0700115 hash_code_(hash_code),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700116 locking_method_(nullptr),
Andreas Gampe74240812014-04-17 10:35:09 -0700117 locking_dex_pc_(0),
118 monitor_id_(id) {
119#ifdef __LP64__
120 next_free_ = nullptr;
121#endif
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700122 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
123 // with the owner unlocking the thin-lock.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800124 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700125 // The identity hash code is set for the life time of the monitor.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700126}
127
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700128int32_t Monitor::GetHashCode() {
129 while (!HasHashCode()) {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700130 if (hash_code_.CompareExchangeWeakRelaxed(0, mirror::Object::GenerateIdentityHashCode())) {
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700131 break;
132 }
133 }
134 DCHECK(HasHashCode());
Ian Rogers3e5cf302014-05-20 16:40:37 -0700135 return hash_code_.LoadRelaxed();
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700136}
137
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700138bool Monitor::Install(Thread* self) {
139 MutexLock mu(self, monitor_lock_); // Uncontended mutex acquisition as monitor isn't yet public.
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700140 CHECK(owner_ == nullptr || owner_ == self || owner_->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700141 // Propagate the lock state.
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700142 LockWord lw(GetObject()->GetLockWord(false));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700143 switch (lw.GetState()) {
144 case LockWord::kThinLocked: {
145 CHECK_EQ(owner_->GetThreadId(), lw.ThinLockOwner());
146 lock_count_ = lw.ThinLockCount();
147 break;
148 }
149 case LockWord::kHashCode: {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700150 CHECK_EQ(hash_code_.LoadRelaxed(), static_cast<int32_t>(lw.GetHashCode()));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700151 break;
152 }
153 case LockWord::kFatLocked: {
154 // The owner_ is suspended but another thread beat us to install a monitor.
155 return false;
156 }
157 case LockWord::kUnlocked: {
158 LOG(FATAL) << "Inflating unlocked lock word";
159 break;
160 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700161 default: {
162 LOG(FATAL) << "Invalid monitor state " << lw.GetState();
163 return false;
164 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700165 }
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700166 LockWord fat(this, lw.GCState());
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700167 // Publish the updated lock word, which may race with other threads.
Hans Boehmb3da36c2016-12-15 13:12:59 -0800168 bool success = GetObject()->CasLockWordWeakRelease(lw, fat);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700169 // Lock profiling.
Mathieu Chartier9728f912013-10-30 09:45:13 -0700170 if (success && owner_ != nullptr && lock_profiling_threshold_ != 0) {
Andreas Gampe6ec8ebd2014-07-25 13:36:56 -0700171 // Do not abort on dex pc errors. This can easily happen when we want to dump a stack trace on
172 // abort.
173 locking_method_ = owner_->GetCurrentMethod(&locking_dex_pc_, false);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700174 }
175 return success;
Elliott Hughes5f791332011-09-15 17:45:30 -0700176}
177
178Monitor::~Monitor() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700179 // Deflated monitors have a null object.
Elliott Hughes5f791332011-09-15 17:45:30 -0700180}
181
Elliott Hughes5f791332011-09-15 17:45:30 -0700182void Monitor::AppendToWaitSet(Thread* thread) {
183 DCHECK(owner_ == Thread::Current());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700184 DCHECK(thread != nullptr);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700185 DCHECK(thread->GetWaitNext() == nullptr) << thread->GetWaitNext();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700186 if (wait_set_ == nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700187 wait_set_ = thread;
188 return;
189 }
190
191 // push_back.
192 Thread* t = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700193 while (t->GetWaitNext() != nullptr) {
194 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700195 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700196 t->SetWaitNext(thread);
Elliott Hughes5f791332011-09-15 17:45:30 -0700197}
198
Elliott Hughes5f791332011-09-15 17:45:30 -0700199void Monitor::RemoveFromWaitSet(Thread *thread) {
200 DCHECK(owner_ == Thread::Current());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700201 DCHECK(thread != nullptr);
202 if (wait_set_ == nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700203 return;
204 }
205 if (wait_set_ == thread) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700206 wait_set_ = thread->GetWaitNext();
207 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700208 return;
209 }
210
211 Thread* t = wait_set_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700212 while (t->GetWaitNext() != nullptr) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700213 if (t->GetWaitNext() == thread) {
214 t->SetWaitNext(thread->GetWaitNext());
215 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700216 return;
217 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700218 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700219 }
220}
221
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700222void Monitor::SetObject(mirror::Object* object) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700223 obj_ = GcRoot<mirror::Object>(object);
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700224}
225
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700226// Note: Adapted from CurrentMethodVisitor in thread.cc. We must not resolve here.
227
228struct NthCallerWithDexPcVisitor FINAL : public StackVisitor {
229 explicit NthCallerWithDexPcVisitor(Thread* thread, size_t frame)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700230 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +0100231 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700232 method_(nullptr),
233 dex_pc_(0),
234 current_frame_number_(0),
235 wanted_frame_number_(frame) {}
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700236 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700237 ArtMethod* m = GetMethod();
238 if (m == nullptr || m->IsRuntimeMethod()) {
239 // Runtime method, upcall, or resolution issue. Skip.
240 return true;
241 }
242
243 // Is this the requested frame?
244 if (current_frame_number_ == wanted_frame_number_) {
245 method_ = m;
246 dex_pc_ = GetDexPc(false /* abort_on_error*/);
247 return false;
248 }
249
250 // Look for more.
251 current_frame_number_++;
252 return true;
253 }
254
255 ArtMethod* method_;
256 uint32_t dex_pc_;
257
258 private:
259 size_t current_frame_number_;
260 const size_t wanted_frame_number_;
261};
262
263// This function is inlined and just helps to not have the VLOG and ATRACE check at all the
264// potential tracing points.
265void Monitor::AtraceMonitorLock(Thread* self, mirror::Object* obj, bool is_wait) {
266 if (UNLIKELY(VLOG_IS_ON(systrace_lock_logging) && ATRACE_ENABLED())) {
267 AtraceMonitorLockImpl(self, obj, is_wait);
268 }
269}
270
271void Monitor::AtraceMonitorLockImpl(Thread* self, mirror::Object* obj, bool is_wait) {
272 // Wait() requires a deeper call stack to be useful. Otherwise you'll see "Waiting at
273 // Object.java". Assume that we'll wait a nontrivial amount, so it's OK to do a longer
274 // stack walk than if !is_wait.
275 NthCallerWithDexPcVisitor visitor(self, is_wait ? 1U : 0U);
276 visitor.WalkStack(false);
277 const char* prefix = is_wait ? "Waiting on " : "Locking ";
278
279 const char* filename;
280 int32_t line_number;
281 TranslateLocation(visitor.method_, visitor.dex_pc_, &filename, &line_number);
282
283 // It would be nice to have a stable "ID" for the object here. However, the only stable thing
284 // would be the identity hashcode. But we cannot use IdentityHashcode here: For one, there are
285 // times when it is unsafe to make that call (see stack dumping for an explanation). More
286 // importantly, we would have to give up on thin-locking when adding systrace locks, as the
287 // identity hashcode is stored in the lockword normally (so can't be used with thin-locks).
288 //
289 // Because of thin-locks we also cannot use the monitor id (as there is no monitor). Monitor ids
290 // also do not have to be stable, as the monitor may be deflated.
291 std::string tmp = StringPrintf("%s %d at %s:%d",
292 prefix,
293 (obj == nullptr ? -1 : static_cast<int32_t>(reinterpret_cast<uintptr_t>(obj))),
294 (filename != nullptr ? filename : "null"),
295 line_number);
296 ATRACE_BEGIN(tmp.c_str());
297}
298
299void Monitor::AtraceMonitorUnlock() {
300 if (UNLIKELY(VLOG_IS_ON(systrace_lock_logging))) {
301 ATRACE_END();
302 }
303}
304
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700305std::string Monitor::PrettyContentionInfo(const std::string& owner_name,
306 pid_t owner_tid,
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700307 ArtMethod* owners_method,
308 uint32_t owners_dex_pc,
309 size_t num_waiters) {
Hiroshi Yamauchi71cd68d2017-01-25 18:28:12 -0800310 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700311 const char* owners_filename;
Goran Jakovljevic49c882b2016-04-19 10:27:21 +0200312 int32_t owners_line_number = 0;
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700313 if (owners_method != nullptr) {
314 TranslateLocation(owners_method, owners_dex_pc, &owners_filename, &owners_line_number);
315 }
316 std::ostringstream oss;
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700317 oss << "monitor contention with owner " << owner_name << " (" << owner_tid << ")";
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700318 if (owners_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700319 oss << " at " << owners_method->PrettyMethod();
Mathieu Chartier36891fe2016-04-28 17:21:08 -0700320 oss << "(" << owners_filename << ":" << owners_line_number << ")";
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700321 }
322 oss << " waiters=" << num_waiters;
323 return oss.str();
324}
325
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700326bool Monitor::TryLockLocked(Thread* self) {
327 if (owner_ == nullptr) { // Unowned.
328 owner_ = self;
329 CHECK_EQ(lock_count_, 0);
330 // When debugging, save the current monitor holder for future
331 // acquisition failures to use in sampled logging.
332 if (lock_profiling_threshold_ != 0) {
333 locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
334 }
335 } else if (owner_ == self) { // Recursive.
336 lock_count_++;
337 } else {
338 return false;
339 }
340 AtraceMonitorLock(self, GetObject(), false /* is_wait */);
341 return true;
342}
343
344bool Monitor::TryLock(Thread* self) {
345 MutexLock mu(self, monitor_lock_);
346 return TryLockLocked(self);
347}
348
Alex Light77fee872017-09-05 14:51:49 -0700349// Asserts that a mutex isn't held when the class comes into and out of scope.
350class ScopedAssertNotHeld {
351 public:
352 ScopedAssertNotHeld(Thread* self, Mutex& mu) : self_(self), mu_(mu) {
353 mu_.AssertNotHeld(self_);
354 }
355
356 ~ScopedAssertNotHeld() {
357 mu_.AssertNotHeld(self_);
358 }
359
360 private:
361 Thread* const self_;
362 Mutex& mu_;
363 DISALLOW_COPY_AND_ASSIGN(ScopedAssertNotHeld);
364};
365
366template <LockReason reason>
Elliott Hughes5f791332011-09-15 17:45:30 -0700367void Monitor::Lock(Thread* self) {
Alex Light77fee872017-09-05 14:51:49 -0700368 ScopedAssertNotHeld sanh(self, monitor_lock_);
369 bool called_monitors_callback = false;
370 monitor_lock_.Lock(self);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700371 while (true) {
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700372 if (TryLockLocked(self)) {
Alex Light77fee872017-09-05 14:51:49 -0700373 break;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700374 }
375 // Contended.
376 const bool log_contention = (lock_profiling_threshold_ != 0);
Xin Guanb894a192014-08-22 11:55:37 -0500377 uint64_t wait_start_ms = log_contention ? MilliTime() : 0;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700378 ArtMethod* owners_method = locking_method_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700379 uint32_t owners_dex_pc = locking_dex_pc_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700380 // Do this before releasing the lock so that we don't get deflated.
Mathieu Chartierb9001ab2014-10-03 13:28:46 -0700381 size_t num_waiters = num_waiters_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700382 ++num_waiters_;
Andreas Gampe2702d562017-02-06 09:48:00 -0800383
384 // If systrace logging is enabled, first look at the lock owner. Acquiring the monitor's
385 // lock and then re-acquiring the mutator lock can deadlock.
386 bool started_trace = false;
387 if (ATRACE_ENABLED()) {
388 if (owner_ != nullptr) { // Did the owner_ give the lock up?
389 std::ostringstream oss;
390 std::string name;
391 owner_->GetThreadName(name);
392 oss << PrettyContentionInfo(name,
393 owner_->GetTid(),
394 owners_method,
395 owners_dex_pc,
396 num_waiters);
397 // Add info for contending thread.
398 uint32_t pc;
399 ArtMethod* m = self->GetCurrentMethod(&pc);
400 const char* filename;
401 int32_t line_number;
402 TranslateLocation(m, pc, &filename, &line_number);
403 oss << " blocking from "
404 << ArtMethod::PrettyMethod(m) << "(" << (filename != nullptr ? filename : "null")
405 << ":" << line_number << ")";
406 ATRACE_BEGIN(oss.str().c_str());
407 started_trace = true;
408 }
409 }
410
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700411 monitor_lock_.Unlock(self); // Let go of locks in order.
Alex Light77fee872017-09-05 14:51:49 -0700412 // Call the contended locking cb once and only once. Also only call it if we are locking for
413 // the first time, not during a Wait wakeup.
414 if (reason == LockReason::kForLock && !called_monitors_callback) {
415 called_monitors_callback = true;
416 Runtime::Current()->GetRuntimeCallbacks()->MonitorContendedLocking(this);
417 }
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700418 self->SetMonitorEnterObject(GetObject());
Elliott Hughes5f791332011-09-15 17:45:30 -0700419 {
Hiroshi Yamauchi71cd68d2017-01-25 18:28:12 -0800420 ScopedThreadSuspension tsc(self, kBlocked); // Change to blocked and give up mutator_lock_.
Andreas Gampe2702d562017-02-06 09:48:00 -0800421 uint32_t original_owner_thread_id = 0u;
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700422 {
423 // Reacquire monitor_lock_ without mutator_lock_ for Wait.
424 MutexLock mu2(self, monitor_lock_);
425 if (owner_ != nullptr) { // Did the owner_ give the lock up?
426 original_owner_thread_id = owner_->GetThreadId();
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700427 monitor_contenders_.Wait(self); // Still contended so wait.
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800428 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700429 }
430 if (original_owner_thread_id != 0u) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700431 // Woken from contention.
432 if (log_contention) {
Andreas Gampe111b1092017-06-22 20:28:23 -0700433 uint64_t wait_ms = MilliTime() - wait_start_ms;
434 uint32_t sample_percent;
435 if (wait_ms >= lock_profiling_threshold_) {
436 sample_percent = 100;
437 } else {
438 sample_percent = 100 * wait_ms / lock_profiling_threshold_;
439 }
440 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
441 // Reacquire mutator_lock_ for logging.
442 ScopedObjectAccess soa(self);
Andreas Gampe111b1092017-06-22 20:28:23 -0700443
Andreas Gamped0210e52017-06-23 13:38:09 -0700444 bool owner_alive = false;
445 pid_t original_owner_tid = 0;
446 std::string original_owner_name;
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700447
Andreas Gamped0210e52017-06-23 13:38:09 -0700448 const bool should_dump_stacks = stack_dump_lock_profiling_threshold_ > 0 &&
449 wait_ms > stack_dump_lock_profiling_threshold_;
450 std::string owner_stack_dump;
Andreas Gampe111b1092017-06-22 20:28:23 -0700451
Andreas Gamped0210e52017-06-23 13:38:09 -0700452 // Acquire thread-list lock to find thread and keep it from dying until we've got all
453 // the info we need.
454 {
455 MutexLock mu2(Thread::Current(), *Locks::thread_list_lock_);
456
457 // Re-find the owner in case the thread got killed.
458 Thread* original_owner = Runtime::Current()->GetThreadList()->FindThreadByThreadId(
459 original_owner_thread_id);
460
461 if (original_owner != nullptr) {
462 owner_alive = true;
463 original_owner_tid = original_owner->GetTid();
464 original_owner->GetThreadName(original_owner_name);
465
466 if (should_dump_stacks) {
467 // Very long contention. Dump stacks.
468 struct CollectStackTrace : public Closure {
469 void Run(art::Thread* thread) OVERRIDE
470 REQUIRES_SHARED(art::Locks::mutator_lock_) {
471 thread->DumpJavaStack(oss);
472 }
473
474 std::ostringstream oss;
475 };
476 CollectStackTrace owner_trace;
477 original_owner->RequestSynchronousCheckpoint(&owner_trace);
478 owner_stack_dump = owner_trace.oss.str();
479 }
480 }
481 // This is all the data we need. Now drop the thread-list lock, it's OK for the
482 // owner to go away now.
483 }
484
485 // If we found the owner (and thus have owner data), go and log now.
486 if (owner_alive) {
487 // Give the detailed traces for really long contention.
488 if (should_dump_stacks) {
489 // This must be here (and not above) because we cannot hold the thread-list lock
490 // while running the checkpoint.
491 std::ostringstream self_trace_oss;
492 self->DumpJavaStack(self_trace_oss);
493
494 uint32_t pc;
495 ArtMethod* m = self->GetCurrentMethod(&pc);
496
497 LOG(WARNING) << "Long "
498 << PrettyContentionInfo(original_owner_name,
499 original_owner_tid,
500 owners_method,
501 owners_dex_pc,
502 num_waiters)
503 << " in " << ArtMethod::PrettyMethod(m) << " for "
504 << PrettyDuration(MsToNs(wait_ms)) << "\n"
505 << "Current owner stack:\n" << owner_stack_dump
506 << "Contender stack:\n" << self_trace_oss.str();
507 } else if (wait_ms > kLongWaitMs && owners_method != nullptr) {
Mathieu Chartier36891fe2016-04-28 17:21:08 -0700508 uint32_t pc;
509 ArtMethod* m = self->GetCurrentMethod(&pc);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700510 // TODO: We should maybe check that original_owner is still a live thread.
511 LOG(WARNING) << "Long "
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700512 << PrettyContentionInfo(original_owner_name,
513 original_owner_tid,
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700514 owners_method,
515 owners_dex_pc,
516 num_waiters)
David Sehr709b0702016-10-13 09:12:37 -0700517 << " in " << ArtMethod::PrettyMethod(m) << " for "
518 << PrettyDuration(MsToNs(wait_ms));
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700519 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700520 LogContentionEvent(self,
Alex Light77fee872017-09-05 14:51:49 -0700521 wait_ms,
522 sample_percent,
523 owners_method,
524 owners_dex_pc);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700525 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700526 }
527 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700528 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700529 }
Andreas Gampe2702d562017-02-06 09:48:00 -0800530 if (started_trace) {
531 ATRACE_END();
532 }
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700533 self->SetMonitorEnterObject(nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700534 monitor_lock_.Lock(self); // Reacquire locks in order.
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700535 --num_waiters_;
Elliott Hughesfc861622011-10-17 17:57:47 -0700536 }
Alex Light77fee872017-09-05 14:51:49 -0700537 monitor_lock_.Unlock(self);
538 // We need to pair this with a single contended locking call. NB we match the RI behavior and call
539 // this even if MonitorEnter failed.
540 if (called_monitors_callback) {
541 CHECK(reason == LockReason::kForLock);
542 Runtime::Current()->GetRuntimeCallbacks()->MonitorContendedLocked(this);
543 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700544}
545
Alex Light77fee872017-09-05 14:51:49 -0700546template void Monitor::Lock<LockReason::kForLock>(Thread* self);
547template void Monitor::Lock<LockReason::kForWait>(Thread* self);
548
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800549static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
550 __attribute__((format(printf, 1, 2)));
551
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700552static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700553 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800554 va_list args;
555 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800556 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000557 self->ThrowNewExceptionV("Ljava/lang/IllegalMonitorStateException;", fmt, args);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700558 if (!Runtime::Current()->IsStarted() || VLOG_IS_ON(monitor)) {
Brian Carlstrom64277f32012-03-26 23:53:34 -0700559 std::ostringstream ss;
Ian Rogers62d6c772013-02-27 08:32:07 -0800560 self->Dump(ss);
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700561 LOG(Runtime::Current()->IsStarted() ? ::android::base::INFO : ::android::base::ERROR)
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000562 << self->GetException()->Dump() << "\n" << ss.str();
Brian Carlstrom64277f32012-03-26 23:53:34 -0700563 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800564 va_end(args);
565}
566
Elliott Hughesd4237412012-02-21 11:24:45 -0800567static std::string ThreadToString(Thread* thread) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700568 if (thread == nullptr) {
569 return "nullptr";
Elliott Hughesd4237412012-02-21 11:24:45 -0800570 }
571 std::ostringstream oss;
572 // TODO: alternatively, we could just return the thread's name.
573 oss << *thread;
574 return oss.str();
575}
576
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700577void Monitor::FailedUnlock(mirror::Object* o,
578 uint32_t expected_owner_thread_id,
579 uint32_t found_owner_thread_id,
Elliott Hughesffb465f2012-03-01 18:46:05 -0800580 Monitor* monitor) {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700581 // Acquire thread list lock so threads won't disappear from under us.
Elliott Hughesffb465f2012-03-01 18:46:05 -0800582 std::string current_owner_string;
583 std::string expected_owner_string;
584 std::string found_owner_string;
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700585 uint32_t current_owner_thread_id = 0u;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800586 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700587 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700588 ThreadList* const thread_list = Runtime::Current()->GetThreadList();
589 Thread* expected_owner = thread_list->FindThreadByThreadId(expected_owner_thread_id);
590 Thread* found_owner = thread_list->FindThreadByThreadId(found_owner_thread_id);
591
Elliott Hughesffb465f2012-03-01 18:46:05 -0800592 // Re-read owner now that we hold lock.
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700593 Thread* current_owner = (monitor != nullptr) ? monitor->GetOwner() : nullptr;
594 if (current_owner != nullptr) {
595 current_owner_thread_id = current_owner->GetThreadId();
596 }
Elliott Hughesffb465f2012-03-01 18:46:05 -0800597 // Get short descriptions of the threads involved.
598 current_owner_string = ThreadToString(current_owner);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700599 expected_owner_string = expected_owner != nullptr ? ThreadToString(expected_owner) : "unnamed";
600 found_owner_string = found_owner != nullptr ? ThreadToString(found_owner) : "unnamed";
Elliott Hughesffb465f2012-03-01 18:46:05 -0800601 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700602
603 if (current_owner_thread_id == 0u) {
604 if (found_owner_thread_id == 0u) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800605 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
606 " on thread '%s'",
David Sehr709b0702016-10-13 09:12:37 -0700607 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800608 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800609 } else {
610 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800611 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
612 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800613 found_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700614 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800615 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800616 }
617 } else {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700618 if (found_owner_thread_id == 0u) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800619 // Race: originally there was no owner, there is now
620 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
621 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800622 current_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700623 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800624 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800625 } else {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700626 if (found_owner_thread_id != current_owner_thread_id) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800627 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800628 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
629 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800630 found_owner_string.c_str(),
631 current_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700632 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800633 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800634 } else {
635 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
636 " on thread '%s",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800637 current_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700638 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800639 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800640 }
641 }
642 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700643}
644
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700645bool Monitor::Unlock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700646 DCHECK(self != nullptr);
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700647 uint32_t owner_thread_id = 0u;
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700648 {
649 MutexLock mu(self, monitor_lock_);
650 Thread* owner = owner_;
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700651 if (owner != nullptr) {
652 owner_thread_id = owner->GetThreadId();
653 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700654 if (owner == self) {
655 // We own the monitor, so nobody else can be in here.
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700656 AtraceMonitorUnlock();
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700657 if (lock_count_ == 0) {
658 owner_ = nullptr;
659 locking_method_ = nullptr;
660 locking_dex_pc_ = 0;
661 // Wake a contender.
662 monitor_contenders_.Signal(self);
663 } else {
664 --lock_count_;
665 }
666 return true;
Elliott Hughes5f791332011-09-15 17:45:30 -0700667 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700668 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700669 // We don't own this, so we're not allowed to unlock it.
670 // The JNI spec says that we should throw IllegalMonitorStateException in this case.
671 FailedUnlock(GetObject(), self->GetThreadId(), owner_thread_id, this);
672 return false;
Elliott Hughes5f791332011-09-15 17:45:30 -0700673}
674
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800675void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
676 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700677 DCHECK(self != nullptr);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800678 DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
Elliott Hughes5f791332011-09-15 17:45:30 -0700679
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700680 monitor_lock_.Lock(self);
681
Elliott Hughes5f791332011-09-15 17:45:30 -0700682 // Make sure that we hold the lock.
683 if (owner_ != self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700684 monitor_lock_.Unlock(self);
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700685 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700686 return;
687 }
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800688
Elliott Hughesdf42c482013-01-09 12:49:02 -0800689 // We need to turn a zero-length timed wait into a regular wait because
690 // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
691 if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
692 why = kWaiting;
693 }
694
Elliott Hughes5f791332011-09-15 17:45:30 -0700695 // Enforce the timeout range.
696 if (ms < 0 || ns < 0 || ns > 999999) {
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700697 monitor_lock_.Unlock(self);
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000698 self->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
Ian Rogersef7d42f2014-01-06 12:55:46 -0800699 "timeout arguments out of range: ms=%" PRId64 " ns=%d", ms, ns);
Elliott Hughes5f791332011-09-15 17:45:30 -0700700 return;
701 }
702
Elliott Hughes5f791332011-09-15 17:45:30 -0700703 /*
704 * Add ourselves to the set of threads waiting on this monitor, and
705 * release our hold. We need to let it go even if we're a few levels
706 * deep in a recursive lock, and we need to restore that later.
707 *
708 * We append to the wait set ahead of clearing the count and owner
709 * fields so the subroutine can check that the calling thread owns
710 * the monitor. Aside from that, the order of member updates is
711 * not order sensitive as we hold the pthread mutex.
712 */
713 AppendToWaitSet(self);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700714 ++num_waiters_;
Ian Rogers0399dde2012-06-06 17:09:28 -0700715 int prev_lock_count = lock_count_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700716 lock_count_ = 0;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700717 owner_ = nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700718 ArtMethod* saved_method = locking_method_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700719 locking_method_ = nullptr;
Ian Rogers0399dde2012-06-06 17:09:28 -0700720 uintptr_t saved_dex_pc = locking_dex_pc_;
721 locking_dex_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700722
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700723 AtraceMonitorUnlock(); // For the implict Unlock() just above. This will only end the deepest
724 // nesting, but that is enough for the visualization, and corresponds to
725 // the single Lock() we do afterwards.
726 AtraceMonitorLock(self, GetObject(), true /* is_wait */);
727
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800728 bool was_interrupted = false;
Alex Light77fee872017-09-05 14:51:49 -0700729 bool timed_out = false;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700730 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700731 // Update thread state. If the GC wakes up, it'll ignore us, knowing
732 // that we won't touch any references in this state, and we'll check
733 // our suspend mode before we transition out.
734 ScopedThreadSuspension sts(self, why);
735
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700736 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700737 MutexLock mu(self, *self->GetWaitMutex());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700738
739 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700740 // non-null a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700741 // up.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700742 DCHECK(self->GetWaitMonitor() == nullptr);
743 self->SetWaitMonitor(this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700744
745 // Release the monitor lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700746 monitor_contenders_.Signal(self);
747 monitor_lock_.Unlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700748
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800749 // Handle the case where the thread was interrupted before we called wait().
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000750 if (self->IsInterrupted()) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800751 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700752 } else {
753 // Wait for a notification or a timeout to occur.
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800754 if (why == kWaiting) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700755 self->GetWaitConditionVariable()->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700756 } else {
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800757 DCHECK(why == kTimedWaiting || why == kSleeping) << why;
Alex Light77fee872017-09-05 14:51:49 -0700758 timed_out = self->GetWaitConditionVariable()->TimedWait(self, ms, ns);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700759 }
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000760 was_interrupted = self->IsInterrupted();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700761 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700762 }
763
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800764 {
765 // We reset the thread's wait_monitor_ field after transitioning back to runnable so
766 // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
767 // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
768 // are waiting on "null".)
Ian Rogersdd7624d2014-03-14 17:43:00 -0700769 MutexLock mu(self, *self->GetWaitMutex());
770 DCHECK(self->GetWaitMonitor() != nullptr);
771 self->SetWaitMonitor(nullptr);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800772 }
773
Mathieu Chartierdaed5d82016-03-10 10:49:35 -0800774 // Allocate the interrupted exception not holding the monitor lock since it may cause a GC.
775 // If the GC requires acquiring the monitor for enqueuing cleared references, this would
776 // cause a deadlock if the monitor is held.
777 if (was_interrupted && interruptShouldThrow) {
778 /*
779 * We were interrupted while waiting, or somebody interrupted an
780 * un-interruptible thread earlier and we're bailing out immediately.
781 *
782 * The doc sayeth: "The interrupted status of the current thread is
783 * cleared when this exception is thrown."
784 */
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000785 self->SetInterrupted(false);
Mathieu Chartierdaed5d82016-03-10 10:49:35 -0800786 self->ThrowNewException("Ljava/lang/InterruptedException;", nullptr);
787 }
788
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700789 AtraceMonitorUnlock(); // End Wait().
790
Alex Light77fee872017-09-05 14:51:49 -0700791 // We just slept, tell the runtime callbacks about this.
792 Runtime::Current()->GetRuntimeCallbacks()->MonitorWaitFinished(this, timed_out);
793
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700794 // Re-acquire the monitor and lock.
Alex Light77fee872017-09-05 14:51:49 -0700795 Lock<LockReason::kForWait>(self);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700796 monitor_lock_.Lock(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700797 self->GetWaitMutex()->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700798
Elliott Hughes5f791332011-09-15 17:45:30 -0700799 /*
800 * We remove our thread from wait set after restoring the count
801 * and owner fields so the subroutine can check that the calling
802 * thread owns the monitor. Aside from that, the order of member
803 * updates is not order sensitive as we hold the pthread mutex.
804 */
805 owner_ = self;
Ian Rogers0399dde2012-06-06 17:09:28 -0700806 lock_count_ = prev_lock_count;
807 locking_method_ = saved_method;
808 locking_dex_pc_ = saved_dex_pc;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700809 --num_waiters_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700810 RemoveFromWaitSet(self);
811
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700812 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700813}
814
815void Monitor::Notify(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700816 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700817 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700818 // Make sure that we hold the lock.
819 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800820 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700821 return;
822 }
823 // Signal the first waiting thread in the wait set.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700824 while (wait_set_ != nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700825 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700826 wait_set_ = thread->GetWaitNext();
827 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700828
829 // Check to see if the thread is still waiting.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800830 MutexLock wait_mu(self, *thread->GetWaitMutex());
Ian Rogersdd7624d2014-03-14 17:43:00 -0700831 if (thread->GetWaitMonitor() != nullptr) {
832 thread->GetWaitConditionVariable()->Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700833 return;
834 }
835 }
836}
837
838void Monitor::NotifyAll(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700839 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700840 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700841 // Make sure that we hold the lock.
842 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800843 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700844 return;
845 }
846 // Signal all threads in the wait set.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700847 while (wait_set_ != nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700848 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700849 wait_set_ = thread->GetWaitNext();
850 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700851 thread->Notify();
852 }
853}
854
Mathieu Chartier590fee92013-09-13 13:46:47 -0700855bool Monitor::Deflate(Thread* self, mirror::Object* obj) {
856 DCHECK(obj != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700857 // Don't need volatile since we only deflate with mutators suspended.
858 LockWord lw(obj->GetLockWord(false));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700859 // If the lock isn't an inflated monitor, then we don't need to deflate anything.
860 if (lw.GetState() == LockWord::kFatLocked) {
861 Monitor* monitor = lw.FatLockMonitor();
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700862 DCHECK(monitor != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700863 MutexLock mu(self, monitor->monitor_lock_);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700864 // Can't deflate if we have anybody waiting on the CV.
865 if (monitor->num_waiters_ > 0) {
866 return false;
867 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700868 Thread* owner = monitor->owner_;
869 if (owner != nullptr) {
870 // Can't deflate if we are locked and have a hash code.
871 if (monitor->HasHashCode()) {
872 return false;
873 }
874 // Can't deflate if our lock count is too high.
Mathieu Chartier1cf194f2016-11-01 20:13:24 -0700875 if (static_cast<uint32_t>(monitor->lock_count_) > LockWord::kThinLockMaxCount) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700876 return false;
877 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700878 // Deflate to a thin lock.
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700879 LockWord new_lw = LockWord::FromThinLockId(owner->GetThreadId(),
880 monitor->lock_count_,
881 lw.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800882 // Assume no concurrent read barrier state changes as mutators are suspended.
883 obj->SetLockWord(new_lw, false);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700884 VLOG(monitor) << "Deflated " << obj << " to thin lock " << owner->GetTid() << " / "
885 << monitor->lock_count_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700886 } else if (monitor->HasHashCode()) {
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700887 LockWord new_lw = LockWord::FromHashCode(monitor->GetHashCode(), lw.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800888 // Assume no concurrent read barrier state changes as mutators are suspended.
889 obj->SetLockWord(new_lw, false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700890 VLOG(monitor) << "Deflated " << obj << " to hash monitor " << monitor->GetHashCode();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700891 } else {
892 // No lock and no hash, just put an empty lock word inside the object.
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700893 LockWord new_lw = LockWord::FromDefault(lw.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800894 // Assume no concurrent read barrier state changes as mutators are suspended.
895 obj->SetLockWord(new_lw, false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700896 VLOG(monitor) << "Deflated" << obj << " to empty lock word";
Mathieu Chartier590fee92013-09-13 13:46:47 -0700897 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700898 // 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 -0700899 // next GC.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700900 monitor->obj_ = GcRoot<mirror::Object>(nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700901 }
902 return true;
903}
904
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700905void Monitor::Inflate(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code) {
Andreas Gampe74240812014-04-17 10:35:09 -0700906 DCHECK(self != nullptr);
907 DCHECK(obj != nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700908 // Allocate and acquire a new monitor.
Andreas Gampe74240812014-04-17 10:35:09 -0700909 Monitor* m = MonitorPool::CreateMonitor(self, owner, obj, hash_code);
910 DCHECK(m != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700911 if (m->Install(self)) {
Haifeng Li86ab7912014-05-16 10:47:59 +0800912 if (owner != nullptr) {
913 VLOG(monitor) << "monitor: thread" << owner->GetThreadId()
Andreas Gampe74240812014-04-17 10:35:09 -0700914 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800915 } else {
916 VLOG(monitor) << "monitor: Inflate with hashcode " << hash_code
Andreas Gampe74240812014-04-17 10:35:09 -0700917 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800918 }
Andreas Gampe74240812014-04-17 10:35:09 -0700919 Runtime::Current()->GetMonitorList()->Add(m);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700920 CHECK_EQ(obj->GetLockWord(true).GetState(), LockWord::kFatLocked);
Andreas Gampe74240812014-04-17 10:35:09 -0700921 } else {
922 MonitorPool::ReleaseMonitor(self, m);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700923 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700924}
925
Mathieu Chartier0cd81352014-05-22 16:48:55 -0700926void Monitor::InflateThinLocked(Thread* self, Handle<mirror::Object> obj, LockWord lock_word,
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700927 uint32_t hash_code) {
928 DCHECK_EQ(lock_word.GetState(), LockWord::kThinLocked);
929 uint32_t owner_thread_id = lock_word.ThinLockOwner();
930 if (owner_thread_id == self->GetThreadId()) {
931 // We own the monitor, we can easily inflate it.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700932 Inflate(self, self, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700933 } else {
934 ThreadList* thread_list = Runtime::Current()->GetThreadList();
935 // Suspend the owner, inflate. First change to blocked and give up mutator_lock_.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700936 self->SetMonitorEnterObject(obj.Get());
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700937 bool timed_out;
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700938 Thread* owner;
939 {
Alex Light77fee872017-09-05 14:51:49 -0700940 ScopedThreadSuspension sts(self, kWaitingForLockInflation);
Alex Light46f93402017-06-29 11:59:50 -0700941 owner = thread_list->SuspendThreadByThreadId(owner_thread_id,
942 SuspendReason::kInternal,
943 &timed_out);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700944 }
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700945 if (owner != nullptr) {
946 // We succeeded in suspending the thread, check the lock's status didn't change.
947 lock_word = obj->GetLockWord(true);
948 if (lock_word.GetState() == LockWord::kThinLocked &&
949 lock_word.ThinLockOwner() == owner_thread_id) {
950 // Go ahead and inflate the lock.
951 Inflate(self, owner, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700952 }
Alex Light88fd7202017-06-30 08:31:59 -0700953 bool resumed = thread_list->Resume(owner, SuspendReason::kInternal);
954 DCHECK(resumed);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700955 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700956 self->SetMonitorEnterObject(nullptr);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700957 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700958}
959
Ian Rogers719d1a32014-03-06 12:13:39 -0800960// Fool annotalysis into thinking that the lock on obj is acquired.
961static mirror::Object* FakeLock(mirror::Object* obj)
962 EXCLUSIVE_LOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
963 return obj;
964}
965
966// Fool annotalysis into thinking that the lock on obj is release.
967static mirror::Object* FakeUnlock(mirror::Object* obj)
968 UNLOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
969 return obj;
970}
971
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700972mirror::Object* Monitor::MonitorEnter(Thread* self, mirror::Object* obj, bool trylock) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700973 DCHECK(self != nullptr);
974 DCHECK(obj != nullptr);
Mathieu Chartier2d096c92015-10-12 16:18:20 -0700975 self->AssertThreadSuspensionIsAllowable();
Ian Rogers719d1a32014-03-06 12:13:39 -0800976 obj = FakeLock(obj);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700977 uint32_t thread_id = self->GetThreadId();
978 size_t contention_count = 0;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700979 StackHandleScope<1> hs(self);
980 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700981 while (true) {
Hans Boehmb3da36c2016-12-15 13:12:59 -0800982 // We initially read the lockword with ordinary Java/relaxed semantics. When stronger
983 // semantics are needed, we address it below. Since GetLockWord bottoms out to a relaxed load,
984 // we can fix it later, in an infrequently executed case, with a fence.
985 LockWord lock_word = h_obj->GetLockWord(false);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700986 switch (lock_word.GetState()) {
987 case LockWord::kUnlocked: {
Hans Boehmb3da36c2016-12-15 13:12:59 -0800988 // No ordering required for preceding lockword read, since we retest.
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700989 LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0, lock_word.GCState()));
Hans Boehmb3da36c2016-12-15 13:12:59 -0800990 if (h_obj->CasLockWordWeakAcquire(lock_word, thin_locked)) {
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700991 AtraceMonitorLock(self, h_obj.Get(), false /* is_wait */);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700992 return h_obj.Get(); // Success!
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700993 }
994 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -0700995 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700996 case LockWord::kThinLocked: {
997 uint32_t owner_thread_id = lock_word.ThinLockOwner();
998 if (owner_thread_id == thread_id) {
Hans Boehmb3da36c2016-12-15 13:12:59 -0800999 // No ordering required for initial lockword read.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001000 // We own the lock, increase the recursion count.
1001 uint32_t new_count = lock_word.ThinLockCount() + 1;
1002 if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001003 LockWord thin_locked(LockWord::FromThinLockId(thread_id,
1004 new_count,
1005 lock_word.GCState()));
Hans Boehmb3da36c2016-12-15 13:12:59 -08001006 // Only this thread pays attention to the count. Thus there is no need for stronger
1007 // than relaxed memory ordering.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001008 if (!kUseReadBarrier) {
Hans Boehmb3da36c2016-12-15 13:12:59 -08001009 h_obj->SetLockWord(thin_locked, false /* volatile */);
Andreas Gampec7ed09b2016-04-25 20:08:55 -07001010 AtraceMonitorLock(self, h_obj.Get(), false /* is_wait */);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001011 return h_obj.Get(); // Success!
1012 } else {
1013 // Use CAS to preserve the read barrier state.
Hans Boehmb3da36c2016-12-15 13:12:59 -08001014 if (h_obj->CasLockWordWeakRelaxed(lock_word, thin_locked)) {
Andreas Gampec7ed09b2016-04-25 20:08:55 -07001015 AtraceMonitorLock(self, h_obj.Get(), false /* is_wait */);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001016 return h_obj.Get(); // Success!
1017 }
1018 }
1019 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -07001020 } else {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001021 // We'd overflow the recursion count, so inflate the monitor.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001022 InflateThinLocked(self, h_obj, lock_word, 0);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001023 }
1024 } else {
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07001025 if (trylock) {
1026 return nullptr;
1027 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001028 // Contention.
1029 contention_count++;
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001030 Runtime* runtime = Runtime::Current();
Hans Boehmb3da36c2016-12-15 13:12:59 -08001031 if (contention_count <= runtime->GetMaxSpinsBeforeThinLockInflation()) {
Alex Light77fee872017-09-05 14:51:49 -07001032 // TODO: Consider switching the thread state to kWaitingForLockInflation when we are
1033 // yielding. Use sched_yield instead of NanoSleep since NanoSleep can wait much longer
1034 // than the parameter you pass in. This can cause thread suspension to take excessively
1035 // long and make long pauses. See b/16307460.
Hans Boehmb3da36c2016-12-15 13:12:59 -08001036 // TODO: We should literally spin first, without sched_yield. Sched_yield either does
1037 // nothing (at significant expense), or guarantees that we wait at least microseconds.
1038 // If the owner is running, I would expect the median lock hold time to be hundreds
1039 // of nanoseconds or less.
Mathieu Chartier251755c2014-07-15 18:10:25 -07001040 sched_yield();
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001041 } else {
1042 contention_count = 0;
Hans Boehmb3da36c2016-12-15 13:12:59 -08001043 // No ordering required for initial lockword read. Install rereads it anyway.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001044 InflateThinLocked(self, h_obj, lock_word, 0);
Elliott Hughes5f791332011-09-15 17:45:30 -07001045 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001046 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001047 continue; // Start from the beginning.
Elliott Hughes5f791332011-09-15 17:45:30 -07001048 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001049 case LockWord::kFatLocked: {
Hans Boehmb3da36c2016-12-15 13:12:59 -08001050 // We should have done an acquire read of the lockword initially, to ensure
1051 // visibility of the monitor data structure. Use an explicit fence instead.
1052 QuasiAtomic::ThreadFenceAcquire();
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001053 Monitor* mon = lock_word.FatLockMonitor();
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07001054 if (trylock) {
1055 return mon->TryLock(self) ? h_obj.Get() : nullptr;
1056 } else {
1057 mon->Lock(self);
1058 return h_obj.Get(); // Success!
1059 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001060 }
Ian Rogers719d1a32014-03-06 12:13:39 -08001061 case LockWord::kHashCode:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001062 // Inflate with the existing hashcode.
Hans Boehmb3da36c2016-12-15 13:12:59 -08001063 // Again no ordering required for initial lockword read, since we don't rely
1064 // on the visibility of any prior computation.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001065 Inflate(self, nullptr, h_obj.Get(), lock_word.GetHashCode());
Ian Rogers719d1a32014-03-06 12:13:39 -08001066 continue; // Start from the beginning.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001067 default: {
1068 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Andreas Gampec7ed09b2016-04-25 20:08:55 -07001069 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001070 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001071 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001072 }
1073}
1074
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001075bool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001076 DCHECK(self != nullptr);
1077 DCHECK(obj != nullptr);
Mathieu Chartier2d096c92015-10-12 16:18:20 -07001078 self->AssertThreadSuspensionIsAllowable();
Ian Rogers719d1a32014-03-06 12:13:39 -08001079 obj = FakeUnlock(obj);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001080 StackHandleScope<1> hs(self);
1081 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001082 while (true) {
1083 LockWord lock_word = obj->GetLockWord(true);
1084 switch (lock_word.GetState()) {
1085 case LockWord::kHashCode:
1086 // Fall-through.
1087 case LockWord::kUnlocked:
Mathieu Chartier61b3cd42016-04-18 11:43:29 -07001088 FailedUnlock(h_obj.Get(), self->GetThreadId(), 0u, nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001089 return false; // Failure.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001090 case LockWord::kThinLocked: {
1091 uint32_t thread_id = self->GetThreadId();
1092 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1093 if (owner_thread_id != thread_id) {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -07001094 FailedUnlock(h_obj.Get(), thread_id, owner_thread_id, nullptr);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001095 return false; // Failure.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001096 } else {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001097 // We own the lock, decrease the recursion count.
1098 LockWord new_lw = LockWord::Default();
1099 if (lock_word.ThinLockCount() != 0) {
1100 uint32_t new_count = lock_word.ThinLockCount() - 1;
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001101 new_lw = LockWord::FromThinLockId(thread_id, new_count, lock_word.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001102 } else {
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001103 new_lw = LockWord::FromDefault(lock_word.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001104 }
1105 if (!kUseReadBarrier) {
1106 DCHECK_EQ(new_lw.ReadBarrierState(), 0U);
Hans Boehmb3da36c2016-12-15 13:12:59 -08001107 // TODO: This really only needs memory_order_release, but we currently have
1108 // no way to specify that. In fact there seem to be no legitimate uses of SetLockWord
1109 // with a final argument of true. This slows down x86 and ARMv7, but probably not v8.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001110 h_obj->SetLockWord(new_lw, true);
Andreas Gampe6e759ad2016-05-17 10:13:10 -07001111 AtraceMonitorUnlock();
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001112 // Success!
1113 return true;
1114 } else {
1115 // Use CAS to preserve the read barrier state.
Hans Boehmb3da36c2016-12-15 13:12:59 -08001116 if (h_obj->CasLockWordWeakRelease(lock_word, new_lw)) {
Andreas Gampe6e759ad2016-05-17 10:13:10 -07001117 AtraceMonitorUnlock();
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001118 // Success!
1119 return true;
1120 }
1121 }
1122 continue; // Go again.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001123 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001124 }
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001125 case LockWord::kFatLocked: {
1126 Monitor* mon = lock_word.FatLockMonitor();
1127 return mon->Unlock(self);
1128 }
1129 default: {
1130 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1131 return false;
1132 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001133 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001134 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001135}
1136
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001137void Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
Elliott Hughes4cd121e2013-01-07 17:35:41 -08001138 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001139 DCHECK(self != nullptr);
1140 DCHECK(obj != nullptr);
Alex Light77fee872017-09-05 14:51:49 -07001141 StackHandleScope<1> hs(self);
1142 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
1143
1144 Runtime::Current()->GetRuntimeCallbacks()->ObjectWaitStart(h_obj, ms);
1145 if (UNLIKELY(self->IsExceptionPending())) {
1146 // See b/65558434 for information on handling of exceptions here.
1147 return;
1148 }
1149
1150 LockWord lock_word = h_obj->GetLockWord(true);
Ian Rogers43c69cc2014-08-15 11:09:28 -07001151 while (lock_word.GetState() != LockWord::kFatLocked) {
1152 switch (lock_word.GetState()) {
1153 case LockWord::kHashCode:
1154 // Fall-through.
1155 case LockWord::kUnlocked:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001156 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
1157 return; // Failure.
Ian Rogers43c69cc2014-08-15 11:09:28 -07001158 case LockWord::kThinLocked: {
1159 uint32_t thread_id = self->GetThreadId();
1160 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1161 if (owner_thread_id != thread_id) {
1162 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
1163 return; // Failure.
1164 } else {
1165 // We own the lock, inflate to enqueue ourself on the Monitor. May fail spuriously so
1166 // re-load.
Alex Light77fee872017-09-05 14:51:49 -07001167 Inflate(self, self, h_obj.Get(), 0);
1168 lock_word = h_obj->GetLockWord(true);
Ian Rogers43c69cc2014-08-15 11:09:28 -07001169 }
1170 break;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001171 }
Ian Rogers43c69cc2014-08-15 11:09:28 -07001172 case LockWord::kFatLocked: // Unreachable given the loop condition above. Fall-through.
1173 default: {
1174 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1175 return;
1176 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001177 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001178 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001179 Monitor* mon = lock_word.FatLockMonitor();
1180 mon->Wait(self, ms, ns, interruptShouldThrow, why);
Elliott Hughes5f791332011-09-15 17:45:30 -07001181}
1182
Ian Rogers13c479e2013-10-11 07:59:01 -07001183void Monitor::DoNotify(Thread* self, mirror::Object* obj, bool notify_all) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001184 DCHECK(self != nullptr);
1185 DCHECK(obj != nullptr);
1186 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001187 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001188 case LockWord::kHashCode:
1189 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001190 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -08001191 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001192 return; // Failure.
1193 case LockWord::kThinLocked: {
1194 uint32_t thread_id = self->GetThreadId();
1195 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1196 if (owner_thread_id != thread_id) {
1197 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
1198 return; // Failure.
1199 } else {
1200 // We own the lock but there's no Monitor and therefore no waiters.
1201 return; // Success.
1202 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001203 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001204 case LockWord::kFatLocked: {
1205 Monitor* mon = lock_word.FatLockMonitor();
1206 if (notify_all) {
1207 mon->NotifyAll(self);
1208 } else {
1209 mon->Notify(self);
1210 }
1211 return; // Success.
1212 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001213 default: {
1214 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1215 return;
1216 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001217 }
1218}
1219
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001220uint32_t Monitor::GetLockOwnerThreadId(mirror::Object* obj) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001221 DCHECK(obj != nullptr);
1222 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001223 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001224 case LockWord::kHashCode:
1225 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001226 case LockWord::kUnlocked:
1227 return ThreadList::kInvalidThreadId;
1228 case LockWord::kThinLocked:
1229 return lock_word.ThinLockOwner();
1230 case LockWord::kFatLocked: {
1231 Monitor* mon = lock_word.FatLockMonitor();
1232 return mon->GetOwnerThreadId();
Elliott Hughes5f791332011-09-15 17:45:30 -07001233 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001234 default: {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001235 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001236 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001237 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001238 }
1239}
1240
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001241void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
Ian Rogersd803bc72014-04-01 15:33:03 -07001242 // Determine the wait message and object we're waiting or blocked upon.
1243 mirror::Object* pretty_object = nullptr;
1244 const char* wait_message = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001245 uint32_t lock_owner = ThreadList::kInvalidThreadId;
Ian Rogersd803bc72014-04-01 15:33:03 -07001246 ThreadState state = thread->GetState();
Elliott Hughesb4e94fd2013-01-08 14:41:26 -08001247 if (state == kWaiting || state == kTimedWaiting || state == kSleeping) {
Ian Rogersd803bc72014-04-01 15:33:03 -07001248 wait_message = (state == kSleeping) ? " - sleeping on " : " - waiting on ";
1249 Thread* self = Thread::Current();
1250 MutexLock mu(self, *thread->GetWaitMutex());
1251 Monitor* monitor = thread->GetWaitMonitor();
1252 if (monitor != nullptr) {
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001253 pretty_object = monitor->GetObject();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001254 }
Alex Light77fee872017-09-05 14:51:49 -07001255 } else if (state == kBlocked || state == kWaitingForLockInflation) {
1256 wait_message = (state == kBlocked) ? " - waiting to lock "
1257 : " - waiting for lock inflation of ";
Ian Rogersd803bc72014-04-01 15:33:03 -07001258 pretty_object = thread->GetMonitorEnterObject();
1259 if (pretty_object != nullptr) {
Hiroshi Yamauchi7b08ae42016-10-04 15:20:36 -07001260 if (kUseReadBarrier && Thread::Current()->GetIsGcMarking()) {
1261 // We may call Thread::Dump() in the middle of the CC thread flip and this thread's stack
1262 // may have not been flipped yet and "pretty_object" may be a from-space (stale) ref, in
1263 // which case the GetLockOwnerThreadId() call below will crash. So explicitly mark/forward
1264 // it here.
1265 pretty_object = ReadBarrier::Mark(pretty_object);
1266 }
Ian Rogersd803bc72014-04-01 15:33:03 -07001267 lock_owner = pretty_object->GetLockOwnerThreadId();
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001268 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001269 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001270
Ian Rogersd803bc72014-04-01 15:33:03 -07001271 if (wait_message != nullptr) {
1272 if (pretty_object == nullptr) {
1273 os << wait_message << "an unknown object";
1274 } else {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001275 if ((pretty_object->GetLockWord(true).GetState() == LockWord::kThinLocked) &&
Ian Rogersd803bc72014-04-01 15:33:03 -07001276 Locks::mutator_lock_->IsExclusiveHeld(Thread::Current())) {
1277 // Getting the identity hashcode here would result in lock inflation and suspension of the
1278 // current thread, which isn't safe if this is the only runnable thread.
1279 os << wait_message << StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)",
1280 reinterpret_cast<intptr_t>(pretty_object),
David Sehr709b0702016-10-13 09:12:37 -07001281 pretty_object->PrettyTypeOf().c_str());
Ian Rogersd803bc72014-04-01 15:33:03 -07001282 } else {
1283 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
Mathieu Chartier49361592015-01-22 16:36:10 -08001284 // Call PrettyTypeOf before IdentityHashCode since IdentityHashCode can cause thread
1285 // suspension and move pretty_object.
David Sehr709b0702016-10-13 09:12:37 -07001286 const std::string pretty_type(pretty_object->PrettyTypeOf());
Ian Rogersd803bc72014-04-01 15:33:03 -07001287 os << wait_message << StringPrintf("<0x%08x> (a %s)", pretty_object->IdentityHashCode(),
Mathieu Chartier49361592015-01-22 16:36:10 -08001288 pretty_type.c_str());
Ian Rogersd803bc72014-04-01 15:33:03 -07001289 }
1290 }
1291 // - waiting to lock <0x613f83d8> (a java.lang.Object) held by thread 5
1292 if (lock_owner != ThreadList::kInvalidThreadId) {
1293 os << " held by thread " << lock_owner;
1294 }
1295 os << "\n";
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001296 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001297}
1298
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001299mirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -08001300 // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
1301 // definition of contended that includes a monitor a thread is trying to enter...
Ian Rogersdd7624d2014-03-14 17:43:00 -07001302 mirror::Object* result = thread->GetMonitorEnterObject();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001303 if (result == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001304 // ...but also a monitor that the thread is waiting on.
Ian Rogersdd7624d2014-03-14 17:43:00 -07001305 MutexLock mu(Thread::Current(), *thread->GetWaitMutex());
1306 Monitor* monitor = thread->GetWaitMonitor();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001307 if (monitor != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001308 result = monitor->GetObject();
Elliott Hughesf9501702013-01-11 11:22:27 -08001309 }
1310 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001311 return result;
Elliott Hughesf9501702013-01-11 11:22:27 -08001312}
1313
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001314void Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
Andreas Gampe760172c2014-08-16 13:41:10 -07001315 void* callback_context, bool abort_on_failure) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001316 ArtMethod* m = stack_visitor->GetMethod();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001317 CHECK(m != nullptr);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001318
1319 // Native methods are an easy special case.
1320 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
1321 if (m->IsNative()) {
1322 if (m->IsSynchronized()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001323 mirror::Object* jni_this =
1324 stack_visitor->GetCurrentHandleScope(sizeof(void*))->GetReference(0);
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001325 callback(jni_this, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001326 }
1327 return;
1328 }
1329
jeffhao61f916c2012-10-25 17:48:51 -07001330 // Proxy methods should not be synchronized.
1331 if (m->IsProxyMethod()) {
1332 CHECK(!m->IsSynchronized());
1333 return;
1334 }
1335
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001336 // Is there any reason to believe there's any synchronization in this method?
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001337 const DexFile::CodeItem* code_item = m->GetCodeItem();
David Sehr709b0702016-10-13 09:12:37 -07001338 CHECK(code_item != nullptr) << m->PrettyMethod();
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001339 if (code_item->tries_size_ == 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001340 return; // No "tries" implies no synchronization, so no held locks to report.
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001341 }
1342
Andreas Gampe760172c2014-08-16 13:41:10 -07001343 // Get the dex pc. If abort_on_failure is false, GetDexPc will not abort in the case it cannot
1344 // find the dex pc, and instead return kDexNoIndex. Then bail out, as it indicates we have an
1345 // inconsistent stack anyways.
1346 uint32_t dex_pc = stack_visitor->GetDexPc(abort_on_failure);
1347 if (!abort_on_failure && dex_pc == DexFile::kDexNoIndex) {
David Sehr709b0702016-10-13 09:12:37 -07001348 LOG(ERROR) << "Could not find dex_pc for " << m->PrettyMethod();
Andreas Gampe760172c2014-08-16 13:41:10 -07001349 return;
1350 }
1351
Elliott Hughes80537bb2013-01-04 16:37:26 -08001352 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
1353 // the locks held in this stack frame.
1354 std::vector<uint32_t> monitor_enter_dex_pcs;
Andreas Gampe760172c2014-08-16 13:41:10 -07001355 verifier::MethodVerifier::FindLocksAtDexPc(m, dex_pc, &monitor_enter_dex_pcs);
Mathieu Chartiere6a8eec2015-01-06 14:17:57 -08001356 for (uint32_t monitor_dex_pc : monitor_enter_dex_pcs) {
Elliott Hughes80537bb2013-01-04 16:37:26 -08001357 // The verifier works in terms of the dex pcs of the monitor-enter instructions.
1358 // We want the registers used by those instructions (so we can read the values out of them).
Sebastien Hertz0f7c9332015-11-05 15:57:30 +01001359 const Instruction* monitor_enter_instruction =
1360 Instruction::At(&code_item->insns_[monitor_dex_pc]);
Elliott Hughes80537bb2013-01-04 16:37:26 -08001361
1362 // Quick sanity check.
Sebastien Hertz0f7c9332015-11-05 15:57:30 +01001363 CHECK_EQ(monitor_enter_instruction->Opcode(), Instruction::MONITOR_ENTER)
1364 << "expected monitor-enter @" << monitor_dex_pc << "; was "
1365 << reinterpret_cast<const void*>(monitor_enter_instruction);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001366
Sebastien Hertz0f7c9332015-11-05 15:57:30 +01001367 uint16_t monitor_register = monitor_enter_instruction->VRegA();
Nicolas Geoffray15b9d522015-03-12 15:05:13 +00001368 uint32_t value;
1369 bool success = stack_visitor->GetVReg(m, monitor_register, kReferenceVReg, &value);
1370 CHECK(success) << "Failed to read v" << monitor_register << " of kind "
David Sehr709b0702016-10-13 09:12:37 -07001371 << kReferenceVReg << " in method " << m->PrettyMethod();
Nicolas Geoffray15b9d522015-03-12 15:05:13 +00001372 mirror::Object* o = reinterpret_cast<mirror::Object*>(value);
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001373 callback(o, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001374 }
1375}
1376
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001377bool Monitor::IsValidLockWord(LockWord lock_word) {
1378 switch (lock_word.GetState()) {
1379 case LockWord::kUnlocked:
1380 // Nothing to check.
1381 return true;
1382 case LockWord::kThinLocked:
1383 // Basic sanity check of owner.
1384 return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
1385 case LockWord::kFatLocked: {
1386 // Check the monitor appears in the monitor list.
1387 Monitor* mon = lock_word.FatLockMonitor();
1388 MonitorList* list = Runtime::Current()->GetMonitorList();
1389 MutexLock mu(Thread::Current(), list->monitor_list_lock_);
1390 for (Monitor* list_mon : list->list_) {
1391 if (mon == list_mon) {
1392 return true; // Found our monitor.
1393 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001394 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001395 return false; // Fail - unowned monitor in an object.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001396 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001397 case LockWord::kHashCode:
1398 return true;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001399 default:
1400 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001401 UNREACHABLE();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001402 }
1403}
1404
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001405bool Monitor::IsLocked() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001406 MutexLock mu(Thread::Current(), monitor_lock_);
1407 return owner_ != nullptr;
1408}
1409
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -07001410void Monitor::TranslateLocation(ArtMethod* method,
1411 uint32_t dex_pc,
1412 const char** source_file,
1413 int32_t* line_number) {
jeffhao33dc7712011-11-09 17:54:24 -08001414 // If method is null, location is unknown
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001415 if (method == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001416 *source_file = "";
1417 *line_number = 0;
jeffhao33dc7712011-11-09 17:54:24 -08001418 return;
1419 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001420 *source_file = method->GetDeclaringClassSourceFile();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001421 if (*source_file == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001422 *source_file = "";
Elliott Hughes12c51e32012-01-17 20:25:05 -08001423 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001424 *line_number = method->GetLineNumFromDexPC(dex_pc);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001425}
1426
1427uint32_t Monitor::GetOwnerThreadId() {
1428 MutexLock mu(Thread::Current(), monitor_lock_);
1429 Thread* owner = owner_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001430 if (owner != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001431 return owner->GetThreadId();
1432 } else {
1433 return ThreadList::kInvalidThreadId;
1434 }
jeffhao33dc7712011-11-09 17:54:24 -08001435}
1436
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001437MonitorList::MonitorList()
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001438 : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock", kMonitorListLock),
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001439 monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001440}
1441
1442MonitorList::~MonitorList() {
Andreas Gampe74240812014-04-17 10:35:09 -07001443 Thread* self = Thread::Current();
1444 MutexLock mu(self, monitor_list_lock_);
1445 // Release all monitors to the pool.
1446 // TODO: Is it an invariant that *all* open monitors are in the list? Then we could
1447 // clear faster in the pool.
1448 MonitorPool::ReleaseMonitors(self, &list_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001449}
1450
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001451void MonitorList::DisallowNewMonitors() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001452 CHECK(!kUseReadBarrier);
Ian Rogers50b35e22012-10-04 10:09:15 -07001453 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001454 allow_new_monitors_ = false;
1455}
1456
1457void MonitorList::AllowNewMonitors() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001458 CHECK(!kUseReadBarrier);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001459 Thread* self = Thread::Current();
1460 MutexLock mu(self, monitor_list_lock_);
1461 allow_new_monitors_ = true;
1462 monitor_add_condition_.Broadcast(self);
1463}
1464
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001465void MonitorList::BroadcastForNewMonitors() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001466 Thread* self = Thread::Current();
1467 MutexLock mu(self, monitor_list_lock_);
1468 monitor_add_condition_.Broadcast(self);
1469}
1470
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001471void MonitorList::Add(Monitor* m) {
1472 Thread* self = Thread::Current();
1473 MutexLock mu(self, monitor_list_lock_);
Hiroshi Yamauchif1c6f872017-01-06 12:23:47 -08001474 // CMS needs this to block for concurrent reference processing because an object allocated during
1475 // the GC won't be marked and concurrent reference processing would incorrectly clear the JNI weak
1476 // ref. But CC (kUseReadBarrier == true) doesn't because of the to-space invariant.
1477 while (!kUseReadBarrier && UNLIKELY(!allow_new_monitors_)) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -07001478 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
1479 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -08001480 self->CheckEmptyCheckpointFromWeakRefAccess(&monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001481 monitor_add_condition_.WaitHoldingLocks(self);
1482 }
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001483 list_.push_front(m);
1484}
1485
Mathieu Chartier97509952015-07-13 14:35:43 -07001486void MonitorList::SweepMonitorList(IsMarkedVisitor* visitor) {
Andreas Gampe74240812014-04-17 10:35:09 -07001487 Thread* self = Thread::Current();
1488 MutexLock mu(self, monitor_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001489 for (auto it = list_.begin(); it != list_.end(); ) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001490 Monitor* m = *it;
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001491 // Disable the read barrier in GetObject() as this is called by GC.
1492 mirror::Object* obj = m->GetObject<kWithoutReadBarrier>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001493 // The object of a monitor can be null if we have deflated it.
Mathieu Chartier97509952015-07-13 14:35:43 -07001494 mirror::Object* new_obj = obj != nullptr ? visitor->IsMarked(obj) : nullptr;
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001495 if (new_obj == nullptr) {
1496 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001497 << obj;
Andreas Gampe74240812014-04-17 10:35:09 -07001498 MonitorPool::ReleaseMonitor(self, m);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001499 it = list_.erase(it);
1500 } else {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001501 m->SetObject(new_obj);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001502 ++it;
1503 }
1504 }
1505}
1506
Hans Boehm6fe97e02016-05-04 18:35:57 -07001507size_t MonitorList::Size() {
1508 Thread* self = Thread::Current();
1509 MutexLock mu(self, monitor_list_lock_);
1510 return list_.size();
1511}
1512
Mathieu Chartier97509952015-07-13 14:35:43 -07001513class MonitorDeflateVisitor : public IsMarkedVisitor {
1514 public:
1515 MonitorDeflateVisitor() : self_(Thread::Current()), deflate_count_(0) {}
1516
1517 virtual mirror::Object* IsMarked(mirror::Object* object) OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001518 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001519 if (Monitor::Deflate(self_, object)) {
1520 DCHECK_NE(object->GetLockWord(true).GetState(), LockWord::kFatLocked);
1521 ++deflate_count_;
1522 // If we deflated, return null so that the monitor gets removed from the array.
1523 return nullptr;
1524 }
1525 return object; // Monitor was not deflated.
1526 }
1527
1528 Thread* const self_;
1529 size_t deflate_count_;
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001530};
1531
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001532size_t MonitorList::DeflateMonitors() {
Mathieu Chartier97509952015-07-13 14:35:43 -07001533 MonitorDeflateVisitor visitor;
1534 Locks::mutator_lock_->AssertExclusiveHeld(visitor.self_);
1535 SweepMonitorList(&visitor);
1536 return visitor.deflate_count_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001537}
1538
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001539MonitorInfo::MonitorInfo(mirror::Object* obj) : owner_(nullptr), entry_count_(0) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001540 DCHECK(obj != nullptr);
1541 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001542 switch (lock_word.GetState()) {
1543 case LockWord::kUnlocked:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001544 // Fall-through.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001545 case LockWord::kForwardingAddress:
1546 // Fall-through.
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001547 case LockWord::kHashCode:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001548 break;
1549 case LockWord::kThinLocked:
1550 owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
Alex Lightce568642017-09-05 16:54:25 -07001551 DCHECK(owner_ != nullptr) << "Thin-locked without owner!";
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001552 entry_count_ = 1 + lock_word.ThinLockCount();
1553 // Thin locks have no waiters.
1554 break;
1555 case LockWord::kFatLocked: {
1556 Monitor* mon = lock_word.FatLockMonitor();
1557 owner_ = mon->owner_;
Alex Lightce568642017-09-05 16:54:25 -07001558 // Here it is okay for the owner to be null since we don't reset the LockWord back to
1559 // kUnlocked until we get a GC. In cases where this hasn't happened yet we will have a fat
1560 // lock without an owner.
1561 if (owner_ != nullptr) {
1562 entry_count_ = 1 + mon->lock_count_;
1563 } else {
1564 DCHECK_EQ(mon->lock_count_, 0) << "Monitor is fat-locked without any owner!";
1565 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001566 for (Thread* waiter = mon->wait_set_; waiter != nullptr; waiter = waiter->GetWaitNext()) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001567 waiters_.push_back(waiter);
1568 }
1569 break;
Elliott Hughesf327e072013-01-09 16:01:26 -08001570 }
1571 }
1572}
1573
Elliott Hughes5f791332011-09-15 17:45:30 -07001574} // namespace art