blob: d5520d9acaa236b233a29ce64a55997f04a4c5e3 [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);
Andreas Gampe5a387272017-11-06 19:47:16 -0800180 if (locking_method_ != nullptr && UNLIKELY(locking_method_->IsProxyMethod())) {
181 // Grab another frame. Proxy methods are not helpful for lock profiling. This should be rare
182 // enough that it's OK to walk the stack twice.
183 struct NextMethodVisitor FINAL : public StackVisitor {
184 explicit NextMethodVisitor(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_)
185 : StackVisitor(thread,
186 nullptr,
187 StackVisitor::StackWalkKind::kIncludeInlinedFrames,
188 false),
189 count_(0),
190 method_(nullptr),
191 dex_pc_(0) {}
192 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
193 ArtMethod* m = GetMethod();
194 if (m->IsRuntimeMethod()) {
195 // Continue if this is a runtime method.
196 return true;
197 }
198 count_++;
199 if (count_ == 2u) {
200 method_ = m;
201 dex_pc_ = GetDexPc(false);
202 return false;
203 }
204 return true;
205 }
206 size_t count_;
207 ArtMethod* method_;
208 uint32_t dex_pc_;
209 };
210 NextMethodVisitor nmv(owner_);
211 nmv.WalkStack();
212 locking_method_ = nmv.method_;
213 locking_dex_pc_ = nmv.dex_pc_;
214 }
215 DCHECK(locking_method_ == nullptr || !locking_method_->IsProxyMethod());
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700216 }
217 return success;
Elliott Hughes5f791332011-09-15 17:45:30 -0700218}
219
220Monitor::~Monitor() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700221 // Deflated monitors have a null object.
Elliott Hughes5f791332011-09-15 17:45:30 -0700222}
223
Elliott Hughes5f791332011-09-15 17:45:30 -0700224void Monitor::AppendToWaitSet(Thread* thread) {
225 DCHECK(owner_ == Thread::Current());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700226 DCHECK(thread != nullptr);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700227 DCHECK(thread->GetWaitNext() == nullptr) << thread->GetWaitNext();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700228 if (wait_set_ == nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700229 wait_set_ = thread;
230 return;
231 }
232
233 // push_back.
234 Thread* t = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700235 while (t->GetWaitNext() != nullptr) {
236 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700237 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700238 t->SetWaitNext(thread);
Elliott Hughes5f791332011-09-15 17:45:30 -0700239}
240
Elliott Hughes5f791332011-09-15 17:45:30 -0700241void Monitor::RemoveFromWaitSet(Thread *thread) {
242 DCHECK(owner_ == Thread::Current());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700243 DCHECK(thread != nullptr);
244 if (wait_set_ == nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700245 return;
246 }
247 if (wait_set_ == thread) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700248 wait_set_ = thread->GetWaitNext();
249 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700250 return;
251 }
252
253 Thread* t = wait_set_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700254 while (t->GetWaitNext() != nullptr) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700255 if (t->GetWaitNext() == thread) {
256 t->SetWaitNext(thread->GetWaitNext());
257 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700258 return;
259 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700260 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700261 }
262}
263
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700264void Monitor::SetObject(mirror::Object* object) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700265 obj_ = GcRoot<mirror::Object>(object);
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700266}
267
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700268// Note: Adapted from CurrentMethodVisitor in thread.cc. We must not resolve here.
269
270struct NthCallerWithDexPcVisitor FINAL : public StackVisitor {
271 explicit NthCallerWithDexPcVisitor(Thread* thread, size_t frame)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700272 REQUIRES_SHARED(Locks::mutator_lock_)
Nicolas Geoffrayc6df1e32016-07-04 10:15:47 +0100273 : StackVisitor(thread, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700274 method_(nullptr),
275 dex_pc_(0),
276 current_frame_number_(0),
277 wanted_frame_number_(frame) {}
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700278 bool VisitFrame() OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700279 ArtMethod* m = GetMethod();
280 if (m == nullptr || m->IsRuntimeMethod()) {
281 // Runtime method, upcall, or resolution issue. Skip.
282 return true;
283 }
284
285 // Is this the requested frame?
286 if (current_frame_number_ == wanted_frame_number_) {
287 method_ = m;
288 dex_pc_ = GetDexPc(false /* abort_on_error*/);
289 return false;
290 }
291
292 // Look for more.
293 current_frame_number_++;
294 return true;
295 }
296
297 ArtMethod* method_;
298 uint32_t dex_pc_;
299
300 private:
301 size_t current_frame_number_;
302 const size_t wanted_frame_number_;
303};
304
305// This function is inlined and just helps to not have the VLOG and ATRACE check at all the
306// potential tracing points.
307void Monitor::AtraceMonitorLock(Thread* self, mirror::Object* obj, bool is_wait) {
308 if (UNLIKELY(VLOG_IS_ON(systrace_lock_logging) && ATRACE_ENABLED())) {
309 AtraceMonitorLockImpl(self, obj, is_wait);
310 }
311}
312
313void Monitor::AtraceMonitorLockImpl(Thread* self, mirror::Object* obj, bool is_wait) {
314 // Wait() requires a deeper call stack to be useful. Otherwise you'll see "Waiting at
315 // Object.java". Assume that we'll wait a nontrivial amount, so it's OK to do a longer
316 // stack walk than if !is_wait.
317 NthCallerWithDexPcVisitor visitor(self, is_wait ? 1U : 0U);
318 visitor.WalkStack(false);
319 const char* prefix = is_wait ? "Waiting on " : "Locking ";
320
321 const char* filename;
322 int32_t line_number;
323 TranslateLocation(visitor.method_, visitor.dex_pc_, &filename, &line_number);
324
325 // It would be nice to have a stable "ID" for the object here. However, the only stable thing
326 // would be the identity hashcode. But we cannot use IdentityHashcode here: For one, there are
327 // times when it is unsafe to make that call (see stack dumping for an explanation). More
328 // importantly, we would have to give up on thin-locking when adding systrace locks, as the
329 // identity hashcode is stored in the lockword normally (so can't be used with thin-locks).
330 //
331 // Because of thin-locks we also cannot use the monitor id (as there is no monitor). Monitor ids
332 // also do not have to be stable, as the monitor may be deflated.
333 std::string tmp = StringPrintf("%s %d at %s:%d",
334 prefix,
335 (obj == nullptr ? -1 : static_cast<int32_t>(reinterpret_cast<uintptr_t>(obj))),
336 (filename != nullptr ? filename : "null"),
337 line_number);
338 ATRACE_BEGIN(tmp.c_str());
339}
340
341void Monitor::AtraceMonitorUnlock() {
342 if (UNLIKELY(VLOG_IS_ON(systrace_lock_logging))) {
343 ATRACE_END();
344 }
345}
346
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700347std::string Monitor::PrettyContentionInfo(const std::string& owner_name,
348 pid_t owner_tid,
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700349 ArtMethod* owners_method,
350 uint32_t owners_dex_pc,
351 size_t num_waiters) {
Hiroshi Yamauchi71cd68d2017-01-25 18:28:12 -0800352 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700353 const char* owners_filename;
Goran Jakovljevic49c882b2016-04-19 10:27:21 +0200354 int32_t owners_line_number = 0;
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700355 if (owners_method != nullptr) {
356 TranslateLocation(owners_method, owners_dex_pc, &owners_filename, &owners_line_number);
357 }
358 std::ostringstream oss;
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700359 oss << "monitor contention with owner " << owner_name << " (" << owner_tid << ")";
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700360 if (owners_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700361 oss << " at " << owners_method->PrettyMethod();
Mathieu Chartier36891fe2016-04-28 17:21:08 -0700362 oss << "(" << owners_filename << ":" << owners_line_number << ")";
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700363 }
364 oss << " waiters=" << num_waiters;
365 return oss.str();
366}
367
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700368bool Monitor::TryLockLocked(Thread* self) {
369 if (owner_ == nullptr) { // Unowned.
370 owner_ = self;
371 CHECK_EQ(lock_count_, 0);
372 // When debugging, save the current monitor holder for future
373 // acquisition failures to use in sampled logging.
374 if (lock_profiling_threshold_ != 0) {
375 locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
Andreas Gampe5a387272017-11-06 19:47:16 -0800376 // We don't expect a proxy method here.
377 DCHECK(locking_method_ == nullptr || !locking_method_->IsProxyMethod());
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700378 }
379 } else if (owner_ == self) { // Recursive.
380 lock_count_++;
381 } else {
382 return false;
383 }
384 AtraceMonitorLock(self, GetObject(), false /* is_wait */);
385 return true;
386}
387
388bool Monitor::TryLock(Thread* self) {
389 MutexLock mu(self, monitor_lock_);
390 return TryLockLocked(self);
391}
392
Alex Light77fee872017-09-05 14:51:49 -0700393// Asserts that a mutex isn't held when the class comes into and out of scope.
394class ScopedAssertNotHeld {
395 public:
396 ScopedAssertNotHeld(Thread* self, Mutex& mu) : self_(self), mu_(mu) {
397 mu_.AssertNotHeld(self_);
398 }
399
400 ~ScopedAssertNotHeld() {
401 mu_.AssertNotHeld(self_);
402 }
403
404 private:
405 Thread* const self_;
406 Mutex& mu_;
407 DISALLOW_COPY_AND_ASSIGN(ScopedAssertNotHeld);
408};
409
410template <LockReason reason>
Elliott Hughes5f791332011-09-15 17:45:30 -0700411void Monitor::Lock(Thread* self) {
Alex Light77fee872017-09-05 14:51:49 -0700412 ScopedAssertNotHeld sanh(self, monitor_lock_);
413 bool called_monitors_callback = false;
414 monitor_lock_.Lock(self);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700415 while (true) {
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700416 if (TryLockLocked(self)) {
Alex Light77fee872017-09-05 14:51:49 -0700417 break;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700418 }
419 // Contended.
420 const bool log_contention = (lock_profiling_threshold_ != 0);
Xin Guanb894a192014-08-22 11:55:37 -0500421 uint64_t wait_start_ms = log_contention ? MilliTime() : 0;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700422 ArtMethod* owners_method = locking_method_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700423 uint32_t owners_dex_pc = locking_dex_pc_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700424 // Do this before releasing the lock so that we don't get deflated.
Mathieu Chartierb9001ab2014-10-03 13:28:46 -0700425 size_t num_waiters = num_waiters_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700426 ++num_waiters_;
Andreas Gampe2702d562017-02-06 09:48:00 -0800427
428 // If systrace logging is enabled, first look at the lock owner. Acquiring the monitor's
429 // lock and then re-acquiring the mutator lock can deadlock.
430 bool started_trace = false;
431 if (ATRACE_ENABLED()) {
432 if (owner_ != nullptr) { // Did the owner_ give the lock up?
433 std::ostringstream oss;
434 std::string name;
435 owner_->GetThreadName(name);
436 oss << PrettyContentionInfo(name,
437 owner_->GetTid(),
438 owners_method,
439 owners_dex_pc,
440 num_waiters);
441 // Add info for contending thread.
442 uint32_t pc;
443 ArtMethod* m = self->GetCurrentMethod(&pc);
444 const char* filename;
445 int32_t line_number;
446 TranslateLocation(m, pc, &filename, &line_number);
447 oss << " blocking from "
448 << ArtMethod::PrettyMethod(m) << "(" << (filename != nullptr ? filename : "null")
449 << ":" << line_number << ")";
450 ATRACE_BEGIN(oss.str().c_str());
451 started_trace = true;
452 }
453 }
454
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700455 monitor_lock_.Unlock(self); // Let go of locks in order.
Alex Light77fee872017-09-05 14:51:49 -0700456 // Call the contended locking cb once and only once. Also only call it if we are locking for
457 // the first time, not during a Wait wakeup.
458 if (reason == LockReason::kForLock && !called_monitors_callback) {
459 called_monitors_callback = true;
460 Runtime::Current()->GetRuntimeCallbacks()->MonitorContendedLocking(this);
461 }
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700462 self->SetMonitorEnterObject(GetObject());
Elliott Hughes5f791332011-09-15 17:45:30 -0700463 {
Hiroshi Yamauchi71cd68d2017-01-25 18:28:12 -0800464 ScopedThreadSuspension tsc(self, kBlocked); // Change to blocked and give up mutator_lock_.
Andreas Gampe2702d562017-02-06 09:48:00 -0800465 uint32_t original_owner_thread_id = 0u;
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700466 {
467 // Reacquire monitor_lock_ without mutator_lock_ for Wait.
468 MutexLock mu2(self, monitor_lock_);
469 if (owner_ != nullptr) { // Did the owner_ give the lock up?
470 original_owner_thread_id = owner_->GetThreadId();
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700471 monitor_contenders_.Wait(self); // Still contended so wait.
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800472 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700473 }
474 if (original_owner_thread_id != 0u) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700475 // Woken from contention.
476 if (log_contention) {
Andreas Gampe111b1092017-06-22 20:28:23 -0700477 uint64_t wait_ms = MilliTime() - wait_start_ms;
478 uint32_t sample_percent;
479 if (wait_ms >= lock_profiling_threshold_) {
480 sample_percent = 100;
481 } else {
482 sample_percent = 100 * wait_ms / lock_profiling_threshold_;
483 }
484 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
485 // Reacquire mutator_lock_ for logging.
486 ScopedObjectAccess soa(self);
Andreas Gampe111b1092017-06-22 20:28:23 -0700487
Andreas Gamped0210e52017-06-23 13:38:09 -0700488 bool owner_alive = false;
489 pid_t original_owner_tid = 0;
490 std::string original_owner_name;
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700491
Andreas Gamped0210e52017-06-23 13:38:09 -0700492 const bool should_dump_stacks = stack_dump_lock_profiling_threshold_ > 0 &&
493 wait_ms > stack_dump_lock_profiling_threshold_;
494 std::string owner_stack_dump;
Andreas Gampe111b1092017-06-22 20:28:23 -0700495
Andreas Gamped0210e52017-06-23 13:38:09 -0700496 // Acquire thread-list lock to find thread and keep it from dying until we've got all
497 // the info we need.
498 {
Alex Lightb1e31a82017-10-04 16:57:36 -0700499 Locks::thread_list_lock_->ExclusiveLock(Thread::Current());
Andreas Gamped0210e52017-06-23 13:38:09 -0700500
501 // Re-find the owner in case the thread got killed.
502 Thread* original_owner = Runtime::Current()->GetThreadList()->FindThreadByThreadId(
503 original_owner_thread_id);
504
505 if (original_owner != nullptr) {
506 owner_alive = true;
507 original_owner_tid = original_owner->GetTid();
508 original_owner->GetThreadName(original_owner_name);
509
510 if (should_dump_stacks) {
511 // Very long contention. Dump stacks.
512 struct CollectStackTrace : public Closure {
513 void Run(art::Thread* thread) OVERRIDE
514 REQUIRES_SHARED(art::Locks::mutator_lock_) {
515 thread->DumpJavaStack(oss);
516 }
517
518 std::ostringstream oss;
519 };
520 CollectStackTrace owner_trace;
Alex Lightb1e31a82017-10-04 16:57:36 -0700521 // RequestSynchronousCheckpoint releases the thread_list_lock_ as a part of its
522 // execution.
Andreas Gamped0210e52017-06-23 13:38:09 -0700523 original_owner->RequestSynchronousCheckpoint(&owner_trace);
524 owner_stack_dump = owner_trace.oss.str();
Alex Lightb1e31a82017-10-04 16:57:36 -0700525 } else {
526 Locks::thread_list_lock_->ExclusiveUnlock(Thread::Current());
Andreas Gamped0210e52017-06-23 13:38:09 -0700527 }
Alex Lightb1e31a82017-10-04 16:57:36 -0700528 } else {
529 Locks::thread_list_lock_->ExclusiveUnlock(Thread::Current());
Andreas Gamped0210e52017-06-23 13:38:09 -0700530 }
531 // This is all the data we need. Now drop the thread-list lock, it's OK for the
532 // owner to go away now.
533 }
534
535 // If we found the owner (and thus have owner data), go and log now.
536 if (owner_alive) {
537 // Give the detailed traces for really long contention.
538 if (should_dump_stacks) {
539 // This must be here (and not above) because we cannot hold the thread-list lock
540 // while running the checkpoint.
541 std::ostringstream self_trace_oss;
542 self->DumpJavaStack(self_trace_oss);
543
544 uint32_t pc;
545 ArtMethod* m = self->GetCurrentMethod(&pc);
546
547 LOG(WARNING) << "Long "
548 << PrettyContentionInfo(original_owner_name,
549 original_owner_tid,
550 owners_method,
551 owners_dex_pc,
552 num_waiters)
553 << " in " << ArtMethod::PrettyMethod(m) << " for "
554 << PrettyDuration(MsToNs(wait_ms)) << "\n"
555 << "Current owner stack:\n" << owner_stack_dump
556 << "Contender stack:\n" << self_trace_oss.str();
557 } else if (wait_ms > kLongWaitMs && owners_method != nullptr) {
Mathieu Chartier36891fe2016-04-28 17:21:08 -0700558 uint32_t pc;
559 ArtMethod* m = self->GetCurrentMethod(&pc);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700560 // TODO: We should maybe check that original_owner is still a live thread.
561 LOG(WARNING) << "Long "
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700562 << PrettyContentionInfo(original_owner_name,
563 original_owner_tid,
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700564 owners_method,
565 owners_dex_pc,
566 num_waiters)
David Sehr709b0702016-10-13 09:12:37 -0700567 << " in " << ArtMethod::PrettyMethod(m) << " for "
568 << PrettyDuration(MsToNs(wait_ms));
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700569 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700570 LogContentionEvent(self,
Alex Light77fee872017-09-05 14:51:49 -0700571 wait_ms,
572 sample_percent,
573 owners_method,
574 owners_dex_pc);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700575 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700576 }
577 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700578 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700579 }
Andreas Gampe2702d562017-02-06 09:48:00 -0800580 if (started_trace) {
581 ATRACE_END();
582 }
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700583 self->SetMonitorEnterObject(nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700584 monitor_lock_.Lock(self); // Reacquire locks in order.
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700585 --num_waiters_;
Elliott Hughesfc861622011-10-17 17:57:47 -0700586 }
Alex Light77fee872017-09-05 14:51:49 -0700587 monitor_lock_.Unlock(self);
588 // We need to pair this with a single contended locking call. NB we match the RI behavior and call
589 // this even if MonitorEnter failed.
590 if (called_monitors_callback) {
591 CHECK(reason == LockReason::kForLock);
592 Runtime::Current()->GetRuntimeCallbacks()->MonitorContendedLocked(this);
593 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700594}
595
Alex Light77fee872017-09-05 14:51:49 -0700596template void Monitor::Lock<LockReason::kForLock>(Thread* self);
597template void Monitor::Lock<LockReason::kForWait>(Thread* self);
598
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800599static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
600 __attribute__((format(printf, 1, 2)));
601
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700602static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700603 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800604 va_list args;
605 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800606 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000607 self->ThrowNewExceptionV("Ljava/lang/IllegalMonitorStateException;", fmt, args);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700608 if (!Runtime::Current()->IsStarted() || VLOG_IS_ON(monitor)) {
Brian Carlstrom64277f32012-03-26 23:53:34 -0700609 std::ostringstream ss;
Ian Rogers62d6c772013-02-27 08:32:07 -0800610 self->Dump(ss);
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700611 LOG(Runtime::Current()->IsStarted() ? ::android::base::INFO : ::android::base::ERROR)
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000612 << self->GetException()->Dump() << "\n" << ss.str();
Brian Carlstrom64277f32012-03-26 23:53:34 -0700613 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800614 va_end(args);
615}
616
Elliott Hughesd4237412012-02-21 11:24:45 -0800617static std::string ThreadToString(Thread* thread) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700618 if (thread == nullptr) {
619 return "nullptr";
Elliott Hughesd4237412012-02-21 11:24:45 -0800620 }
621 std::ostringstream oss;
622 // TODO: alternatively, we could just return the thread's name.
623 oss << *thread;
624 return oss.str();
625}
626
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700627void Monitor::FailedUnlock(mirror::Object* o,
628 uint32_t expected_owner_thread_id,
629 uint32_t found_owner_thread_id,
Elliott Hughesffb465f2012-03-01 18:46:05 -0800630 Monitor* monitor) {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700631 // Acquire thread list lock so threads won't disappear from under us.
Elliott Hughesffb465f2012-03-01 18:46:05 -0800632 std::string current_owner_string;
633 std::string expected_owner_string;
634 std::string found_owner_string;
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700635 uint32_t current_owner_thread_id = 0u;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800636 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700637 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700638 ThreadList* const thread_list = Runtime::Current()->GetThreadList();
639 Thread* expected_owner = thread_list->FindThreadByThreadId(expected_owner_thread_id);
640 Thread* found_owner = thread_list->FindThreadByThreadId(found_owner_thread_id);
641
Elliott Hughesffb465f2012-03-01 18:46:05 -0800642 // Re-read owner now that we hold lock.
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700643 Thread* current_owner = (monitor != nullptr) ? monitor->GetOwner() : nullptr;
644 if (current_owner != nullptr) {
645 current_owner_thread_id = current_owner->GetThreadId();
646 }
Elliott Hughesffb465f2012-03-01 18:46:05 -0800647 // Get short descriptions of the threads involved.
648 current_owner_string = ThreadToString(current_owner);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700649 expected_owner_string = expected_owner != nullptr ? ThreadToString(expected_owner) : "unnamed";
650 found_owner_string = found_owner != nullptr ? ThreadToString(found_owner) : "unnamed";
Elliott Hughesffb465f2012-03-01 18:46:05 -0800651 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700652
653 if (current_owner_thread_id == 0u) {
654 if (found_owner_thread_id == 0u) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800655 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
656 " on thread '%s'",
David Sehr709b0702016-10-13 09:12:37 -0700657 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800658 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800659 } else {
660 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800661 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
662 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800663 found_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700664 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800665 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800666 }
667 } else {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700668 if (found_owner_thread_id == 0u) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800669 // Race: originally there was no owner, there is now
670 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
671 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800672 current_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700673 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800674 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800675 } else {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700676 if (found_owner_thread_id != current_owner_thread_id) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800677 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800678 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
679 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800680 found_owner_string.c_str(),
681 current_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700682 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800683 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800684 } else {
685 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
686 " on thread '%s",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800687 current_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700688 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800689 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800690 }
691 }
692 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700693}
694
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700695bool Monitor::Unlock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700696 DCHECK(self != nullptr);
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700697 uint32_t owner_thread_id = 0u;
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700698 {
699 MutexLock mu(self, monitor_lock_);
700 Thread* owner = owner_;
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700701 if (owner != nullptr) {
702 owner_thread_id = owner->GetThreadId();
703 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700704 if (owner == self) {
705 // We own the monitor, so nobody else can be in here.
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700706 AtraceMonitorUnlock();
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700707 if (lock_count_ == 0) {
708 owner_ = nullptr;
709 locking_method_ = nullptr;
710 locking_dex_pc_ = 0;
711 // Wake a contender.
712 monitor_contenders_.Signal(self);
713 } else {
714 --lock_count_;
715 }
716 return true;
Elliott Hughes5f791332011-09-15 17:45:30 -0700717 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700718 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700719 // We don't own this, so we're not allowed to unlock it.
720 // The JNI spec says that we should throw IllegalMonitorStateException in this case.
721 FailedUnlock(GetObject(), self->GetThreadId(), owner_thread_id, this);
722 return false;
Elliott Hughes5f791332011-09-15 17:45:30 -0700723}
724
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800725void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
726 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700727 DCHECK(self != nullptr);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800728 DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
Elliott Hughes5f791332011-09-15 17:45:30 -0700729
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700730 monitor_lock_.Lock(self);
731
Elliott Hughes5f791332011-09-15 17:45:30 -0700732 // Make sure that we hold the lock.
733 if (owner_ != self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700734 monitor_lock_.Unlock(self);
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700735 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700736 return;
737 }
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800738
Elliott Hughesdf42c482013-01-09 12:49:02 -0800739 // We need to turn a zero-length timed wait into a regular wait because
740 // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
741 if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
742 why = kWaiting;
743 }
744
Elliott Hughes5f791332011-09-15 17:45:30 -0700745 // Enforce the timeout range.
746 if (ms < 0 || ns < 0 || ns > 999999) {
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700747 monitor_lock_.Unlock(self);
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000748 self->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
Ian Rogersef7d42f2014-01-06 12:55:46 -0800749 "timeout arguments out of range: ms=%" PRId64 " ns=%d", ms, ns);
Elliott Hughes5f791332011-09-15 17:45:30 -0700750 return;
751 }
752
Elliott Hughes5f791332011-09-15 17:45:30 -0700753 /*
754 * Add ourselves to the set of threads waiting on this monitor, and
755 * release our hold. We need to let it go even if we're a few levels
756 * deep in a recursive lock, and we need to restore that later.
757 *
758 * We append to the wait set ahead of clearing the count and owner
759 * fields so the subroutine can check that the calling thread owns
760 * the monitor. Aside from that, the order of member updates is
761 * not order sensitive as we hold the pthread mutex.
762 */
763 AppendToWaitSet(self);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700764 ++num_waiters_;
Ian Rogers0399dde2012-06-06 17:09:28 -0700765 int prev_lock_count = lock_count_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700766 lock_count_ = 0;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700767 owner_ = nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700768 ArtMethod* saved_method = locking_method_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700769 locking_method_ = nullptr;
Ian Rogers0399dde2012-06-06 17:09:28 -0700770 uintptr_t saved_dex_pc = locking_dex_pc_;
771 locking_dex_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700772
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700773 AtraceMonitorUnlock(); // For the implict Unlock() just above. This will only end the deepest
774 // nesting, but that is enough for the visualization, and corresponds to
775 // the single Lock() we do afterwards.
776 AtraceMonitorLock(self, GetObject(), true /* is_wait */);
777
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800778 bool was_interrupted = false;
Alex Light77fee872017-09-05 14:51:49 -0700779 bool timed_out = false;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700780 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700781 // Update thread state. If the GC wakes up, it'll ignore us, knowing
782 // that we won't touch any references in this state, and we'll check
783 // our suspend mode before we transition out.
784 ScopedThreadSuspension sts(self, why);
785
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700786 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700787 MutexLock mu(self, *self->GetWaitMutex());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700788
789 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700790 // non-null a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700791 // up.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700792 DCHECK(self->GetWaitMonitor() == nullptr);
793 self->SetWaitMonitor(this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700794
795 // Release the monitor lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700796 monitor_contenders_.Signal(self);
797 monitor_lock_.Unlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700798
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800799 // Handle the case where the thread was interrupted before we called wait().
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000800 if (self->IsInterrupted()) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800801 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700802 } else {
803 // Wait for a notification or a timeout to occur.
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800804 if (why == kWaiting) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700805 self->GetWaitConditionVariable()->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700806 } else {
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800807 DCHECK(why == kTimedWaiting || why == kSleeping) << why;
Alex Light77fee872017-09-05 14:51:49 -0700808 timed_out = self->GetWaitConditionVariable()->TimedWait(self, ms, ns);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700809 }
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000810 was_interrupted = self->IsInterrupted();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700811 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700812 }
813
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800814 {
815 // We reset the thread's wait_monitor_ field after transitioning back to runnable so
816 // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
817 // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
818 // are waiting on "null".)
Ian Rogersdd7624d2014-03-14 17:43:00 -0700819 MutexLock mu(self, *self->GetWaitMutex());
820 DCHECK(self->GetWaitMonitor() != nullptr);
821 self->SetWaitMonitor(nullptr);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800822 }
823
Mathieu Chartierdaed5d82016-03-10 10:49:35 -0800824 // Allocate the interrupted exception not holding the monitor lock since it may cause a GC.
825 // If the GC requires acquiring the monitor for enqueuing cleared references, this would
826 // cause a deadlock if the monitor is held.
827 if (was_interrupted && interruptShouldThrow) {
828 /*
829 * We were interrupted while waiting, or somebody interrupted an
830 * un-interruptible thread earlier and we're bailing out immediately.
831 *
832 * The doc sayeth: "The interrupted status of the current thread is
833 * cleared when this exception is thrown."
834 */
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000835 self->SetInterrupted(false);
Mathieu Chartierdaed5d82016-03-10 10:49:35 -0800836 self->ThrowNewException("Ljava/lang/InterruptedException;", nullptr);
837 }
838
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700839 AtraceMonitorUnlock(); // End Wait().
840
Alex Light77fee872017-09-05 14:51:49 -0700841 // We just slept, tell the runtime callbacks about this.
842 Runtime::Current()->GetRuntimeCallbacks()->MonitorWaitFinished(this, timed_out);
843
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700844 // Re-acquire the monitor and lock.
Alex Light77fee872017-09-05 14:51:49 -0700845 Lock<LockReason::kForWait>(self);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700846 monitor_lock_.Lock(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700847 self->GetWaitMutex()->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700848
Elliott Hughes5f791332011-09-15 17:45:30 -0700849 /*
850 * We remove our thread from wait set after restoring the count
851 * and owner fields so the subroutine can check that the calling
852 * thread owns the monitor. Aside from that, the order of member
853 * updates is not order sensitive as we hold the pthread mutex.
854 */
855 owner_ = self;
Ian Rogers0399dde2012-06-06 17:09:28 -0700856 lock_count_ = prev_lock_count;
857 locking_method_ = saved_method;
858 locking_dex_pc_ = saved_dex_pc;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700859 --num_waiters_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700860 RemoveFromWaitSet(self);
861
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700862 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700863}
864
865void Monitor::Notify(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700866 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700867 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700868 // Make sure that we hold the lock.
869 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800870 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700871 return;
872 }
873 // Signal the first waiting thread in the wait set.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700874 while (wait_set_ != nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700875 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700876 wait_set_ = thread->GetWaitNext();
877 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700878
879 // Check to see if the thread is still waiting.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800880 MutexLock wait_mu(self, *thread->GetWaitMutex());
Ian Rogersdd7624d2014-03-14 17:43:00 -0700881 if (thread->GetWaitMonitor() != nullptr) {
882 thread->GetWaitConditionVariable()->Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700883 return;
884 }
885 }
886}
887
888void Monitor::NotifyAll(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700889 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700890 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700891 // Make sure that we hold the lock.
892 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800893 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700894 return;
895 }
896 // Signal all threads in the wait set.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700897 while (wait_set_ != nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700898 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700899 wait_set_ = thread->GetWaitNext();
900 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700901 thread->Notify();
902 }
903}
904
Mathieu Chartier590fee92013-09-13 13:46:47 -0700905bool Monitor::Deflate(Thread* self, mirror::Object* obj) {
906 DCHECK(obj != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700907 // Don't need volatile since we only deflate with mutators suspended.
908 LockWord lw(obj->GetLockWord(false));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700909 // If the lock isn't an inflated monitor, then we don't need to deflate anything.
910 if (lw.GetState() == LockWord::kFatLocked) {
911 Monitor* monitor = lw.FatLockMonitor();
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700912 DCHECK(monitor != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700913 MutexLock mu(self, monitor->monitor_lock_);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700914 // Can't deflate if we have anybody waiting on the CV.
915 if (monitor->num_waiters_ > 0) {
916 return false;
917 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700918 Thread* owner = monitor->owner_;
919 if (owner != nullptr) {
920 // Can't deflate if we are locked and have a hash code.
921 if (monitor->HasHashCode()) {
922 return false;
923 }
924 // Can't deflate if our lock count is too high.
Mathieu Chartier1cf194f2016-11-01 20:13:24 -0700925 if (static_cast<uint32_t>(monitor->lock_count_) > LockWord::kThinLockMaxCount) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700926 return false;
927 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700928 // Deflate to a thin lock.
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700929 LockWord new_lw = LockWord::FromThinLockId(owner->GetThreadId(),
930 monitor->lock_count_,
931 lw.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800932 // Assume no concurrent read barrier state changes as mutators are suspended.
933 obj->SetLockWord(new_lw, false);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700934 VLOG(monitor) << "Deflated " << obj << " to thin lock " << owner->GetTid() << " / "
935 << monitor->lock_count_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700936 } else if (monitor->HasHashCode()) {
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700937 LockWord new_lw = LockWord::FromHashCode(monitor->GetHashCode(), lw.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800938 // Assume no concurrent read barrier state changes as mutators are suspended.
939 obj->SetLockWord(new_lw, false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700940 VLOG(monitor) << "Deflated " << obj << " to hash monitor " << monitor->GetHashCode();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700941 } else {
942 // No lock and no hash, just put an empty lock word inside the object.
Mathieu Chartier36a270a2016-07-28 18:08:51 -0700943 LockWord new_lw = LockWord::FromDefault(lw.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800944 // Assume no concurrent read barrier state changes as mutators are suspended.
945 obj->SetLockWord(new_lw, false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700946 VLOG(monitor) << "Deflated" << obj << " to empty lock word";
Mathieu Chartier590fee92013-09-13 13:46:47 -0700947 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700948 // 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 -0700949 // next GC.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700950 monitor->obj_ = GcRoot<mirror::Object>(nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700951 }
952 return true;
953}
954
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700955void Monitor::Inflate(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code) {
Andreas Gampe74240812014-04-17 10:35:09 -0700956 DCHECK(self != nullptr);
957 DCHECK(obj != nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700958 // Allocate and acquire a new monitor.
Andreas Gampe74240812014-04-17 10:35:09 -0700959 Monitor* m = MonitorPool::CreateMonitor(self, owner, obj, hash_code);
960 DCHECK(m != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700961 if (m->Install(self)) {
Haifeng Li86ab7912014-05-16 10:47:59 +0800962 if (owner != nullptr) {
963 VLOG(monitor) << "monitor: thread" << owner->GetThreadId()
Andreas Gampe74240812014-04-17 10:35:09 -0700964 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800965 } else {
966 VLOG(monitor) << "monitor: Inflate with hashcode " << hash_code
Andreas Gampe74240812014-04-17 10:35:09 -0700967 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800968 }
Andreas Gampe74240812014-04-17 10:35:09 -0700969 Runtime::Current()->GetMonitorList()->Add(m);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700970 CHECK_EQ(obj->GetLockWord(true).GetState(), LockWord::kFatLocked);
Andreas Gampe74240812014-04-17 10:35:09 -0700971 } else {
972 MonitorPool::ReleaseMonitor(self, m);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700973 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700974}
975
Mathieu Chartier0cd81352014-05-22 16:48:55 -0700976void Monitor::InflateThinLocked(Thread* self, Handle<mirror::Object> obj, LockWord lock_word,
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700977 uint32_t hash_code) {
978 DCHECK_EQ(lock_word.GetState(), LockWord::kThinLocked);
979 uint32_t owner_thread_id = lock_word.ThinLockOwner();
980 if (owner_thread_id == self->GetThreadId()) {
981 // We own the monitor, we can easily inflate it.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700982 Inflate(self, self, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700983 } else {
984 ThreadList* thread_list = Runtime::Current()->GetThreadList();
985 // Suspend the owner, inflate. First change to blocked and give up mutator_lock_.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700986 self->SetMonitorEnterObject(obj.Get());
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700987 bool timed_out;
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700988 Thread* owner;
989 {
Alex Light77fee872017-09-05 14:51:49 -0700990 ScopedThreadSuspension sts(self, kWaitingForLockInflation);
Alex Light46f93402017-06-29 11:59:50 -0700991 owner = thread_list->SuspendThreadByThreadId(owner_thread_id,
992 SuspendReason::kInternal,
993 &timed_out);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700994 }
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700995 if (owner != nullptr) {
996 // We succeeded in suspending the thread, check the lock's status didn't change.
997 lock_word = obj->GetLockWord(true);
998 if (lock_word.GetState() == LockWord::kThinLocked &&
999 lock_word.ThinLockOwner() == owner_thread_id) {
1000 // Go ahead and inflate the lock.
1001 Inflate(self, owner, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001002 }
Alex Light88fd7202017-06-30 08:31:59 -07001003 bool resumed = thread_list->Resume(owner, SuspendReason::kInternal);
1004 DCHECK(resumed);
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001005 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07001006 self->SetMonitorEnterObject(nullptr);
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001007 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001008}
1009
Ian Rogers719d1a32014-03-06 12:13:39 -08001010// Fool annotalysis into thinking that the lock on obj is acquired.
1011static mirror::Object* FakeLock(mirror::Object* obj)
1012 EXCLUSIVE_LOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
1013 return obj;
1014}
1015
1016// Fool annotalysis into thinking that the lock on obj is release.
1017static mirror::Object* FakeUnlock(mirror::Object* obj)
1018 UNLOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
1019 return obj;
1020}
1021
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07001022mirror::Object* Monitor::MonitorEnter(Thread* self, mirror::Object* obj, bool trylock) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001023 DCHECK(self != nullptr);
1024 DCHECK(obj != nullptr);
Mathieu Chartier2d096c92015-10-12 16:18:20 -07001025 self->AssertThreadSuspensionIsAllowable();
Ian Rogers719d1a32014-03-06 12:13:39 -08001026 obj = FakeLock(obj);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001027 uint32_t thread_id = self->GetThreadId();
1028 size_t contention_count = 0;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001029 StackHandleScope<1> hs(self);
1030 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001031 while (true) {
Hans Boehmb3da36c2016-12-15 13:12:59 -08001032 // We initially read the lockword with ordinary Java/relaxed semantics. When stronger
1033 // semantics are needed, we address it below. Since GetLockWord bottoms out to a relaxed load,
1034 // we can fix it later, in an infrequently executed case, with a fence.
1035 LockWord lock_word = h_obj->GetLockWord(false);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001036 switch (lock_word.GetState()) {
1037 case LockWord::kUnlocked: {
Hans Boehmb3da36c2016-12-15 13:12:59 -08001038 // No ordering required for preceding lockword read, since we retest.
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001039 LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0, lock_word.GCState()));
Hans Boehmb3da36c2016-12-15 13:12:59 -08001040 if (h_obj->CasLockWordWeakAcquire(lock_word, thin_locked)) {
Andreas Gampec7ed09b2016-04-25 20:08:55 -07001041 AtraceMonitorLock(self, h_obj.Get(), false /* is_wait */);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001042 return h_obj.Get(); // Success!
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001043 }
1044 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -07001045 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001046 case LockWord::kThinLocked: {
1047 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1048 if (owner_thread_id == thread_id) {
Hans Boehmb3da36c2016-12-15 13:12:59 -08001049 // No ordering required for initial lockword read.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001050 // We own the lock, increase the recursion count.
1051 uint32_t new_count = lock_word.ThinLockCount() + 1;
1052 if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001053 LockWord thin_locked(LockWord::FromThinLockId(thread_id,
1054 new_count,
1055 lock_word.GCState()));
Hans Boehmb3da36c2016-12-15 13:12:59 -08001056 // Only this thread pays attention to the count. Thus there is no need for stronger
1057 // than relaxed memory ordering.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001058 if (!kUseReadBarrier) {
Hans Boehmb3da36c2016-12-15 13:12:59 -08001059 h_obj->SetLockWord(thin_locked, false /* volatile */);
Andreas Gampec7ed09b2016-04-25 20:08:55 -07001060 AtraceMonitorLock(self, h_obj.Get(), false /* is_wait */);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001061 return h_obj.Get(); // Success!
1062 } else {
1063 // Use CAS to preserve the read barrier state.
Hans Boehmb3da36c2016-12-15 13:12:59 -08001064 if (h_obj->CasLockWordWeakRelaxed(lock_word, thin_locked)) {
Andreas Gampec7ed09b2016-04-25 20:08:55 -07001065 AtraceMonitorLock(self, h_obj.Get(), false /* is_wait */);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001066 return h_obj.Get(); // Success!
1067 }
1068 }
1069 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -07001070 } else {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001071 // We'd overflow the recursion count, so inflate the monitor.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001072 InflateThinLocked(self, h_obj, lock_word, 0);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001073 }
1074 } else {
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07001075 if (trylock) {
1076 return nullptr;
1077 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001078 // Contention.
1079 contention_count++;
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001080 Runtime* runtime = Runtime::Current();
Hans Boehmb3da36c2016-12-15 13:12:59 -08001081 if (contention_count <= runtime->GetMaxSpinsBeforeThinLockInflation()) {
Alex Light77fee872017-09-05 14:51:49 -07001082 // TODO: Consider switching the thread state to kWaitingForLockInflation when we are
1083 // yielding. Use sched_yield instead of NanoSleep since NanoSleep can wait much longer
1084 // than the parameter you pass in. This can cause thread suspension to take excessively
1085 // long and make long pauses. See b/16307460.
Hans Boehmb3da36c2016-12-15 13:12:59 -08001086 // TODO: We should literally spin first, without sched_yield. Sched_yield either does
1087 // nothing (at significant expense), or guarantees that we wait at least microseconds.
1088 // If the owner is running, I would expect the median lock hold time to be hundreds
1089 // of nanoseconds or less.
Mathieu Chartier251755c2014-07-15 18:10:25 -07001090 sched_yield();
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001091 } else {
1092 contention_count = 0;
Hans Boehmb3da36c2016-12-15 13:12:59 -08001093 // No ordering required for initial lockword read. Install rereads it anyway.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001094 InflateThinLocked(self, h_obj, lock_word, 0);
Elliott Hughes5f791332011-09-15 17:45:30 -07001095 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001096 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001097 continue; // Start from the beginning.
Elliott Hughes5f791332011-09-15 17:45:30 -07001098 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001099 case LockWord::kFatLocked: {
Hans Boehmb3da36c2016-12-15 13:12:59 -08001100 // We should have done an acquire read of the lockword initially, to ensure
1101 // visibility of the monitor data structure. Use an explicit fence instead.
1102 QuasiAtomic::ThreadFenceAcquire();
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001103 Monitor* mon = lock_word.FatLockMonitor();
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07001104 if (trylock) {
1105 return mon->TryLock(self) ? h_obj.Get() : nullptr;
1106 } else {
1107 mon->Lock(self);
1108 return h_obj.Get(); // Success!
1109 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001110 }
Ian Rogers719d1a32014-03-06 12:13:39 -08001111 case LockWord::kHashCode:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001112 // Inflate with the existing hashcode.
Hans Boehmb3da36c2016-12-15 13:12:59 -08001113 // Again no ordering required for initial lockword read, since we don't rely
1114 // on the visibility of any prior computation.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001115 Inflate(self, nullptr, h_obj.Get(), lock_word.GetHashCode());
Ian Rogers719d1a32014-03-06 12:13:39 -08001116 continue; // Start from the beginning.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001117 default: {
1118 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Andreas Gampec7ed09b2016-04-25 20:08:55 -07001119 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001120 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001121 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001122 }
1123}
1124
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001125bool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001126 DCHECK(self != nullptr);
1127 DCHECK(obj != nullptr);
Mathieu Chartier2d096c92015-10-12 16:18:20 -07001128 self->AssertThreadSuspensionIsAllowable();
Ian Rogers719d1a32014-03-06 12:13:39 -08001129 obj = FakeUnlock(obj);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001130 StackHandleScope<1> hs(self);
1131 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001132 while (true) {
1133 LockWord lock_word = obj->GetLockWord(true);
1134 switch (lock_word.GetState()) {
1135 case LockWord::kHashCode:
1136 // Fall-through.
1137 case LockWord::kUnlocked:
Mathieu Chartier61b3cd42016-04-18 11:43:29 -07001138 FailedUnlock(h_obj.Get(), self->GetThreadId(), 0u, nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001139 return false; // Failure.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001140 case LockWord::kThinLocked: {
1141 uint32_t thread_id = self->GetThreadId();
1142 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1143 if (owner_thread_id != thread_id) {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -07001144 FailedUnlock(h_obj.Get(), thread_id, owner_thread_id, nullptr);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001145 return false; // Failure.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001146 } else {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001147 // We own the lock, decrease the recursion count.
1148 LockWord new_lw = LockWord::Default();
1149 if (lock_word.ThinLockCount() != 0) {
1150 uint32_t new_count = lock_word.ThinLockCount() - 1;
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001151 new_lw = LockWord::FromThinLockId(thread_id, new_count, lock_word.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001152 } else {
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001153 new_lw = LockWord::FromDefault(lock_word.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001154 }
1155 if (!kUseReadBarrier) {
1156 DCHECK_EQ(new_lw.ReadBarrierState(), 0U);
Hans Boehmb3da36c2016-12-15 13:12:59 -08001157 // TODO: This really only needs memory_order_release, but we currently have
1158 // no way to specify that. In fact there seem to be no legitimate uses of SetLockWord
1159 // with a final argument of true. This slows down x86 and ARMv7, but probably not v8.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001160 h_obj->SetLockWord(new_lw, true);
Andreas Gampe6e759ad2016-05-17 10:13:10 -07001161 AtraceMonitorUnlock();
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001162 // Success!
1163 return true;
1164 } else {
1165 // Use CAS to preserve the read barrier state.
Hans Boehmb3da36c2016-12-15 13:12:59 -08001166 if (h_obj->CasLockWordWeakRelease(lock_word, new_lw)) {
Andreas Gampe6e759ad2016-05-17 10:13:10 -07001167 AtraceMonitorUnlock();
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001168 // Success!
1169 return true;
1170 }
1171 }
1172 continue; // Go again.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001173 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001174 }
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001175 case LockWord::kFatLocked: {
1176 Monitor* mon = lock_word.FatLockMonitor();
1177 return mon->Unlock(self);
1178 }
1179 default: {
1180 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1181 return false;
1182 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001183 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001184 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001185}
1186
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001187void Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
Elliott Hughes4cd121e2013-01-07 17:35:41 -08001188 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001189 DCHECK(self != nullptr);
1190 DCHECK(obj != nullptr);
Alex Light77fee872017-09-05 14:51:49 -07001191 StackHandleScope<1> hs(self);
1192 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
1193
1194 Runtime::Current()->GetRuntimeCallbacks()->ObjectWaitStart(h_obj, ms);
Alex Light848574c2017-09-25 16:59:39 -07001195 if (UNLIKELY(self->ObserveAsyncException() || self->IsExceptionPending())) {
Alex Light77fee872017-09-05 14:51:49 -07001196 // See b/65558434 for information on handling of exceptions here.
1197 return;
1198 }
1199
1200 LockWord lock_word = h_obj->GetLockWord(true);
Ian Rogers43c69cc2014-08-15 11:09:28 -07001201 while (lock_word.GetState() != LockWord::kFatLocked) {
1202 switch (lock_word.GetState()) {
1203 case LockWord::kHashCode:
1204 // Fall-through.
1205 case LockWord::kUnlocked:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001206 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
1207 return; // Failure.
Ian Rogers43c69cc2014-08-15 11:09:28 -07001208 case LockWord::kThinLocked: {
1209 uint32_t thread_id = self->GetThreadId();
1210 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1211 if (owner_thread_id != thread_id) {
1212 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
1213 return; // Failure.
1214 } else {
1215 // We own the lock, inflate to enqueue ourself on the Monitor. May fail spuriously so
1216 // re-load.
Alex Light77fee872017-09-05 14:51:49 -07001217 Inflate(self, self, h_obj.Get(), 0);
1218 lock_word = h_obj->GetLockWord(true);
Ian Rogers43c69cc2014-08-15 11:09:28 -07001219 }
1220 break;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001221 }
Ian Rogers43c69cc2014-08-15 11:09:28 -07001222 case LockWord::kFatLocked: // Unreachable given the loop condition above. Fall-through.
1223 default: {
1224 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1225 return;
1226 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001227 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001228 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001229 Monitor* mon = lock_word.FatLockMonitor();
1230 mon->Wait(self, ms, ns, interruptShouldThrow, why);
Elliott Hughes5f791332011-09-15 17:45:30 -07001231}
1232
Ian Rogers13c479e2013-10-11 07:59:01 -07001233void Monitor::DoNotify(Thread* self, mirror::Object* obj, bool notify_all) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001234 DCHECK(self != nullptr);
1235 DCHECK(obj != nullptr);
1236 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001237 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001238 case LockWord::kHashCode:
1239 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001240 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -08001241 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001242 return; // Failure.
1243 case LockWord::kThinLocked: {
1244 uint32_t thread_id = self->GetThreadId();
1245 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1246 if (owner_thread_id != thread_id) {
1247 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
1248 return; // Failure.
1249 } else {
1250 // We own the lock but there's no Monitor and therefore no waiters.
1251 return; // Success.
1252 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001253 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001254 case LockWord::kFatLocked: {
1255 Monitor* mon = lock_word.FatLockMonitor();
1256 if (notify_all) {
1257 mon->NotifyAll(self);
1258 } else {
1259 mon->Notify(self);
1260 }
1261 return; // Success.
1262 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001263 default: {
1264 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
1265 return;
1266 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001267 }
1268}
1269
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001270uint32_t Monitor::GetLockOwnerThreadId(mirror::Object* obj) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001271 DCHECK(obj != nullptr);
1272 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001273 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001274 case LockWord::kHashCode:
1275 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001276 case LockWord::kUnlocked:
1277 return ThreadList::kInvalidThreadId;
1278 case LockWord::kThinLocked:
1279 return lock_word.ThinLockOwner();
1280 case LockWord::kFatLocked: {
1281 Monitor* mon = lock_word.FatLockMonitor();
1282 return mon->GetOwnerThreadId();
Elliott Hughes5f791332011-09-15 17:45:30 -07001283 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001284 default: {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001285 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001286 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001287 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001288 }
1289}
1290
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001291void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
Ian Rogersd803bc72014-04-01 15:33:03 -07001292 // Determine the wait message and object we're waiting or blocked upon.
1293 mirror::Object* pretty_object = nullptr;
1294 const char* wait_message = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001295 uint32_t lock_owner = ThreadList::kInvalidThreadId;
Ian Rogersd803bc72014-04-01 15:33:03 -07001296 ThreadState state = thread->GetState();
Elliott Hughesb4e94fd2013-01-08 14:41:26 -08001297 if (state == kWaiting || state == kTimedWaiting || state == kSleeping) {
Ian Rogersd803bc72014-04-01 15:33:03 -07001298 wait_message = (state == kSleeping) ? " - sleeping on " : " - waiting on ";
1299 Thread* self = Thread::Current();
1300 MutexLock mu(self, *thread->GetWaitMutex());
1301 Monitor* monitor = thread->GetWaitMonitor();
1302 if (monitor != nullptr) {
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001303 pretty_object = monitor->GetObject();
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001304 }
Alex Light77fee872017-09-05 14:51:49 -07001305 } else if (state == kBlocked || state == kWaitingForLockInflation) {
1306 wait_message = (state == kBlocked) ? " - waiting to lock "
1307 : " - waiting for lock inflation of ";
Ian Rogersd803bc72014-04-01 15:33:03 -07001308 pretty_object = thread->GetMonitorEnterObject();
1309 if (pretty_object != nullptr) {
Hiroshi Yamauchi7b08ae42016-10-04 15:20:36 -07001310 if (kUseReadBarrier && Thread::Current()->GetIsGcMarking()) {
1311 // We may call Thread::Dump() in the middle of the CC thread flip and this thread's stack
1312 // may have not been flipped yet and "pretty_object" may be a from-space (stale) ref, in
1313 // which case the GetLockOwnerThreadId() call below will crash. So explicitly mark/forward
1314 // it here.
1315 pretty_object = ReadBarrier::Mark(pretty_object);
1316 }
Ian Rogersd803bc72014-04-01 15:33:03 -07001317 lock_owner = pretty_object->GetLockOwnerThreadId();
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001318 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001319 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001320
Ian Rogersd803bc72014-04-01 15:33:03 -07001321 if (wait_message != nullptr) {
1322 if (pretty_object == nullptr) {
1323 os << wait_message << "an unknown object";
1324 } else {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001325 if ((pretty_object->GetLockWord(true).GetState() == LockWord::kThinLocked) &&
Ian Rogersd803bc72014-04-01 15:33:03 -07001326 Locks::mutator_lock_->IsExclusiveHeld(Thread::Current())) {
1327 // Getting the identity hashcode here would result in lock inflation and suspension of the
1328 // current thread, which isn't safe if this is the only runnable thread.
1329 os << wait_message << StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)",
1330 reinterpret_cast<intptr_t>(pretty_object),
David Sehr709b0702016-10-13 09:12:37 -07001331 pretty_object->PrettyTypeOf().c_str());
Ian Rogersd803bc72014-04-01 15:33:03 -07001332 } else {
1333 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
Mathieu Chartier49361592015-01-22 16:36:10 -08001334 // Call PrettyTypeOf before IdentityHashCode since IdentityHashCode can cause thread
1335 // suspension and move pretty_object.
David Sehr709b0702016-10-13 09:12:37 -07001336 const std::string pretty_type(pretty_object->PrettyTypeOf());
Ian Rogersd803bc72014-04-01 15:33:03 -07001337 os << wait_message << StringPrintf("<0x%08x> (a %s)", pretty_object->IdentityHashCode(),
Mathieu Chartier49361592015-01-22 16:36:10 -08001338 pretty_type.c_str());
Ian Rogersd803bc72014-04-01 15:33:03 -07001339 }
1340 }
1341 // - waiting to lock <0x613f83d8> (a java.lang.Object) held by thread 5
1342 if (lock_owner != ThreadList::kInvalidThreadId) {
1343 os << " held by thread " << lock_owner;
1344 }
1345 os << "\n";
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001346 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001347}
1348
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001349mirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -08001350 // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
1351 // definition of contended that includes a monitor a thread is trying to enter...
Ian Rogersdd7624d2014-03-14 17:43:00 -07001352 mirror::Object* result = thread->GetMonitorEnterObject();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001353 if (result == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001354 // ...but also a monitor that the thread is waiting on.
Ian Rogersdd7624d2014-03-14 17:43:00 -07001355 MutexLock mu(Thread::Current(), *thread->GetWaitMutex());
1356 Monitor* monitor = thread->GetWaitMonitor();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001357 if (monitor != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001358 result = monitor->GetObject();
Elliott Hughesf9501702013-01-11 11:22:27 -08001359 }
1360 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001361 return result;
Elliott Hughesf9501702013-01-11 11:22:27 -08001362}
1363
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001364void Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
Andreas Gampe760172c2014-08-16 13:41:10 -07001365 void* callback_context, bool abort_on_failure) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001366 ArtMethod* m = stack_visitor->GetMethod();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001367 CHECK(m != nullptr);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001368
1369 // Native methods are an easy special case.
1370 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
1371 if (m->IsNative()) {
1372 if (m->IsSynchronized()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001373 mirror::Object* jni_this =
1374 stack_visitor->GetCurrentHandleScope(sizeof(void*))->GetReference(0);
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001375 callback(jni_this, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001376 }
1377 return;
1378 }
1379
jeffhao61f916c2012-10-25 17:48:51 -07001380 // Proxy methods should not be synchronized.
1381 if (m->IsProxyMethod()) {
1382 CHECK(!m->IsSynchronized());
1383 return;
1384 }
1385
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001386 // Is there any reason to believe there's any synchronization in this method?
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001387 const DexFile::CodeItem* code_item = m->GetCodeItem();
David Sehr709b0702016-10-13 09:12:37 -07001388 CHECK(code_item != nullptr) << m->PrettyMethod();
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001389 if (code_item->tries_size_ == 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001390 return; // No "tries" implies no synchronization, so no held locks to report.
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001391 }
1392
Andreas Gampe760172c2014-08-16 13:41:10 -07001393 // Get the dex pc. If abort_on_failure is false, GetDexPc will not abort in the case it cannot
1394 // find the dex pc, and instead return kDexNoIndex. Then bail out, as it indicates we have an
1395 // inconsistent stack anyways.
1396 uint32_t dex_pc = stack_visitor->GetDexPc(abort_on_failure);
Andreas Gampee2abbc62017-09-15 11:59:26 -07001397 if (!abort_on_failure && dex_pc == dex::kDexNoIndex) {
David Sehr709b0702016-10-13 09:12:37 -07001398 LOG(ERROR) << "Could not find dex_pc for " << m->PrettyMethod();
Andreas Gampe760172c2014-08-16 13:41:10 -07001399 return;
1400 }
1401
Elliott Hughes80537bb2013-01-04 16:37:26 -08001402 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
1403 // the locks held in this stack frame.
Andreas Gampeaaf0d382017-11-27 14:10:21 -08001404 std::vector<verifier::MethodVerifier::DexLockInfo> monitor_enter_dex_pcs;
Andreas Gampe760172c2014-08-16 13:41:10 -07001405 verifier::MethodVerifier::FindLocksAtDexPc(m, dex_pc, &monitor_enter_dex_pcs);
Andreas Gampeaaf0d382017-11-27 14:10:21 -08001406 for (verifier::MethodVerifier::DexLockInfo& dex_lock_info : monitor_enter_dex_pcs) {
1407 // As a debug check, check that dex PC corresponds to a monitor-enter.
1408 if (kIsDebugBuild) {
1409 const Instruction* monitor_enter_instruction =
1410 Instruction::At(&code_item->insns_[dex_lock_info.dex_pc]);
1411 CHECK_EQ(monitor_enter_instruction->Opcode(), Instruction::MONITOR_ENTER)
1412 << "expected monitor-enter @" << dex_lock_info.dex_pc << "; was "
1413 << reinterpret_cast<const void*>(monitor_enter_instruction);
1414 }
Elliott Hughes80537bb2013-01-04 16:37:26 -08001415
Andreas Gampeaaf0d382017-11-27 14:10:21 -08001416 // Iterate through the set of dex registers, as the compiler may not have held all of them
1417 // live.
1418 bool success = false;
1419 for (uint32_t dex_reg : dex_lock_info.dex_registers) {
1420 uint32_t value;
1421 success = stack_visitor->GetVReg(m, dex_reg, kReferenceVReg, &value);
1422 if (success) {
1423 mirror::Object* o = reinterpret_cast<mirror::Object*>(value);
1424 callback(o, callback_context);
1425 break;
1426 }
1427 }
1428 DCHECK(success) << "Failed to find/read reference for monitor-enter at dex pc "
1429 << dex_lock_info.dex_pc
1430 << " in method "
1431 << m->PrettyMethod();
1432 if (!success) {
1433 LOG(WARNING) << "Had a lock reported for dex pc " << dex_lock_info.dex_pc
1434 << " but was not able to fetch a corresponding object!";
1435 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001436 }
1437}
1438
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001439bool Monitor::IsValidLockWord(LockWord lock_word) {
1440 switch (lock_word.GetState()) {
1441 case LockWord::kUnlocked:
1442 // Nothing to check.
1443 return true;
1444 case LockWord::kThinLocked:
1445 // Basic sanity check of owner.
1446 return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
1447 case LockWord::kFatLocked: {
1448 // Check the monitor appears in the monitor list.
1449 Monitor* mon = lock_word.FatLockMonitor();
1450 MonitorList* list = Runtime::Current()->GetMonitorList();
1451 MutexLock mu(Thread::Current(), list->monitor_list_lock_);
1452 for (Monitor* list_mon : list->list_) {
1453 if (mon == list_mon) {
1454 return true; // Found our monitor.
1455 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001456 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001457 return false; // Fail - unowned monitor in an object.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001458 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001459 case LockWord::kHashCode:
1460 return true;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001461 default:
1462 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001463 UNREACHABLE();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001464 }
1465}
1466
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001467bool Monitor::IsLocked() REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001468 MutexLock mu(Thread::Current(), monitor_lock_);
1469 return owner_ != nullptr;
1470}
1471
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -07001472void Monitor::TranslateLocation(ArtMethod* method,
1473 uint32_t dex_pc,
1474 const char** source_file,
1475 int32_t* line_number) {
jeffhao33dc7712011-11-09 17:54:24 -08001476 // If method is null, location is unknown
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001477 if (method == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001478 *source_file = "";
1479 *line_number = 0;
jeffhao33dc7712011-11-09 17:54:24 -08001480 return;
1481 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001482 *source_file = method->GetDeclaringClassSourceFile();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001483 if (*source_file == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001484 *source_file = "";
Elliott Hughes12c51e32012-01-17 20:25:05 -08001485 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001486 *line_number = method->GetLineNumFromDexPC(dex_pc);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001487}
1488
1489uint32_t Monitor::GetOwnerThreadId() {
1490 MutexLock mu(Thread::Current(), monitor_lock_);
1491 Thread* owner = owner_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001492 if (owner != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001493 return owner->GetThreadId();
1494 } else {
1495 return ThreadList::kInvalidThreadId;
1496 }
jeffhao33dc7712011-11-09 17:54:24 -08001497}
1498
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001499MonitorList::MonitorList()
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001500 : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock", kMonitorListLock),
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001501 monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001502}
1503
1504MonitorList::~MonitorList() {
Andreas Gampe74240812014-04-17 10:35:09 -07001505 Thread* self = Thread::Current();
1506 MutexLock mu(self, monitor_list_lock_);
1507 // Release all monitors to the pool.
1508 // TODO: Is it an invariant that *all* open monitors are in the list? Then we could
1509 // clear faster in the pool.
1510 MonitorPool::ReleaseMonitors(self, &list_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001511}
1512
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001513void MonitorList::DisallowNewMonitors() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001514 CHECK(!kUseReadBarrier);
Ian Rogers50b35e22012-10-04 10:09:15 -07001515 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001516 allow_new_monitors_ = false;
1517}
1518
1519void MonitorList::AllowNewMonitors() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001520 CHECK(!kUseReadBarrier);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001521 Thread* self = Thread::Current();
1522 MutexLock mu(self, monitor_list_lock_);
1523 allow_new_monitors_ = true;
1524 monitor_add_condition_.Broadcast(self);
1525}
1526
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001527void MonitorList::BroadcastForNewMonitors() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001528 Thread* self = Thread::Current();
1529 MutexLock mu(self, monitor_list_lock_);
1530 monitor_add_condition_.Broadcast(self);
1531}
1532
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001533void MonitorList::Add(Monitor* m) {
1534 Thread* self = Thread::Current();
1535 MutexLock mu(self, monitor_list_lock_);
Hiroshi Yamauchif1c6f872017-01-06 12:23:47 -08001536 // CMS needs this to block for concurrent reference processing because an object allocated during
1537 // the GC won't be marked and concurrent reference processing would incorrectly clear the JNI weak
1538 // ref. But CC (kUseReadBarrier == true) doesn't because of the to-space invariant.
1539 while (!kUseReadBarrier && UNLIKELY(!allow_new_monitors_)) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -07001540 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
1541 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -08001542 self->CheckEmptyCheckpointFromWeakRefAccess(&monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001543 monitor_add_condition_.WaitHoldingLocks(self);
1544 }
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001545 list_.push_front(m);
1546}
1547
Mathieu Chartier97509952015-07-13 14:35:43 -07001548void MonitorList::SweepMonitorList(IsMarkedVisitor* visitor) {
Andreas Gampe74240812014-04-17 10:35:09 -07001549 Thread* self = Thread::Current();
1550 MutexLock mu(self, monitor_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001551 for (auto it = list_.begin(); it != list_.end(); ) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001552 Monitor* m = *it;
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001553 // Disable the read barrier in GetObject() as this is called by GC.
1554 mirror::Object* obj = m->GetObject<kWithoutReadBarrier>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001555 // The object of a monitor can be null if we have deflated it.
Mathieu Chartier97509952015-07-13 14:35:43 -07001556 mirror::Object* new_obj = obj != nullptr ? visitor->IsMarked(obj) : nullptr;
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001557 if (new_obj == nullptr) {
1558 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001559 << obj;
Andreas Gampe74240812014-04-17 10:35:09 -07001560 MonitorPool::ReleaseMonitor(self, m);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001561 it = list_.erase(it);
1562 } else {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001563 m->SetObject(new_obj);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001564 ++it;
1565 }
1566 }
1567}
1568
Hans Boehm6fe97e02016-05-04 18:35:57 -07001569size_t MonitorList::Size() {
1570 Thread* self = Thread::Current();
1571 MutexLock mu(self, monitor_list_lock_);
1572 return list_.size();
1573}
1574
Mathieu Chartier97509952015-07-13 14:35:43 -07001575class MonitorDeflateVisitor : public IsMarkedVisitor {
1576 public:
1577 MonitorDeflateVisitor() : self_(Thread::Current()), deflate_count_(0) {}
1578
1579 virtual mirror::Object* IsMarked(mirror::Object* object) OVERRIDE
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001580 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001581 if (Monitor::Deflate(self_, object)) {
1582 DCHECK_NE(object->GetLockWord(true).GetState(), LockWord::kFatLocked);
1583 ++deflate_count_;
1584 // If we deflated, return null so that the monitor gets removed from the array.
1585 return nullptr;
1586 }
1587 return object; // Monitor was not deflated.
1588 }
1589
1590 Thread* const self_;
1591 size_t deflate_count_;
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001592};
1593
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001594size_t MonitorList::DeflateMonitors() {
Mathieu Chartier97509952015-07-13 14:35:43 -07001595 MonitorDeflateVisitor visitor;
1596 Locks::mutator_lock_->AssertExclusiveHeld(visitor.self_);
1597 SweepMonitorList(&visitor);
1598 return visitor.deflate_count_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001599}
1600
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001601MonitorInfo::MonitorInfo(mirror::Object* obj) : owner_(nullptr), entry_count_(0) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001602 DCHECK(obj != nullptr);
1603 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001604 switch (lock_word.GetState()) {
1605 case LockWord::kUnlocked:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001606 // Fall-through.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001607 case LockWord::kForwardingAddress:
1608 // Fall-through.
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001609 case LockWord::kHashCode:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001610 break;
1611 case LockWord::kThinLocked:
1612 owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
Alex Lightce568642017-09-05 16:54:25 -07001613 DCHECK(owner_ != nullptr) << "Thin-locked without owner!";
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001614 entry_count_ = 1 + lock_word.ThinLockCount();
1615 // Thin locks have no waiters.
1616 break;
1617 case LockWord::kFatLocked: {
1618 Monitor* mon = lock_word.FatLockMonitor();
1619 owner_ = mon->owner_;
Alex Lightce568642017-09-05 16:54:25 -07001620 // Here it is okay for the owner to be null since we don't reset the LockWord back to
1621 // kUnlocked until we get a GC. In cases where this hasn't happened yet we will have a fat
1622 // lock without an owner.
1623 if (owner_ != nullptr) {
1624 entry_count_ = 1 + mon->lock_count_;
1625 } else {
1626 DCHECK_EQ(mon->lock_count_, 0) << "Monitor is fat-locked without any owner!";
1627 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001628 for (Thread* waiter = mon->wait_set_; waiter != nullptr; waiter = waiter->GetWaitNext()) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001629 waiters_.push_back(waiter);
1630 }
1631 break;
Elliott Hughesf327e072013-01-09 16:01:26 -08001632 }
1633 }
1634}
1635
Elliott Hughes5f791332011-09-15 17:45:30 -07001636} // namespace art