blob: e7ecaa75f92e09a5160e368d536e260106056be9 [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"
Andreas Gampee2abbc62017-09-15 11:59:26 -070030#include "dex_file_types.h"
Sebastien Hertz0f7c9332015-11-05 15:57:30 +010031#include "dex_instruction-inl.h"
Ian Rogersd9c4fc92013-10-01 19:45:43 -070032#include "lock_word-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070033#include "mirror/class-inl.h"
Ian Rogers05f30572013-02-20 12:13:11 -080034#include "mirror/object-inl.h"
Andreas Gampe5d08fcc2017-06-05 17:56:46 -070035#include "object_callbacks.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070036#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070037#include "stack.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070038#include "thread.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070039#include "thread_list.h"
Elliott Hughes08fc03a2012-06-26 17:34:00 -070040#include "verifier/method_verifier.h"
Elliott Hughes044288f2012-06-25 14:46:39 -070041#include "well_known_classes.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070042
43namespace art {
44
Andreas Gampe46ee31b2016-12-14 10:11:49 -080045using android::base::StringPrintf;
46
Andreas Gampe5d689142017-10-19 13:03:29 -070047static constexpr uint64_t kDebugThresholdFudgeFactor = kIsDebugBuild ? 10 : 1;
48static constexpr uint64_t kLongWaitMs = 100 * kDebugThresholdFudgeFactor;
Mathieu Chartierb9001ab2014-10-03 13:28:46 -070049
Elliott Hughes5f791332011-09-15 17:45:30 -070050/*
Ian Rogersd9c4fc92013-10-01 19:45:43 -070051 * Every Object has a monitor associated with it, but not every Object is actually locked. Even
52 * the ones that are locked do not need a full-fledged monitor until a) there is actual contention
53 * or b) wait() is called on the Object.
Elliott Hughes5f791332011-09-15 17:45:30 -070054 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070055 * For Android, we have implemented a scheme similar to the one described in Bacon et al.'s
56 * "Thin locks: featherweight synchronization for Java" (ACM 1998). Things are even easier for us,
57 * though, because we have a full 32 bits to work with.
Elliott Hughes5f791332011-09-15 17:45:30 -070058 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070059 * The two states of an Object's lock are referred to as "thin" and "fat". A lock may transition
60 * from the "thin" state to the "fat" state and this transition is referred to as inflation. Once
61 * a lock has been inflated it remains in the "fat" state indefinitely.
Elliott Hughes5f791332011-09-15 17:45:30 -070062 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070063 * The lock value itself is stored in mirror::Object::monitor_ and the representation is described
64 * in the LockWord value type.
Elliott Hughes54e7df12011-09-16 11:47:04 -070065 *
Elliott Hughes5f791332011-09-15 17:45:30 -070066 * Monitors provide:
67 * - mutually exclusive access to resources
68 * - a way for multiple threads to wait for notification
69 *
70 * In effect, they fill the role of both mutexes and condition variables.
71 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070072 * Only one thread can own the monitor at any time. There may be several threads waiting on it
73 * (the wait call unlocks it). One or more waiting threads may be getting interrupted or notified
74 * at any given time.
Elliott Hughes5f791332011-09-15 17:45:30 -070075 */
Elliott Hughes54e7df12011-09-16 11:47:04 -070076
Elliott Hughesfc861622011-10-17 17:57:47 -070077uint32_t Monitor::lock_profiling_threshold_ = 0;
Andreas Gamped0210e52017-06-23 13:38:09 -070078uint32_t Monitor::stack_dump_lock_profiling_threshold_ = 0;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070079
Andreas Gamped0210e52017-06-23 13:38:09 -070080void Monitor::Init(uint32_t lock_profiling_threshold,
81 uint32_t stack_dump_lock_profiling_threshold) {
Andreas Gampe5d689142017-10-19 13:03:29 -070082 // It isn't great to always include the debug build fudge factor for command-
83 // line driven arguments, but it's easier to adjust here than in the build.
84 lock_profiling_threshold_ =
85 lock_profiling_threshold * kDebugThresholdFudgeFactor;
86 stack_dump_lock_profiling_threshold_ =
87 stack_dump_lock_profiling_threshold * kDebugThresholdFudgeFactor;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070088}
89
Ian Rogersef7d42f2014-01-06 12:55:46 -080090Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code)
Ian Rogers00f7d0e2012-07-19 15:28:27 -070091 : monitor_lock_("a monitor lock", kMonitorLock),
Ian Rogersd9c4fc92013-10-01 19:45:43 -070092 monitor_contenders_("monitor contenders", monitor_lock_),
Mathieu Chartier46bc7782013-11-12 17:03:02 -080093 num_waiters_(0),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070094 owner_(owner),
Elliott Hughes5f791332011-09-15 17:45:30 -070095 lock_count_(0),
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070096 obj_(GcRoot<mirror::Object>(obj)),
Mathieu Chartier2cebb242015-04-21 16:50:40 -070097 wait_set_(nullptr),
Mathieu Chartierad2541a2013-10-25 10:05:23 -070098 hash_code_(hash_code),
Mathieu Chartier2cebb242015-04-21 16:50:40 -070099 locking_method_(nullptr),
Ian Rogersef7d42f2014-01-06 12:55:46 -0800100 locking_dex_pc_(0),
Andreas Gampe74240812014-04-17 10:35:09 -0700101 monitor_id_(MonitorPool::ComputeMonitorId(this, self)) {
102#ifdef __LP64__
103 DCHECK(false) << "Should not be reached in 64b";
104 next_free_ = nullptr;
105#endif
106 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
107 // with the owner unlocking the thin-lock.
108 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
109 // The identity hash code is set for the life time of the monitor.
110}
111
112Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code,
113 MonitorId id)
114 : monitor_lock_("a monitor lock", kMonitorLock),
115 monitor_contenders_("monitor contenders", monitor_lock_),
116 num_waiters_(0),
117 owner_(owner),
118 lock_count_(0),
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700119 obj_(GcRoot<mirror::Object>(obj)),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700120 wait_set_(nullptr),
Andreas Gampe74240812014-04-17 10:35:09 -0700121 hash_code_(hash_code),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700122 locking_method_(nullptr),
Andreas Gampe74240812014-04-17 10:35:09 -0700123 locking_dex_pc_(0),
124 monitor_id_(id) {
125#ifdef __LP64__
126 next_free_ = nullptr;
127#endif
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700128 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
129 // with the owner unlocking the thin-lock.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800130 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700131 // The identity hash code is set for the life time of the monitor.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700132}
133
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700134int32_t Monitor::GetHashCode() {
135 while (!HasHashCode()) {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700136 if (hash_code_.CompareExchangeWeakRelaxed(0, mirror::Object::GenerateIdentityHashCode())) {
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700137 break;
138 }
139 }
140 DCHECK(HasHashCode());
Ian Rogers3e5cf302014-05-20 16:40:37 -0700141 return hash_code_.LoadRelaxed();
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700142}
143
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700144bool Monitor::Install(Thread* self) {
145 MutexLock mu(self, monitor_lock_); // Uncontended mutex acquisition as monitor isn't yet public.
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700146 CHECK(owner_ == nullptr || owner_ == self || owner_->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700147 // Propagate the lock state.
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700148 LockWord lw(GetObject()->GetLockWord(false));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700149 switch (lw.GetState()) {
150 case LockWord::kThinLocked: {
151 CHECK_EQ(owner_->GetThreadId(), lw.ThinLockOwner());
152 lock_count_ = lw.ThinLockCount();
153 break;
154 }
155 case LockWord::kHashCode: {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700156 CHECK_EQ(hash_code_.LoadRelaxed(), static_cast<int32_t>(lw.GetHashCode()));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700157 break;
158 }
159 case LockWord::kFatLocked: {
160 // The owner_ is suspended but another thread beat us to install a monitor.
161 return false;
162 }
163 case LockWord::kUnlocked: {
164 LOG(FATAL) << "Inflating unlocked lock word";
165 break;
166 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700167 default: {
168 LOG(FATAL) << "Invalid monitor state " << lw.GetState();
169 return false;
170 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700171 }
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700172 LockWord fat(this, lw.GCState());
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700173 // Publish the updated lock word, which may race with other threads.
Hans Boehmb3da36c2016-12-15 13:12:59 -0800174 bool success = GetObject()->CasLockWordWeakRelease(lw, fat);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700175 // Lock profiling.
Mathieu Chartier9728f912013-10-30 09:45:13 -0700176 if (success && owner_ != nullptr && lock_profiling_threshold_ != 0) {
Andreas Gampe6ec8ebd2014-07-25 13:36:56 -0700177 // Do not abort on dex pc errors. This can easily happen when we want to dump a stack trace on
178 // abort.
179 locking_method_ = owner_->GetCurrentMethod(&locking_dex_pc_, false);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700180 }
181 return success;
Elliott Hughes5f791332011-09-15 17:45:30 -0700182}
183
184Monitor::~Monitor() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700185 // Deflated monitors have a null object.
Elliott Hughes5f791332011-09-15 17:45:30 -0700186}
187
Elliott Hughes5f791332011-09-15 17:45:30 -0700188void Monitor::AppendToWaitSet(Thread* thread) {
189 DCHECK(owner_ == Thread::Current());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700190 DCHECK(thread != nullptr);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700191 DCHECK(thread->GetWaitNext() == nullptr) << thread->GetWaitNext();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700192 if (wait_set_ == nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700193 wait_set_ = thread;
194 return;
195 }
196
197 // push_back.
198 Thread* t = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700199 while (t->GetWaitNext() != nullptr) {
200 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700201 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700202 t->SetWaitNext(thread);
Elliott Hughes5f791332011-09-15 17:45:30 -0700203}
204
Elliott Hughes5f791332011-09-15 17:45:30 -0700205void Monitor::RemoveFromWaitSet(Thread *thread) {
206 DCHECK(owner_ == Thread::Current());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700207 DCHECK(thread != nullptr);
208 if (wait_set_ == nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700209 return;
210 }
211 if (wait_set_ == thread) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700212 wait_set_ = thread->GetWaitNext();
213 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700214 return;
215 }
216
217 Thread* t = wait_set_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700218 while (t->GetWaitNext() != nullptr) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700219 if (t->GetWaitNext() == thread) {
220 t->SetWaitNext(thread->GetWaitNext());
221 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700222 return;
223 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700224 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700225 }
226}
227
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700228void Monitor::SetObject(mirror::Object* object) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700229 obj_ = GcRoot<mirror::Object>(object);
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700230}
231
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700232// Note: Adapted from CurrentMethodVisitor in thread.cc. We must not resolve here.
233
234struct NthCallerWithDexPcVisitor FINAL : public StackVisitor {
235 explicit NthCallerWithDexPcVisitor(Thread* thread, size_t frame)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700236 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +0100237 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700238 method_(nullptr),
239 dex_pc_(0),
240 current_frame_number_(0),
241 wanted_frame_number_(frame) {}
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700242 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700243 ArtMethod* m = GetMethod();
244 if (m == nullptr || m->IsRuntimeMethod()) {
245 // Runtime method, upcall, or resolution issue. Skip.
246 return true;
247 }
248
249 // Is this the requested frame?
250 if (current_frame_number_ == wanted_frame_number_) {
251 method_ = m;
252 dex_pc_ = GetDexPc(false /* abort_on_error*/);
253 return false;
254 }
255
256 // Look for more.
257 current_frame_number_++;
258 return true;
259 }
260
261 ArtMethod* method_;
262 uint32_t dex_pc_;
263
264 private:
265 size_t current_frame_number_;
266 const size_t wanted_frame_number_;
267};
268
269// This function is inlined and just helps to not have the VLOG and ATRACE check at all the
270// potential tracing points.
271void Monitor::AtraceMonitorLock(Thread* self, mirror::Object* obj, bool is_wait) {
272 if (UNLIKELY(VLOG_IS_ON(systrace_lock_logging) && ATRACE_ENABLED())) {
273 AtraceMonitorLockImpl(self, obj, is_wait);
274 }
275}
276
277void Monitor::AtraceMonitorLockImpl(Thread* self, mirror::Object* obj, bool is_wait) {
278 // Wait() requires a deeper call stack to be useful. Otherwise you'll see "Waiting at
279 // Object.java". Assume that we'll wait a nontrivial amount, so it's OK to do a longer
280 // stack walk than if !is_wait.
281 NthCallerWithDexPcVisitor visitor(self, is_wait ? 1U : 0U);
282 visitor.WalkStack(false);
283 const char* prefix = is_wait ? "Waiting on " : "Locking ";
284
285 const char* filename;
286 int32_t line_number;
287 TranslateLocation(visitor.method_, visitor.dex_pc_, &filename, &line_number);
288
289 // It would be nice to have a stable "ID" for the object here. However, the only stable thing
290 // would be the identity hashcode. But we cannot use IdentityHashcode here: For one, there are
291 // times when it is unsafe to make that call (see stack dumping for an explanation). More
292 // importantly, we would have to give up on thin-locking when adding systrace locks, as the
293 // identity hashcode is stored in the lockword normally (so can't be used with thin-locks).
294 //
295 // Because of thin-locks we also cannot use the monitor id (as there is no monitor). Monitor ids
296 // also do not have to be stable, as the monitor may be deflated.
297 std::string tmp = StringPrintf("%s %d at %s:%d",
298 prefix,
299 (obj == nullptr ? -1 : static_cast<int32_t>(reinterpret_cast<uintptr_t>(obj))),
300 (filename != nullptr ? filename : "null"),
301 line_number);
302 ATRACE_BEGIN(tmp.c_str());
303}
304
305void Monitor::AtraceMonitorUnlock() {
306 if (UNLIKELY(VLOG_IS_ON(systrace_lock_logging))) {
307 ATRACE_END();
308 }
309}
310
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700311std::string Monitor::PrettyContentionInfo(const std::string& owner_name,
312 pid_t owner_tid,
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700313 ArtMethod* owners_method,
314 uint32_t owners_dex_pc,
315 size_t num_waiters) {
Hiroshi Yamauchi71cd68d2017-01-25 18:28:12 -0800316 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700317 const char* owners_filename;
Goran Jakovljevic49c882b2016-04-19 10:27:21 +0200318 int32_t owners_line_number = 0;
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700319 if (owners_method != nullptr) {
320 TranslateLocation(owners_method, owners_dex_pc, &owners_filename, &owners_line_number);
321 }
322 std::ostringstream oss;
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700323 oss << "monitor contention with owner " << owner_name << " (" << owner_tid << ")";
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700324 if (owners_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700325 oss << " at " << owners_method->PrettyMethod();
Mathieu Chartier36891fe2016-04-28 17:21:08 -0700326 oss << "(" << owners_filename << ":" << owners_line_number << ")";
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700327 }
328 oss << " waiters=" << num_waiters;
329 return oss.str();
330}
331
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700332bool Monitor::TryLockLocked(Thread* self) {
333 if (owner_ == nullptr) { // Unowned.
334 owner_ = self;
335 CHECK_EQ(lock_count_, 0);
336 // When debugging, save the current monitor holder for future
337 // acquisition failures to use in sampled logging.
338 if (lock_profiling_threshold_ != 0) {
339 locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
340 }
341 } else if (owner_ == self) { // Recursive.
342 lock_count_++;
343 } else {
344 return false;
345 }
346 AtraceMonitorLock(self, GetObject(), false /* is_wait */);
347 return true;
348}
349
350bool Monitor::TryLock(Thread* self) {
351 MutexLock mu(self, monitor_lock_);
352 return TryLockLocked(self);
353}
354
Alex Light77fee872017-09-05 14:51:49 -0700355// Asserts that a mutex isn't held when the class comes into and out of scope.
356class ScopedAssertNotHeld {
357 public:
358 ScopedAssertNotHeld(Thread* self, Mutex& mu) : self_(self), mu_(mu) {
359 mu_.AssertNotHeld(self_);
360 }
361
362 ~ScopedAssertNotHeld() {
363 mu_.AssertNotHeld(self_);
364 }
365
366 private:
367 Thread* const self_;
368 Mutex& mu_;
369 DISALLOW_COPY_AND_ASSIGN(ScopedAssertNotHeld);
370};
371
372template <LockReason reason>
Elliott Hughes5f791332011-09-15 17:45:30 -0700373void Monitor::Lock(Thread* self) {
Alex Light77fee872017-09-05 14:51:49 -0700374 ScopedAssertNotHeld sanh(self, monitor_lock_);
375 bool called_monitors_callback = false;
376 monitor_lock_.Lock(self);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700377 while (true) {
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700378 if (TryLockLocked(self)) {
Alex Light77fee872017-09-05 14:51:49 -0700379 break;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700380 }
381 // Contended.
382 const bool log_contention = (lock_profiling_threshold_ != 0);
Xin Guanb894a192014-08-22 11:55:37 -0500383 uint64_t wait_start_ms = log_contention ? MilliTime() : 0;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700384 ArtMethod* owners_method = locking_method_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700385 uint32_t owners_dex_pc = locking_dex_pc_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700386 // Do this before releasing the lock so that we don't get deflated.
Mathieu Chartierb9001ab2014-10-03 13:28:46 -0700387 size_t num_waiters = num_waiters_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700388 ++num_waiters_;
Andreas Gampe2702d562017-02-06 09:48:00 -0800389
390 // If systrace logging is enabled, first look at the lock owner. Acquiring the monitor's
391 // lock and then re-acquiring the mutator lock can deadlock.
392 bool started_trace = false;
393 if (ATRACE_ENABLED()) {
394 if (owner_ != nullptr) { // Did the owner_ give the lock up?
395 std::ostringstream oss;
396 std::string name;
397 owner_->GetThreadName(name);
398 oss << PrettyContentionInfo(name,
399 owner_->GetTid(),
400 owners_method,
401 owners_dex_pc,
402 num_waiters);
403 // Add info for contending thread.
404 uint32_t pc;
405 ArtMethod* m = self->GetCurrentMethod(&pc);
406 const char* filename;
407 int32_t line_number;
408 TranslateLocation(m, pc, &filename, &line_number);
409 oss << " blocking from "
410 << ArtMethod::PrettyMethod(m) << "(" << (filename != nullptr ? filename : "null")
411 << ":" << line_number << ")";
412 ATRACE_BEGIN(oss.str().c_str());
413 started_trace = true;
414 }
415 }
416
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700417 monitor_lock_.Unlock(self); // Let go of locks in order.
Alex Light77fee872017-09-05 14:51:49 -0700418 // Call the contended locking cb once and only once. Also only call it if we are locking for
419 // the first time, not during a Wait wakeup.
420 if (reason == LockReason::kForLock && !called_monitors_callback) {
421 called_monitors_callback = true;
422 Runtime::Current()->GetRuntimeCallbacks()->MonitorContendedLocking(this);
423 }
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700424 self->SetMonitorEnterObject(GetObject());
Elliott Hughes5f791332011-09-15 17:45:30 -0700425 {
Hiroshi Yamauchi71cd68d2017-01-25 18:28:12 -0800426 ScopedThreadSuspension tsc(self, kBlocked); // Change to blocked and give up mutator_lock_.
Andreas Gampe2702d562017-02-06 09:48:00 -0800427 uint32_t original_owner_thread_id = 0u;
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700428 {
429 // Reacquire monitor_lock_ without mutator_lock_ for Wait.
430 MutexLock mu2(self, monitor_lock_);
431 if (owner_ != nullptr) { // Did the owner_ give the lock up?
432 original_owner_thread_id = owner_->GetThreadId();
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700433 monitor_contenders_.Wait(self); // Still contended so wait.
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800434 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700435 }
436 if (original_owner_thread_id != 0u) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700437 // Woken from contention.
438 if (log_contention) {
Andreas Gampe111b1092017-06-22 20:28:23 -0700439 uint64_t wait_ms = MilliTime() - wait_start_ms;
440 uint32_t sample_percent;
441 if (wait_ms >= lock_profiling_threshold_) {
442 sample_percent = 100;
443 } else {
444 sample_percent = 100 * wait_ms / lock_profiling_threshold_;
445 }
446 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
447 // Reacquire mutator_lock_ for logging.
448 ScopedObjectAccess soa(self);
Andreas Gampe111b1092017-06-22 20:28:23 -0700449
Andreas Gamped0210e52017-06-23 13:38:09 -0700450 bool owner_alive = false;
451 pid_t original_owner_tid = 0;
452 std::string original_owner_name;
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700453
Andreas Gamped0210e52017-06-23 13:38:09 -0700454 const bool should_dump_stacks = stack_dump_lock_profiling_threshold_ > 0 &&
455 wait_ms > stack_dump_lock_profiling_threshold_;
456 std::string owner_stack_dump;
Andreas Gampe111b1092017-06-22 20:28:23 -0700457
Andreas Gamped0210e52017-06-23 13:38:09 -0700458 // Acquire thread-list lock to find thread and keep it from dying until we've got all
459 // the info we need.
460 {
461 MutexLock mu2(Thread::Current(), *Locks::thread_list_lock_);
462
463 // Re-find the owner in case the thread got killed.
464 Thread* original_owner = Runtime::Current()->GetThreadList()->FindThreadByThreadId(
465 original_owner_thread_id);
466
467 if (original_owner != nullptr) {
468 owner_alive = true;
469 original_owner_tid = original_owner->GetTid();
470 original_owner->GetThreadName(original_owner_name);
471
472 if (should_dump_stacks) {
473 // Very long contention. Dump stacks.
474 struct CollectStackTrace : public Closure {
475 void Run(art::Thread* thread) OVERRIDE
476 REQUIRES_SHARED(art::Locks::mutator_lock_) {
477 thread->DumpJavaStack(oss);
478 }
479
480 std::ostringstream oss;
481 };
482 CollectStackTrace owner_trace;
483 original_owner->RequestSynchronousCheckpoint(&owner_trace);
484 owner_stack_dump = owner_trace.oss.str();
485 }
486 }
487 // This is all the data we need. Now drop the thread-list lock, it's OK for the
488 // owner to go away now.
489 }
490
491 // If we found the owner (and thus have owner data), go and log now.
492 if (owner_alive) {
493 // Give the detailed traces for really long contention.
494 if (should_dump_stacks) {
495 // This must be here (and not above) because we cannot hold the thread-list lock
496 // while running the checkpoint.
497 std::ostringstream self_trace_oss;
498 self->DumpJavaStack(self_trace_oss);
499
500 uint32_t pc;
501 ArtMethod* m = self->GetCurrentMethod(&pc);
502
503 LOG(WARNING) << "Long "
504 << PrettyContentionInfo(original_owner_name,
505 original_owner_tid,
506 owners_method,
507 owners_dex_pc,
508 num_waiters)
509 << " in " << ArtMethod::PrettyMethod(m) << " for "
510 << PrettyDuration(MsToNs(wait_ms)) << "\n"
511 << "Current owner stack:\n" << owner_stack_dump
512 << "Contender stack:\n" << self_trace_oss.str();
513 } else if (wait_ms > kLongWaitMs && owners_method != nullptr) {
Mathieu Chartier36891fe2016-04-28 17:21:08 -0700514 uint32_t pc;
515 ArtMethod* m = self->GetCurrentMethod(&pc);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700516 // TODO: We should maybe check that original_owner is still a live thread.
517 LOG(WARNING) << "Long "
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700518 << PrettyContentionInfo(original_owner_name,
519 original_owner_tid,
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700520 owners_method,
521 owners_dex_pc,
522 num_waiters)
David Sehr709b0702016-10-13 09:12:37 -0700523 << " in " << ArtMethod::PrettyMethod(m) << " for "
524 << PrettyDuration(MsToNs(wait_ms));
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700525 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700526 LogContentionEvent(self,
Alex Light77fee872017-09-05 14:51:49 -0700527 wait_ms,
528 sample_percent,
529 owners_method,
530 owners_dex_pc);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700531 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700532 }
533 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700534 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700535 }
Andreas Gampe2702d562017-02-06 09:48:00 -0800536 if (started_trace) {
537 ATRACE_END();
538 }
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700539 self->SetMonitorEnterObject(nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700540 monitor_lock_.Lock(self); // Reacquire locks in order.
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700541 --num_waiters_;
Elliott Hughesfc861622011-10-17 17:57:47 -0700542 }
Alex Light77fee872017-09-05 14:51:49 -0700543 monitor_lock_.Unlock(self);
544 // We need to pair this with a single contended locking call. NB we match the RI behavior and call
545 // this even if MonitorEnter failed.
546 if (called_monitors_callback) {
547 CHECK(reason == LockReason::kForLock);
548 Runtime::Current()->GetRuntimeCallbacks()->MonitorContendedLocked(this);
549 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700550}
551
Alex Light77fee872017-09-05 14:51:49 -0700552template void Monitor::Lock<LockReason::kForLock>(Thread* self);
553template void Monitor::Lock<LockReason::kForWait>(Thread* self);
554
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800555static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
556 __attribute__((format(printf, 1, 2)));
557
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700558static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700559 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800560 va_list args;
561 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800562 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000563 self->ThrowNewExceptionV("Ljava/lang/IllegalMonitorStateException;", fmt, args);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700564 if (!Runtime::Current()->IsStarted() || VLOG_IS_ON(monitor)) {
Brian Carlstrom64277f32012-03-26 23:53:34 -0700565 std::ostringstream ss;
Ian Rogers62d6c772013-02-27 08:32:07 -0800566 self->Dump(ss);
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700567 LOG(Runtime::Current()->IsStarted() ? ::android::base::INFO : ::android::base::ERROR)
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000568 << self->GetException()->Dump() << "\n" << ss.str();
Brian Carlstrom64277f32012-03-26 23:53:34 -0700569 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800570 va_end(args);
571}
572
Elliott Hughesd4237412012-02-21 11:24:45 -0800573static std::string ThreadToString(Thread* thread) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700574 if (thread == nullptr) {
575 return "nullptr";
Elliott Hughesd4237412012-02-21 11:24:45 -0800576 }
577 std::ostringstream oss;
578 // TODO: alternatively, we could just return the thread's name.
579 oss << *thread;
580 return oss.str();
581}
582
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700583void Monitor::FailedUnlock(mirror::Object* o,
584 uint32_t expected_owner_thread_id,
585 uint32_t found_owner_thread_id,
Elliott Hughesffb465f2012-03-01 18:46:05 -0800586 Monitor* monitor) {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700587 // Acquire thread list lock so threads won't disappear from under us.
Elliott Hughesffb465f2012-03-01 18:46:05 -0800588 std::string current_owner_string;
589 std::string expected_owner_string;
590 std::string found_owner_string;
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700591 uint32_t current_owner_thread_id = 0u;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800592 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700593 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700594 ThreadList* const thread_list = Runtime::Current()->GetThreadList();
595 Thread* expected_owner = thread_list->FindThreadByThreadId(expected_owner_thread_id);
596 Thread* found_owner = thread_list->FindThreadByThreadId(found_owner_thread_id);
597
Elliott Hughesffb465f2012-03-01 18:46:05 -0800598 // Re-read owner now that we hold lock.
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700599 Thread* current_owner = (monitor != nullptr) ? monitor->GetOwner() : nullptr;
600 if (current_owner != nullptr) {
601 current_owner_thread_id = current_owner->GetThreadId();
602 }
Elliott Hughesffb465f2012-03-01 18:46:05 -0800603 // Get short descriptions of the threads involved.
604 current_owner_string = ThreadToString(current_owner);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700605 expected_owner_string = expected_owner != nullptr ? ThreadToString(expected_owner) : "unnamed";
606 found_owner_string = found_owner != nullptr ? ThreadToString(found_owner) : "unnamed";
Elliott Hughesffb465f2012-03-01 18:46:05 -0800607 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700608
609 if (current_owner_thread_id == 0u) {
610 if (found_owner_thread_id == 0u) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800611 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
612 " on thread '%s'",
David Sehr709b0702016-10-13 09:12:37 -0700613 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800614 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800615 } else {
616 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800617 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
618 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800619 found_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700620 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800621 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800622 }
623 } else {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700624 if (found_owner_thread_id == 0u) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800625 // Race: originally there was no owner, there is now
626 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
627 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800628 current_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700629 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800630 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800631 } else {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700632 if (found_owner_thread_id != current_owner_thread_id) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800633 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800634 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
635 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800636 found_owner_string.c_str(),
637 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 } else {
641 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
642 " on thread '%s",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800643 current_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700644 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800645 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800646 }
647 }
648 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700649}
650
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700651bool Monitor::Unlock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700652 DCHECK(self != nullptr);
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700653 uint32_t owner_thread_id = 0u;
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700654 {
655 MutexLock mu(self, monitor_lock_);
656 Thread* owner = owner_;
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700657 if (owner != nullptr) {
658 owner_thread_id = owner->GetThreadId();
659 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700660 if (owner == self) {
661 // We own the monitor, so nobody else can be in here.
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700662 AtraceMonitorUnlock();
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700663 if (lock_count_ == 0) {
664 owner_ = nullptr;
665 locking_method_ = nullptr;
666 locking_dex_pc_ = 0;
667 // Wake a contender.
668 monitor_contenders_.Signal(self);
669 } else {
670 --lock_count_;
671 }
672 return true;
Elliott Hughes5f791332011-09-15 17:45:30 -0700673 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700674 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700675 // We don't own this, so we're not allowed to unlock it.
676 // The JNI spec says that we should throw IllegalMonitorStateException in this case.
677 FailedUnlock(GetObject(), self->GetThreadId(), owner_thread_id, this);
678 return false;
Elliott Hughes5f791332011-09-15 17:45:30 -0700679}
680
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800681void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
682 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700683 DCHECK(self != nullptr);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800684 DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
Elliott Hughes5f791332011-09-15 17:45:30 -0700685
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700686 monitor_lock_.Lock(self);
687
Elliott Hughes5f791332011-09-15 17:45:30 -0700688 // Make sure that we hold the lock.
689 if (owner_ != self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700690 monitor_lock_.Unlock(self);
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700691 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700692 return;
693 }
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800694
Elliott Hughesdf42c482013-01-09 12:49:02 -0800695 // We need to turn a zero-length timed wait into a regular wait because
696 // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
697 if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
698 why = kWaiting;
699 }
700
Elliott Hughes5f791332011-09-15 17:45:30 -0700701 // Enforce the timeout range.
702 if (ms < 0 || ns < 0 || ns > 999999) {
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700703 monitor_lock_.Unlock(self);
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000704 self->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
Ian Rogersef7d42f2014-01-06 12:55:46 -0800705 "timeout arguments out of range: ms=%" PRId64 " ns=%d", ms, ns);
Elliott Hughes5f791332011-09-15 17:45:30 -0700706 return;
707 }
708
Elliott Hughes5f791332011-09-15 17:45:30 -0700709 /*
710 * Add ourselves to the set of threads waiting on this monitor, and
711 * release our hold. We need to let it go even if we're a few levels
712 * deep in a recursive lock, and we need to restore that later.
713 *
714 * We append to the wait set ahead of clearing the count and owner
715 * fields so the subroutine can check that the calling thread owns
716 * the monitor. Aside from that, the order of member updates is
717 * not order sensitive as we hold the pthread mutex.
718 */
719 AppendToWaitSet(self);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700720 ++num_waiters_;
Ian Rogers0399dde2012-06-06 17:09:28 -0700721 int prev_lock_count = lock_count_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700722 lock_count_ = 0;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700723 owner_ = nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700724 ArtMethod* saved_method = locking_method_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700725 locking_method_ = nullptr;
Ian Rogers0399dde2012-06-06 17:09:28 -0700726 uintptr_t saved_dex_pc = locking_dex_pc_;
727 locking_dex_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700728
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700729 AtraceMonitorUnlock(); // For the implict Unlock() just above. This will only end the deepest
730 // nesting, but that is enough for the visualization, and corresponds to
731 // the single Lock() we do afterwards.
732 AtraceMonitorLock(self, GetObject(), true /* is_wait */);
733
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800734 bool was_interrupted = false;
Alex Light77fee872017-09-05 14:51:49 -0700735 bool timed_out = false;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700736 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700737 // Update thread state. If the GC wakes up, it'll ignore us, knowing
738 // that we won't touch any references in this state, and we'll check
739 // our suspend mode before we transition out.
740 ScopedThreadSuspension sts(self, why);
741
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700742 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700743 MutexLock mu(self, *self->GetWaitMutex());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700744
745 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700746 // non-null a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700747 // up.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700748 DCHECK(self->GetWaitMonitor() == nullptr);
749 self->SetWaitMonitor(this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700750
751 // Release the monitor lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700752 monitor_contenders_.Signal(self);
753 monitor_lock_.Unlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700754
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800755 // Handle the case where the thread was interrupted before we called wait().
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000756 if (self->IsInterrupted()) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800757 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700758 } else {
759 // Wait for a notification or a timeout to occur.
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800760 if (why == kWaiting) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700761 self->GetWaitConditionVariable()->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700762 } else {
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800763 DCHECK(why == kTimedWaiting || why == kSleeping) << why;
Alex Light77fee872017-09-05 14:51:49 -0700764 timed_out = self->GetWaitConditionVariable()->TimedWait(self, ms, ns);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700765 }
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000766 was_interrupted = self->IsInterrupted();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700767 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700768 }
769
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800770 {
771 // We reset the thread's wait_monitor_ field after transitioning back to runnable so
772 // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
773 // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
774 // are waiting on "null".)
Ian Rogersdd7624d2014-03-14 17:43:00 -0700775 MutexLock mu(self, *self->GetWaitMutex());
776 DCHECK(self->GetWaitMonitor() != nullptr);
777 self->SetWaitMonitor(nullptr);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800778 }
779
Mathieu Chartierdaed5d82016-03-10 10:49:35 -0800780 // Allocate the interrupted exception not holding the monitor lock since it may cause a GC.
781 // If the GC requires acquiring the monitor for enqueuing cleared references, this would
782 // cause a deadlock if the monitor is held.
783 if (was_interrupted && interruptShouldThrow) {
784 /*
785 * We were interrupted while waiting, or somebody interrupted an
786 * un-interruptible thread earlier and we're bailing out immediately.
787 *
788 * The doc sayeth: "The interrupted status of the current thread is
789 * cleared when this exception is thrown."
790 */
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000791 self->SetInterrupted(false);
Mathieu Chartierdaed5d82016-03-10 10:49:35 -0800792 self->ThrowNewException("Ljava/lang/InterruptedException;", nullptr);
793 }
794
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700795 AtraceMonitorUnlock(); // End Wait().
796
Alex Light77fee872017-09-05 14:51:49 -0700797 // We just slept, tell the runtime callbacks about this.
798 Runtime::Current()->GetRuntimeCallbacks()->MonitorWaitFinished(this, timed_out);
799
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700800 // Re-acquire the monitor and lock.
Alex Light77fee872017-09-05 14:51:49 -0700801 Lock<LockReason::kForWait>(self);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700802 monitor_lock_.Lock(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700803 self->GetWaitMutex()->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700804
Elliott Hughes5f791332011-09-15 17:45:30 -0700805 /*
806 * We remove our thread from wait set after restoring the count
807 * and owner fields so the subroutine can check that the calling
808 * thread owns the monitor. Aside from that, the order of member
809 * updates is not order sensitive as we hold the pthread mutex.
810 */
811 owner_ = self;
Ian Rogers0399dde2012-06-06 17:09:28 -0700812 lock_count_ = prev_lock_count;
813 locking_method_ = saved_method;
814 locking_dex_pc_ = saved_dex_pc;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700815 --num_waiters_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700816 RemoveFromWaitSet(self);
817
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700818 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700819}
820
821void Monitor::Notify(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700822 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700823 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700824 // Make sure that we hold the lock.
825 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800826 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700827 return;
828 }
829 // Signal the first waiting thread in the wait set.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700830 while (wait_set_ != nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700831 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700832 wait_set_ = thread->GetWaitNext();
833 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700834
835 // Check to see if the thread is still waiting.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800836 MutexLock wait_mu(self, *thread->GetWaitMutex());
Ian Rogersdd7624d2014-03-14 17:43:00 -0700837 if (thread->GetWaitMonitor() != nullptr) {
838 thread->GetWaitConditionVariable()->Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700839 return;
840 }
841 }
842}
843
844void Monitor::NotifyAll(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700845 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700846 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700847 // Make sure that we hold the lock.
848 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800849 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700850 return;
851 }
852 // Signal all threads in the wait set.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700853 while (wait_set_ != nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700854 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700855 wait_set_ = thread->GetWaitNext();
856 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700857 thread->Notify();
858 }
859}
860
Mathieu Chartier590fee92013-09-13 13:46:47 -0700861bool Monitor::Deflate(Thread* self, mirror::Object* obj) {
862 DCHECK(obj != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700863 // Don't need volatile since we only deflate with mutators suspended.
864 LockWord lw(obj->GetLockWord(false));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700865 // If the lock isn't an inflated monitor, then we don't need to deflate anything.
866 if (lw.GetState() == LockWord::kFatLocked) {
867 Monitor* monitor = lw.FatLockMonitor();
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700868 DCHECK(monitor != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700869 MutexLock mu(self, monitor->monitor_lock_);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700870 // Can't deflate if we have anybody waiting on the CV.
871 if (monitor->num_waiters_ > 0) {
872 return false;
873 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700874 Thread* owner = monitor->owner_;
875 if (owner != nullptr) {
876 // Can't deflate if we are locked and have a hash code.
877 if (monitor->HasHashCode()) {
878 return false;
879 }
880 // Can't deflate if our lock count is too high.
Mathieu Chartier1cf194f2016-11-01 20:13:24 -0700881 if (static_cast<uint32_t>(monitor->lock_count_) > LockWord::kThinLockMaxCount) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700882 return false;
883 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700884 // Deflate to a thin lock.
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700885 LockWord new_lw = LockWord::FromThinLockId(owner->GetThreadId(),
886 monitor->lock_count_,
887 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 Chartier4d7f61d2014-04-17 14:43:39 -0700890 VLOG(monitor) << "Deflated " << obj << " to thin lock " << owner->GetTid() << " / "
891 << monitor->lock_count_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700892 } else if (monitor->HasHashCode()) {
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700893 LockWord new_lw = LockWord::FromHashCode(monitor->GetHashCode(), 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 hash monitor " << monitor->GetHashCode();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700897 } else {
898 // No lock and no hash, just put an empty lock word inside the object.
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700899 LockWord new_lw = LockWord::FromDefault(lw.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800900 // Assume no concurrent read barrier state changes as mutators are suspended.
901 obj->SetLockWord(new_lw, false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700902 VLOG(monitor) << "Deflated" << obj << " to empty lock word";
Mathieu Chartier590fee92013-09-13 13:46:47 -0700903 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700904 // 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 -0700905 // next GC.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700906 monitor->obj_ = GcRoot<mirror::Object>(nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700907 }
908 return true;
909}
910
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700911void Monitor::Inflate(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code) {
Andreas Gampe74240812014-04-17 10:35:09 -0700912 DCHECK(self != nullptr);
913 DCHECK(obj != nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700914 // Allocate and acquire a new monitor.
Andreas Gampe74240812014-04-17 10:35:09 -0700915 Monitor* m = MonitorPool::CreateMonitor(self, owner, obj, hash_code);
916 DCHECK(m != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700917 if (m->Install(self)) {
Haifeng Li86ab7912014-05-16 10:47:59 +0800918 if (owner != nullptr) {
919 VLOG(monitor) << "monitor: thread" << owner->GetThreadId()
Andreas Gampe74240812014-04-17 10:35:09 -0700920 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800921 } else {
922 VLOG(monitor) << "monitor: Inflate with hashcode " << hash_code
Andreas Gampe74240812014-04-17 10:35:09 -0700923 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800924 }
Andreas Gampe74240812014-04-17 10:35:09 -0700925 Runtime::Current()->GetMonitorList()->Add(m);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700926 CHECK_EQ(obj->GetLockWord(true).GetState(), LockWord::kFatLocked);
Andreas Gampe74240812014-04-17 10:35:09 -0700927 } else {
928 MonitorPool::ReleaseMonitor(self, m);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700929 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700930}
931
Mathieu Chartier0cd81352014-05-22 16:48:55 -0700932void Monitor::InflateThinLocked(Thread* self, Handle<mirror::Object> obj, LockWord lock_word,
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700933 uint32_t hash_code) {
934 DCHECK_EQ(lock_word.GetState(), LockWord::kThinLocked);
935 uint32_t owner_thread_id = lock_word.ThinLockOwner();
936 if (owner_thread_id == self->GetThreadId()) {
937 // We own the monitor, we can easily inflate it.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700938 Inflate(self, self, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700939 } else {
940 ThreadList* thread_list = Runtime::Current()->GetThreadList();
941 // Suspend the owner, inflate. First change to blocked and give up mutator_lock_.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700942 self->SetMonitorEnterObject(obj.Get());
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700943 bool timed_out;
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700944 Thread* owner;
945 {
Alex Light77fee872017-09-05 14:51:49 -0700946 ScopedThreadSuspension sts(self, kWaitingForLockInflation);
Alex Light46f93402017-06-29 11:59:50 -0700947 owner = thread_list->SuspendThreadByThreadId(owner_thread_id,
948 SuspendReason::kInternal,
949 &timed_out);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700950 }
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700951 if (owner != nullptr) {
952 // We succeeded in suspending the thread, check the lock's status didn't change.
953 lock_word = obj->GetLockWord(true);
954 if (lock_word.GetState() == LockWord::kThinLocked &&
955 lock_word.ThinLockOwner() == owner_thread_id) {
956 // Go ahead and inflate the lock.
957 Inflate(self, owner, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700958 }
Alex Light88fd7202017-06-30 08:31:59 -0700959 bool resumed = thread_list->Resume(owner, SuspendReason::kInternal);
960 DCHECK(resumed);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700961 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700962 self->SetMonitorEnterObject(nullptr);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700963 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700964}
965
Ian Rogers719d1a32014-03-06 12:13:39 -0800966// Fool annotalysis into thinking that the lock on obj is acquired.
967static mirror::Object* FakeLock(mirror::Object* obj)
968 EXCLUSIVE_LOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
969 return obj;
970}
971
972// Fool annotalysis into thinking that the lock on obj is release.
973static mirror::Object* FakeUnlock(mirror::Object* obj)
974 UNLOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
975 return obj;
976}
977
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700978mirror::Object* Monitor::MonitorEnter(Thread* self, mirror::Object* obj, bool trylock) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700979 DCHECK(self != nullptr);
980 DCHECK(obj != nullptr);
Mathieu Chartier2d096c92015-10-12 16:18:20 -0700981 self->AssertThreadSuspensionIsAllowable();
Ian Rogers719d1a32014-03-06 12:13:39 -0800982 obj = FakeLock(obj);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700983 uint32_t thread_id = self->GetThreadId();
984 size_t contention_count = 0;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700985 StackHandleScope<1> hs(self);
986 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700987 while (true) {
Hans Boehmb3da36c2016-12-15 13:12:59 -0800988 // We initially read the lockword with ordinary Java/relaxed semantics. When stronger
989 // semantics are needed, we address it below. Since GetLockWord bottoms out to a relaxed load,
990 // we can fix it later, in an infrequently executed case, with a fence.
991 LockWord lock_word = h_obj->GetLockWord(false);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700992 switch (lock_word.GetState()) {
993 case LockWord::kUnlocked: {
Hans Boehmb3da36c2016-12-15 13:12:59 -0800994 // No ordering required for preceding lockword read, since we retest.
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700995 LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0, lock_word.GCState()));
Hans Boehmb3da36c2016-12-15 13:12:59 -0800996 if (h_obj->CasLockWordWeakAcquire(lock_word, thin_locked)) {
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700997 AtraceMonitorLock(self, h_obj.Get(), false /* is_wait */);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700998 return h_obj.Get(); // Success!
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700999 }
1000 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -07001001 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001002 case LockWord::kThinLocked: {
1003 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1004 if (owner_thread_id == thread_id) {
Hans Boehmb3da36c2016-12-15 13:12:59 -08001005 // No ordering required for initial lockword read.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001006 // We own the lock, increase the recursion count.
1007 uint32_t new_count = lock_word.ThinLockCount() + 1;
1008 if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001009 LockWord thin_locked(LockWord::FromThinLockId(thread_id,
1010 new_count,
1011 lock_word.GCState()));
Hans Boehmb3da36c2016-12-15 13:12:59 -08001012 // Only this thread pays attention to the count. Thus there is no need for stronger
1013 // than relaxed memory ordering.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001014 if (!kUseReadBarrier) {
Hans Boehmb3da36c2016-12-15 13:12:59 -08001015 h_obj->SetLockWord(thin_locked, false /* volatile */);
Andreas Gampec7ed09b2016-04-25 20:08:55 -07001016 AtraceMonitorLock(self, h_obj.Get(), false /* is_wait */);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001017 return h_obj.Get(); // Success!
1018 } else {
1019 // Use CAS to preserve the read barrier state.
Hans Boehmb3da36c2016-12-15 13:12:59 -08001020 if (h_obj->CasLockWordWeakRelaxed(lock_word, thin_locked)) {
Andreas Gampec7ed09b2016-04-25 20:08:55 -07001021 AtraceMonitorLock(self, h_obj.Get(), false /* is_wait */);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001022 return h_obj.Get(); // Success!
1023 }
1024 }
1025 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -07001026 } else {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001027 // We'd overflow the recursion count, so inflate the monitor.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001028 InflateThinLocked(self, h_obj, lock_word, 0);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001029 }
1030 } else {
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07001031 if (trylock) {
1032 return nullptr;
1033 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001034 // Contention.
1035 contention_count++;
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001036 Runtime* runtime = Runtime::Current();
Hans Boehmb3da36c2016-12-15 13:12:59 -08001037 if (contention_count <= runtime->GetMaxSpinsBeforeThinLockInflation()) {
Alex Light77fee872017-09-05 14:51:49 -07001038 // TODO: Consider switching the thread state to kWaitingForLockInflation when we are
1039 // yielding. Use sched_yield instead of NanoSleep since NanoSleep can wait much longer
1040 // than the parameter you pass in. This can cause thread suspension to take excessively
1041 // long and make long pauses. See b/16307460.
Hans Boehmb3da36c2016-12-15 13:12:59 -08001042 // TODO: We should literally spin first, without sched_yield. Sched_yield either does
1043 // nothing (at significant expense), or guarantees that we wait at least microseconds.
1044 // If the owner is running, I would expect the median lock hold time to be hundreds
1045 // of nanoseconds or less.
Mathieu Chartier251755c2014-07-15 18:10:25 -07001046 sched_yield();
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001047 } else {
1048 contention_count = 0;
Hans Boehmb3da36c2016-12-15 13:12:59 -08001049 // No ordering required for initial lockword read. Install rereads it anyway.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001050 InflateThinLocked(self, h_obj, lock_word, 0);
Elliott Hughes5f791332011-09-15 17:45:30 -07001051 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001052 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001053 continue; // Start from the beginning.
Elliott Hughes5f791332011-09-15 17:45:30 -07001054 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001055 case LockWord::kFatLocked: {
Hans Boehmb3da36c2016-12-15 13:12:59 -08001056 // We should have done an acquire read of the lockword initially, to ensure
1057 // visibility of the monitor data structure. Use an explicit fence instead.
1058 QuasiAtomic::ThreadFenceAcquire();
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001059 Monitor* mon = lock_word.FatLockMonitor();
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07001060 if (trylock) {
1061 return mon->TryLock(self) ? h_obj.Get() : nullptr;
1062 } else {
1063 mon->Lock(self);
1064 return h_obj.Get(); // Success!
1065 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001066 }
Ian Rogers719d1a32014-03-06 12:13:39 -08001067 case LockWord::kHashCode:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001068 // Inflate with the existing hashcode.
Hans Boehmb3da36c2016-12-15 13:12:59 -08001069 // Again no ordering required for initial lockword read, since we don't rely
1070 // on the visibility of any prior computation.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001071 Inflate(self, nullptr, h_obj.Get(), lock_word.GetHashCode());
Ian Rogers719d1a32014-03-06 12:13:39 -08001072 continue; // Start from the beginning.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001073 default: {
1074 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Andreas Gampec7ed09b2016-04-25 20:08:55 -07001075 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001076 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001077 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001078 }
1079}
1080
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001081bool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001082 DCHECK(self != nullptr);
1083 DCHECK(obj != nullptr);
Mathieu Chartier2d096c92015-10-12 16:18:20 -07001084 self->AssertThreadSuspensionIsAllowable();
Ian Rogers719d1a32014-03-06 12:13:39 -08001085 obj = FakeUnlock(obj);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001086 StackHandleScope<1> hs(self);
1087 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001088 while (true) {
1089 LockWord lock_word = obj->GetLockWord(true);
1090 switch (lock_word.GetState()) {
1091 case LockWord::kHashCode:
1092 // Fall-through.
1093 case LockWord::kUnlocked:
Mathieu Chartier61b3cd42016-04-18 11:43:29 -07001094 FailedUnlock(h_obj.Get(), self->GetThreadId(), 0u, nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001095 return false; // Failure.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001096 case LockWord::kThinLocked: {
1097 uint32_t thread_id = self->GetThreadId();
1098 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1099 if (owner_thread_id != thread_id) {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -07001100 FailedUnlock(h_obj.Get(), thread_id, owner_thread_id, nullptr);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001101 return false; // Failure.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001102 } else {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001103 // We own the lock, decrease the recursion count.
1104 LockWord new_lw = LockWord::Default();
1105 if (lock_word.ThinLockCount() != 0) {
1106 uint32_t new_count = lock_word.ThinLockCount() - 1;
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001107 new_lw = LockWord::FromThinLockId(thread_id, new_count, lock_word.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001108 } else {
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001109 new_lw = LockWord::FromDefault(lock_word.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001110 }
1111 if (!kUseReadBarrier) {
1112 DCHECK_EQ(new_lw.ReadBarrierState(), 0U);
Hans Boehmb3da36c2016-12-15 13:12:59 -08001113 // TODO: This really only needs memory_order_release, but we currently have
1114 // no way to specify that. In fact there seem to be no legitimate uses of SetLockWord
1115 // with a final argument of true. This slows down x86 and ARMv7, but probably not v8.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001116 h_obj->SetLockWord(new_lw, true);
Andreas Gampe6e759ad2016-05-17 10:13:10 -07001117 AtraceMonitorUnlock();
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001118 // Success!
1119 return true;
1120 } else {
1121 // Use CAS to preserve the read barrier state.
Hans Boehmb3da36c2016-12-15 13:12:59 -08001122 if (h_obj->CasLockWordWeakRelease(lock_word, new_lw)) {
Andreas Gampe6e759ad2016-05-17 10:13:10 -07001123 AtraceMonitorUnlock();
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001124 // Success!
1125 return true;
1126 }
1127 }
1128 continue; // Go again.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001129 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001130 }
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001131 case LockWord::kFatLocked: {
1132 Monitor* mon = lock_word.FatLockMonitor();
1133 return mon->Unlock(self);
1134 }
1135 default: {
1136 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1137 return false;
1138 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001139 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001140 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001141}
1142
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001143void Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
Elliott Hughes4cd121e2013-01-07 17:35:41 -08001144 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001145 DCHECK(self != nullptr);
1146 DCHECK(obj != nullptr);
Alex Light77fee872017-09-05 14:51:49 -07001147 StackHandleScope<1> hs(self);
1148 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
1149
1150 Runtime::Current()->GetRuntimeCallbacks()->ObjectWaitStart(h_obj, ms);
Alex Light848574c2017-09-25 16:59:39 -07001151 if (UNLIKELY(self->ObserveAsyncException() || self->IsExceptionPending())) {
Alex Light77fee872017-09-05 14:51:49 -07001152 // See b/65558434 for information on handling of exceptions here.
1153 return;
1154 }
1155
1156 LockWord lock_word = h_obj->GetLockWord(true);
Ian Rogers43c69cc2014-08-15 11:09:28 -07001157 while (lock_word.GetState() != LockWord::kFatLocked) {
1158 switch (lock_word.GetState()) {
1159 case LockWord::kHashCode:
1160 // Fall-through.
1161 case LockWord::kUnlocked:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001162 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
1163 return; // Failure.
Ian Rogers43c69cc2014-08-15 11:09:28 -07001164 case LockWord::kThinLocked: {
1165 uint32_t thread_id = self->GetThreadId();
1166 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1167 if (owner_thread_id != thread_id) {
1168 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
1169 return; // Failure.
1170 } else {
1171 // We own the lock, inflate to enqueue ourself on the Monitor. May fail spuriously so
1172 // re-load.
Alex Light77fee872017-09-05 14:51:49 -07001173 Inflate(self, self, h_obj.Get(), 0);
1174 lock_word = h_obj->GetLockWord(true);
Ian Rogers43c69cc2014-08-15 11:09:28 -07001175 }
1176 break;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001177 }
Ian Rogers43c69cc2014-08-15 11:09:28 -07001178 case LockWord::kFatLocked: // Unreachable given the loop condition above. Fall-through.
1179 default: {
1180 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1181 return;
1182 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001183 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001184 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001185 Monitor* mon = lock_word.FatLockMonitor();
1186 mon->Wait(self, ms, ns, interruptShouldThrow, why);
Elliott Hughes5f791332011-09-15 17:45:30 -07001187}
1188
Ian Rogers13c479e2013-10-11 07:59:01 -07001189void Monitor::DoNotify(Thread* self, mirror::Object* obj, bool notify_all) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001190 DCHECK(self != nullptr);
1191 DCHECK(obj != nullptr);
1192 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001193 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001194 case LockWord::kHashCode:
1195 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001196 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -08001197 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001198 return; // Failure.
1199 case LockWord::kThinLocked: {
1200 uint32_t thread_id = self->GetThreadId();
1201 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1202 if (owner_thread_id != thread_id) {
1203 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
1204 return; // Failure.
1205 } else {
1206 // We own the lock but there's no Monitor and therefore no waiters.
1207 return; // Success.
1208 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001209 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001210 case LockWord::kFatLocked: {
1211 Monitor* mon = lock_word.FatLockMonitor();
1212 if (notify_all) {
1213 mon->NotifyAll(self);
1214 } else {
1215 mon->Notify(self);
1216 }
1217 return; // Success.
1218 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001219 default: {
1220 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1221 return;
1222 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001223 }
1224}
1225
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001226uint32_t Monitor::GetLockOwnerThreadId(mirror::Object* obj) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001227 DCHECK(obj != nullptr);
1228 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001229 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001230 case LockWord::kHashCode:
1231 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001232 case LockWord::kUnlocked:
1233 return ThreadList::kInvalidThreadId;
1234 case LockWord::kThinLocked:
1235 return lock_word.ThinLockOwner();
1236 case LockWord::kFatLocked: {
1237 Monitor* mon = lock_word.FatLockMonitor();
1238 return mon->GetOwnerThreadId();
Elliott Hughes5f791332011-09-15 17:45:30 -07001239 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001240 default: {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001241 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001242 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001243 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001244 }
1245}
1246
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001247void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
Ian Rogersd803bc72014-04-01 15:33:03 -07001248 // Determine the wait message and object we're waiting or blocked upon.
1249 mirror::Object* pretty_object = nullptr;
1250 const char* wait_message = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001251 uint32_t lock_owner = ThreadList::kInvalidThreadId;
Ian Rogersd803bc72014-04-01 15:33:03 -07001252 ThreadState state = thread->GetState();
Elliott Hughesb4e94fd2013-01-08 14:41:26 -08001253 if (state == kWaiting || state == kTimedWaiting || state == kSleeping) {
Ian Rogersd803bc72014-04-01 15:33:03 -07001254 wait_message = (state == kSleeping) ? " - sleeping on " : " - waiting on ";
1255 Thread* self = Thread::Current();
1256 MutexLock mu(self, *thread->GetWaitMutex());
1257 Monitor* monitor = thread->GetWaitMonitor();
1258 if (monitor != nullptr) {
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001259 pretty_object = monitor->GetObject();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001260 }
Alex Light77fee872017-09-05 14:51:49 -07001261 } else if (state == kBlocked || state == kWaitingForLockInflation) {
1262 wait_message = (state == kBlocked) ? " - waiting to lock "
1263 : " - waiting for lock inflation of ";
Ian Rogersd803bc72014-04-01 15:33:03 -07001264 pretty_object = thread->GetMonitorEnterObject();
1265 if (pretty_object != nullptr) {
Hiroshi Yamauchi7b08ae42016-10-04 15:20:36 -07001266 if (kUseReadBarrier && Thread::Current()->GetIsGcMarking()) {
1267 // We may call Thread::Dump() in the middle of the CC thread flip and this thread's stack
1268 // may have not been flipped yet and "pretty_object" may be a from-space (stale) ref, in
1269 // which case the GetLockOwnerThreadId() call below will crash. So explicitly mark/forward
1270 // it here.
1271 pretty_object = ReadBarrier::Mark(pretty_object);
1272 }
Ian Rogersd803bc72014-04-01 15:33:03 -07001273 lock_owner = pretty_object->GetLockOwnerThreadId();
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001274 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001275 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001276
Ian Rogersd803bc72014-04-01 15:33:03 -07001277 if (wait_message != nullptr) {
1278 if (pretty_object == nullptr) {
1279 os << wait_message << "an unknown object";
1280 } else {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001281 if ((pretty_object->GetLockWord(true).GetState() == LockWord::kThinLocked) &&
Ian Rogersd803bc72014-04-01 15:33:03 -07001282 Locks::mutator_lock_->IsExclusiveHeld(Thread::Current())) {
1283 // Getting the identity hashcode here would result in lock inflation and suspension of the
1284 // current thread, which isn't safe if this is the only runnable thread.
1285 os << wait_message << StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)",
1286 reinterpret_cast<intptr_t>(pretty_object),
David Sehr709b0702016-10-13 09:12:37 -07001287 pretty_object->PrettyTypeOf().c_str());
Ian Rogersd803bc72014-04-01 15:33:03 -07001288 } else {
1289 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
Mathieu Chartier49361592015-01-22 16:36:10 -08001290 // Call PrettyTypeOf before IdentityHashCode since IdentityHashCode can cause thread
1291 // suspension and move pretty_object.
David Sehr709b0702016-10-13 09:12:37 -07001292 const std::string pretty_type(pretty_object->PrettyTypeOf());
Ian Rogersd803bc72014-04-01 15:33:03 -07001293 os << wait_message << StringPrintf("<0x%08x> (a %s)", pretty_object->IdentityHashCode(),
Mathieu Chartier49361592015-01-22 16:36:10 -08001294 pretty_type.c_str());
Ian Rogersd803bc72014-04-01 15:33:03 -07001295 }
1296 }
1297 // - waiting to lock <0x613f83d8> (a java.lang.Object) held by thread 5
1298 if (lock_owner != ThreadList::kInvalidThreadId) {
1299 os << " held by thread " << lock_owner;
1300 }
1301 os << "\n";
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001302 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001303}
1304
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001305mirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -08001306 // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
1307 // definition of contended that includes a monitor a thread is trying to enter...
Ian Rogersdd7624d2014-03-14 17:43:00 -07001308 mirror::Object* result = thread->GetMonitorEnterObject();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001309 if (result == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001310 // ...but also a monitor that the thread is waiting on.
Ian Rogersdd7624d2014-03-14 17:43:00 -07001311 MutexLock mu(Thread::Current(), *thread->GetWaitMutex());
1312 Monitor* monitor = thread->GetWaitMonitor();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001313 if (monitor != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001314 result = monitor->GetObject();
Elliott Hughesf9501702013-01-11 11:22:27 -08001315 }
1316 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001317 return result;
Elliott Hughesf9501702013-01-11 11:22:27 -08001318}
1319
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001320void Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
Andreas Gampe760172c2014-08-16 13:41:10 -07001321 void* callback_context, bool abort_on_failure) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001322 ArtMethod* m = stack_visitor->GetMethod();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001323 CHECK(m != nullptr);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001324
1325 // Native methods are an easy special case.
1326 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
1327 if (m->IsNative()) {
1328 if (m->IsSynchronized()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001329 mirror::Object* jni_this =
1330 stack_visitor->GetCurrentHandleScope(sizeof(void*))->GetReference(0);
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001331 callback(jni_this, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001332 }
1333 return;
1334 }
1335
jeffhao61f916c2012-10-25 17:48:51 -07001336 // Proxy methods should not be synchronized.
1337 if (m->IsProxyMethod()) {
1338 CHECK(!m->IsSynchronized());
1339 return;
1340 }
1341
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001342 // Is there any reason to believe there's any synchronization in this method?
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001343 const DexFile::CodeItem* code_item = m->GetCodeItem();
David Sehr709b0702016-10-13 09:12:37 -07001344 CHECK(code_item != nullptr) << m->PrettyMethod();
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001345 if (code_item->tries_size_ == 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001346 return; // No "tries" implies no synchronization, so no held locks to report.
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001347 }
1348
Andreas Gampe760172c2014-08-16 13:41:10 -07001349 // Get the dex pc. If abort_on_failure is false, GetDexPc will not abort in the case it cannot
1350 // find the dex pc, and instead return kDexNoIndex. Then bail out, as it indicates we have an
1351 // inconsistent stack anyways.
1352 uint32_t dex_pc = stack_visitor->GetDexPc(abort_on_failure);
Andreas Gampee2abbc62017-09-15 11:59:26 -07001353 if (!abort_on_failure && dex_pc == dex::kDexNoIndex) {
David Sehr709b0702016-10-13 09:12:37 -07001354 LOG(ERROR) << "Could not find dex_pc for " << m->PrettyMethod();
Andreas Gampe760172c2014-08-16 13:41:10 -07001355 return;
1356 }
1357
Elliott Hughes80537bb2013-01-04 16:37:26 -08001358 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
1359 // the locks held in this stack frame.
1360 std::vector<uint32_t> monitor_enter_dex_pcs;
Andreas Gampe760172c2014-08-16 13:41:10 -07001361 verifier::MethodVerifier::FindLocksAtDexPc(m, dex_pc, &monitor_enter_dex_pcs);
Mathieu Chartiere6a8eec2015-01-06 14:17:57 -08001362 for (uint32_t monitor_dex_pc : monitor_enter_dex_pcs) {
Elliott Hughes80537bb2013-01-04 16:37:26 -08001363 // The verifier works in terms of the dex pcs of the monitor-enter instructions.
1364 // We want the registers used by those instructions (so we can read the values out of them).
Sebastien Hertz0f7c9332015-11-05 15:57:30 +01001365 const Instruction* monitor_enter_instruction =
1366 Instruction::At(&code_item->insns_[monitor_dex_pc]);
Elliott Hughes80537bb2013-01-04 16:37:26 -08001367
1368 // Quick sanity check.
Sebastien Hertz0f7c9332015-11-05 15:57:30 +01001369 CHECK_EQ(monitor_enter_instruction->Opcode(), Instruction::MONITOR_ENTER)
1370 << "expected monitor-enter @" << monitor_dex_pc << "; was "
1371 << reinterpret_cast<const void*>(monitor_enter_instruction);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001372
Sebastien Hertz0f7c9332015-11-05 15:57:30 +01001373 uint16_t monitor_register = monitor_enter_instruction->VRegA();
Nicolas Geoffray15b9d522015-03-12 15:05:13 +00001374 uint32_t value;
1375 bool success = stack_visitor->GetVReg(m, monitor_register, kReferenceVReg, &value);
1376 CHECK(success) << "Failed to read v" << monitor_register << " of kind "
David Sehr709b0702016-10-13 09:12:37 -07001377 << kReferenceVReg << " in method " << m->PrettyMethod();
Nicolas Geoffray15b9d522015-03-12 15:05:13 +00001378 mirror::Object* o = reinterpret_cast<mirror::Object*>(value);
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001379 callback(o, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001380 }
1381}
1382
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001383bool Monitor::IsValidLockWord(LockWord lock_word) {
1384 switch (lock_word.GetState()) {
1385 case LockWord::kUnlocked:
1386 // Nothing to check.
1387 return true;
1388 case LockWord::kThinLocked:
1389 // Basic sanity check of owner.
1390 return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
1391 case LockWord::kFatLocked: {
1392 // Check the monitor appears in the monitor list.
1393 Monitor* mon = lock_word.FatLockMonitor();
1394 MonitorList* list = Runtime::Current()->GetMonitorList();
1395 MutexLock mu(Thread::Current(), list->monitor_list_lock_);
1396 for (Monitor* list_mon : list->list_) {
1397 if (mon == list_mon) {
1398 return true; // Found our monitor.
1399 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001400 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001401 return false; // Fail - unowned monitor in an object.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001402 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001403 case LockWord::kHashCode:
1404 return true;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001405 default:
1406 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001407 UNREACHABLE();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001408 }
1409}
1410
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001411bool Monitor::IsLocked() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001412 MutexLock mu(Thread::Current(), monitor_lock_);
1413 return owner_ != nullptr;
1414}
1415
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -07001416void Monitor::TranslateLocation(ArtMethod* method,
1417 uint32_t dex_pc,
1418 const char** source_file,
1419 int32_t* line_number) {
jeffhao33dc7712011-11-09 17:54:24 -08001420 // If method is null, location is unknown
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001421 if (method == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001422 *source_file = "";
1423 *line_number = 0;
jeffhao33dc7712011-11-09 17:54:24 -08001424 return;
1425 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001426 *source_file = method->GetDeclaringClassSourceFile();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001427 if (*source_file == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001428 *source_file = "";
Elliott Hughes12c51e32012-01-17 20:25:05 -08001429 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001430 *line_number = method->GetLineNumFromDexPC(dex_pc);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001431}
1432
1433uint32_t Monitor::GetOwnerThreadId() {
1434 MutexLock mu(Thread::Current(), monitor_lock_);
1435 Thread* owner = owner_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001436 if (owner != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001437 return owner->GetThreadId();
1438 } else {
1439 return ThreadList::kInvalidThreadId;
1440 }
jeffhao33dc7712011-11-09 17:54:24 -08001441}
1442
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001443MonitorList::MonitorList()
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001444 : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock", kMonitorListLock),
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001445 monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001446}
1447
1448MonitorList::~MonitorList() {
Andreas Gampe74240812014-04-17 10:35:09 -07001449 Thread* self = Thread::Current();
1450 MutexLock mu(self, monitor_list_lock_);
1451 // Release all monitors to the pool.
1452 // TODO: Is it an invariant that *all* open monitors are in the list? Then we could
1453 // clear faster in the pool.
1454 MonitorPool::ReleaseMonitors(self, &list_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001455}
1456
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001457void MonitorList::DisallowNewMonitors() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001458 CHECK(!kUseReadBarrier);
Ian Rogers50b35e22012-10-04 10:09:15 -07001459 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001460 allow_new_monitors_ = false;
1461}
1462
1463void MonitorList::AllowNewMonitors() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001464 CHECK(!kUseReadBarrier);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001465 Thread* self = Thread::Current();
1466 MutexLock mu(self, monitor_list_lock_);
1467 allow_new_monitors_ = true;
1468 monitor_add_condition_.Broadcast(self);
1469}
1470
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001471void MonitorList::BroadcastForNewMonitors() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001472 Thread* self = Thread::Current();
1473 MutexLock mu(self, monitor_list_lock_);
1474 monitor_add_condition_.Broadcast(self);
1475}
1476
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001477void MonitorList::Add(Monitor* m) {
1478 Thread* self = Thread::Current();
1479 MutexLock mu(self, monitor_list_lock_);
Hiroshi Yamauchif1c6f872017-01-06 12:23:47 -08001480 // CMS needs this to block for concurrent reference processing because an object allocated during
1481 // the GC won't be marked and concurrent reference processing would incorrectly clear the JNI weak
1482 // ref. But CC (kUseReadBarrier == true) doesn't because of the to-space invariant.
1483 while (!kUseReadBarrier && UNLIKELY(!allow_new_monitors_)) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -07001484 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
1485 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -08001486 self->CheckEmptyCheckpointFromWeakRefAccess(&monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001487 monitor_add_condition_.WaitHoldingLocks(self);
1488 }
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001489 list_.push_front(m);
1490}
1491
Mathieu Chartier97509952015-07-13 14:35:43 -07001492void MonitorList::SweepMonitorList(IsMarkedVisitor* visitor) {
Andreas Gampe74240812014-04-17 10:35:09 -07001493 Thread* self = Thread::Current();
1494 MutexLock mu(self, monitor_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001495 for (auto it = list_.begin(); it != list_.end(); ) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001496 Monitor* m = *it;
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001497 // Disable the read barrier in GetObject() as this is called by GC.
1498 mirror::Object* obj = m->GetObject<kWithoutReadBarrier>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001499 // The object of a monitor can be null if we have deflated it.
Mathieu Chartier97509952015-07-13 14:35:43 -07001500 mirror::Object* new_obj = obj != nullptr ? visitor->IsMarked(obj) : nullptr;
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001501 if (new_obj == nullptr) {
1502 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001503 << obj;
Andreas Gampe74240812014-04-17 10:35:09 -07001504 MonitorPool::ReleaseMonitor(self, m);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001505 it = list_.erase(it);
1506 } else {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001507 m->SetObject(new_obj);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001508 ++it;
1509 }
1510 }
1511}
1512
Hans Boehm6fe97e02016-05-04 18:35:57 -07001513size_t MonitorList::Size() {
1514 Thread* self = Thread::Current();
1515 MutexLock mu(self, monitor_list_lock_);
1516 return list_.size();
1517}
1518
Mathieu Chartier97509952015-07-13 14:35:43 -07001519class MonitorDeflateVisitor : public IsMarkedVisitor {
1520 public:
1521 MonitorDeflateVisitor() : self_(Thread::Current()), deflate_count_(0) {}
1522
1523 virtual mirror::Object* IsMarked(mirror::Object* object) OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001524 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001525 if (Monitor::Deflate(self_, object)) {
1526 DCHECK_NE(object->GetLockWord(true).GetState(), LockWord::kFatLocked);
1527 ++deflate_count_;
1528 // If we deflated, return null so that the monitor gets removed from the array.
1529 return nullptr;
1530 }
1531 return object; // Monitor was not deflated.
1532 }
1533
1534 Thread* const self_;
1535 size_t deflate_count_;
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001536};
1537
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001538size_t MonitorList::DeflateMonitors() {
Mathieu Chartier97509952015-07-13 14:35:43 -07001539 MonitorDeflateVisitor visitor;
1540 Locks::mutator_lock_->AssertExclusiveHeld(visitor.self_);
1541 SweepMonitorList(&visitor);
1542 return visitor.deflate_count_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001543}
1544
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001545MonitorInfo::MonitorInfo(mirror::Object* obj) : owner_(nullptr), entry_count_(0) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001546 DCHECK(obj != nullptr);
1547 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001548 switch (lock_word.GetState()) {
1549 case LockWord::kUnlocked:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001550 // Fall-through.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001551 case LockWord::kForwardingAddress:
1552 // Fall-through.
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001553 case LockWord::kHashCode:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001554 break;
1555 case LockWord::kThinLocked:
1556 owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
Alex Lightce568642017-09-05 16:54:25 -07001557 DCHECK(owner_ != nullptr) << "Thin-locked without owner!";
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001558 entry_count_ = 1 + lock_word.ThinLockCount();
1559 // Thin locks have no waiters.
1560 break;
1561 case LockWord::kFatLocked: {
1562 Monitor* mon = lock_word.FatLockMonitor();
1563 owner_ = mon->owner_;
Alex Lightce568642017-09-05 16:54:25 -07001564 // Here it is okay for the owner to be null since we don't reset the LockWord back to
1565 // kUnlocked until we get a GC. In cases where this hasn't happened yet we will have a fat
1566 // lock without an owner.
1567 if (owner_ != nullptr) {
1568 entry_count_ = 1 + mon->lock_count_;
1569 } else {
1570 DCHECK_EQ(mon->lock_count_, 0) << "Monitor is fat-locked without any owner!";
1571 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001572 for (Thread* waiter = mon->wait_set_; waiter != nullptr; waiter = waiter->GetWaitNext()) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001573 waiters_.push_back(waiter);
1574 }
1575 break;
Elliott Hughesf327e072013-01-09 16:01:26 -08001576 }
1577 }
1578}
1579
Elliott Hughes5f791332011-09-15 17:45:30 -07001580} // namespace art