blob: 0b6e3b25f51d6cd1158024490861c9fac11bb01e [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
Elliott Hughes76b61672012-12-12 17:47:30 -080021#include "base/mutex.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080022#include "base/stl_util.h"
jeffhao33dc7712011-11-09 17:54:24 -080023#include "class_linker.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070024#include "dex_file-inl.h"
Elliott Hughes08fc03a2012-06-26 17:34:00 -070025#include "dex_instruction.h"
Ian Rogersd9c4fc92013-10-01 19:45:43 -070026#include "lock_word-inl.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070027#include "mirror/art_method-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070028#include "mirror/class-inl.h"
Ian Rogers05f30572013-02-20 12:13:11 -080029#include "mirror/object-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080030#include "mirror/object_array-inl.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070031#include "scoped_thread_state_change.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070032#include "thread.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070033#include "thread_list.h"
Elliott Hughes08fc03a2012-06-26 17:34:00 -070034#include "verifier/method_verifier.h"
Elliott Hughes044288f2012-06-25 14:46:39 -070035#include "well_known_classes.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070036
37namespace art {
38
39/*
Ian Rogersd9c4fc92013-10-01 19:45:43 -070040 * Every Object has a monitor associated with it, but not every Object is actually locked. Even
41 * the ones that are locked do not need a full-fledged monitor until a) there is actual contention
42 * or b) wait() is called on the Object.
Elliott Hughes5f791332011-09-15 17:45:30 -070043 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070044 * For Android, we have implemented a scheme similar to the one described in Bacon et al.'s
45 * "Thin locks: featherweight synchronization for Java" (ACM 1998). Things are even easier for us,
46 * though, because we have a full 32 bits to work with.
Elliott Hughes5f791332011-09-15 17:45:30 -070047 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070048 * The two states of an Object's lock are referred to as "thin" and "fat". A lock may transition
49 * from the "thin" state to the "fat" state and this transition is referred to as inflation. Once
50 * a lock has been inflated it remains in the "fat" state indefinitely.
Elliott Hughes5f791332011-09-15 17:45:30 -070051 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070052 * The lock value itself is stored in mirror::Object::monitor_ and the representation is described
53 * in the LockWord value type.
Elliott Hughes54e7df12011-09-16 11:47:04 -070054 *
Elliott Hughes5f791332011-09-15 17:45:30 -070055 * Monitors provide:
56 * - mutually exclusive access to resources
57 * - a way for multiple threads to wait for notification
58 *
59 * In effect, they fill the role of both mutexes and condition variables.
60 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070061 * Only one thread can own the monitor at any time. There may be several threads waiting on it
62 * (the wait call unlocks it). One or more waiting threads may be getting interrupted or notified
63 * at any given time.
Elliott Hughes5f791332011-09-15 17:45:30 -070064 */
Elliott Hughes54e7df12011-09-16 11:47:04 -070065
Elliott Hughesfc861622011-10-17 17:57:47 -070066bool (*Monitor::is_sensitive_thread_hook_)() = NULL;
Elliott Hughesfc861622011-10-17 17:57:47 -070067uint32_t Monitor::lock_profiling_threshold_ = 0;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070068
Elliott Hughesfc861622011-10-17 17:57:47 -070069bool Monitor::IsSensitiveThread() {
70 if (is_sensitive_thread_hook_ != NULL) {
71 return (*is_sensitive_thread_hook_)();
72 }
73 return false;
74}
75
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -080076void Monitor::Init(uint32_t lock_profiling_threshold, bool (*is_sensitive_thread_hook)()) {
Elliott Hughesfc861622011-10-17 17:57:47 -070077 lock_profiling_threshold_ = lock_profiling_threshold;
78 is_sensitive_thread_hook_ = is_sensitive_thread_hook;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070079}
80
Ian Rogersef7d42f2014-01-06 12:55:46 -080081Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code)
Ian Rogers00f7d0e2012-07-19 15:28:27 -070082 : monitor_lock_("a monitor lock", kMonitorLock),
Ian Rogersd9c4fc92013-10-01 19:45:43 -070083 monitor_contenders_("monitor contenders", monitor_lock_),
Mathieu Chartier46bc7782013-11-12 17:03:02 -080084 num_waiters_(0),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070085 owner_(owner),
Elliott Hughes5f791332011-09-15 17:45:30 -070086 lock_count_(0),
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070087 obj_(GcRoot<mirror::Object>(obj)),
Elliott Hughes5f791332011-09-15 17:45:30 -070088 wait_set_(NULL),
Mathieu Chartierad2541a2013-10-25 10:05:23 -070089 hash_code_(hash_code),
jeffhao33dc7712011-11-09 17:54:24 -080090 locking_method_(NULL),
Ian Rogersef7d42f2014-01-06 12:55:46 -080091 locking_dex_pc_(0),
Andreas Gampe74240812014-04-17 10:35:09 -070092 monitor_id_(MonitorPool::ComputeMonitorId(this, self)) {
93#ifdef __LP64__
94 DCHECK(false) << "Should not be reached in 64b";
95 next_free_ = nullptr;
96#endif
97 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
98 // with the owner unlocking the thin-lock.
99 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
100 // The identity hash code is set for the life time of the monitor.
101}
102
103Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code,
104 MonitorId id)
105 : monitor_lock_("a monitor lock", kMonitorLock),
106 monitor_contenders_("monitor contenders", monitor_lock_),
107 num_waiters_(0),
108 owner_(owner),
109 lock_count_(0),
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700110 obj_(GcRoot<mirror::Object>(obj)),
Andreas Gampe74240812014-04-17 10:35:09 -0700111 wait_set_(NULL),
112 hash_code_(hash_code),
113 locking_method_(NULL),
114 locking_dex_pc_(0),
115 monitor_id_(id) {
116#ifdef __LP64__
117 next_free_ = nullptr;
118#endif
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700119 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
120 // with the owner unlocking the thin-lock.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800121 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700122 // The identity hash code is set for the life time of the monitor.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700123}
124
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700125int32_t Monitor::GetHashCode() {
126 while (!HasHashCode()) {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700127 if (hash_code_.CompareExchangeWeakRelaxed(0, mirror::Object::GenerateIdentityHashCode())) {
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700128 break;
129 }
130 }
131 DCHECK(HasHashCode());
Ian Rogers3e5cf302014-05-20 16:40:37 -0700132 return hash_code_.LoadRelaxed();
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700133}
134
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700135bool Monitor::Install(Thread* self) {
136 MutexLock mu(self, monitor_lock_); // Uncontended mutex acquisition as monitor isn't yet public.
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700137 CHECK(owner_ == nullptr || owner_ == self || owner_->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700138 // Propagate the lock state.
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700139 LockWord lw(GetObject()->GetLockWord(false));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700140 switch (lw.GetState()) {
141 case LockWord::kThinLocked: {
142 CHECK_EQ(owner_->GetThreadId(), lw.ThinLockOwner());
143 lock_count_ = lw.ThinLockCount();
144 break;
145 }
146 case LockWord::kHashCode: {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700147 CHECK_EQ(hash_code_.LoadRelaxed(), static_cast<int32_t>(lw.GetHashCode()));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700148 break;
149 }
150 case LockWord::kFatLocked: {
151 // The owner_ is suspended but another thread beat us to install a monitor.
152 return false;
153 }
154 case LockWord::kUnlocked: {
155 LOG(FATAL) << "Inflating unlocked lock word";
156 break;
157 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700158 default: {
159 LOG(FATAL) << "Invalid monitor state " << lw.GetState();
160 return false;
161 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700162 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700163 LockWord fat(this);
164 // Publish the updated lock word, which may race with other threads.
Ian Rogers228602f2014-07-10 02:07:54 -0700165 bool success = GetObject()->CasLockWordWeakSequentiallyConsistent(lw, fat);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700166 // Lock profiling.
Mathieu Chartier9728f912013-10-30 09:45:13 -0700167 if (success && owner_ != nullptr && lock_profiling_threshold_ != 0) {
Andreas Gampe6ec8ebd2014-07-25 13:36:56 -0700168 // Do not abort on dex pc errors. This can easily happen when we want to dump a stack trace on
169 // abort.
170 locking_method_ = owner_->GetCurrentMethod(&locking_dex_pc_, false);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700171 }
172 return success;
Elliott Hughes5f791332011-09-15 17:45:30 -0700173}
174
175Monitor::~Monitor() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700176 // Deflated monitors have a null object.
Elliott Hughes5f791332011-09-15 17:45:30 -0700177}
178
179/*
180 * Links a thread into a monitor's wait set. The monitor lock must be
181 * held by the caller of this routine.
182 */
183void Monitor::AppendToWaitSet(Thread* thread) {
184 DCHECK(owner_ == Thread::Current());
185 DCHECK(thread != NULL);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700186 DCHECK(thread->GetWaitNext() == nullptr) << thread->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700187 if (wait_set_ == NULL) {
188 wait_set_ = thread;
189 return;
190 }
191
192 // push_back.
193 Thread* t = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700194 while (t->GetWaitNext() != nullptr) {
195 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700196 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700197 t->SetWaitNext(thread);
Elliott Hughes5f791332011-09-15 17:45:30 -0700198}
199
200/*
201 * Unlinks a thread from a monitor's wait set. The monitor lock must
202 * be held by the caller of this routine.
203 */
204void Monitor::RemoveFromWaitSet(Thread *thread) {
205 DCHECK(owner_ == Thread::Current());
206 DCHECK(thread != NULL);
207 if (wait_set_ == NULL) {
208 return;
209 }
210 if (wait_set_ == thread) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700211 wait_set_ = thread->GetWaitNext();
212 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700213 return;
214 }
215
216 Thread* t = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700217 while (t->GetWaitNext() != NULL) {
218 if (t->GetWaitNext() == thread) {
219 t->SetWaitNext(thread->GetWaitNext());
220 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700221 return;
222 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700223 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700224 }
225}
226
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700227void Monitor::SetObject(mirror::Object* object) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700228 obj_ = GcRoot<mirror::Object>(object);
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700229}
230
Elliott Hughes5f791332011-09-15 17:45:30 -0700231void Monitor::Lock(Thread* self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700232 MutexLock mu(self, monitor_lock_);
233 while (true) {
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700234 if (owner_ == nullptr) { // Unowned.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700235 owner_ = self;
236 CHECK_EQ(lock_count_, 0);
237 // When debugging, save the current monitor holder for future
238 // acquisition failures to use in sampled logging.
239 if (lock_profiling_threshold_ != 0) {
240 locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
241 }
242 return;
243 } else if (owner_ == self) { // Recursive.
244 lock_count_++;
245 return;
246 }
247 // Contended.
248 const bool log_contention = (lock_profiling_threshold_ != 0);
Xin Guanb894a192014-08-22 11:55:37 -0500249 uint64_t wait_start_ms = log_contention ? MilliTime() : 0;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800250 mirror::ArtMethod* owners_method = locking_method_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700251 uint32_t owners_dex_pc = locking_dex_pc_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700252 // Do this before releasing the lock so that we don't get deflated.
253 ++num_waiters_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700254 monitor_lock_.Unlock(self); // Let go of locks in order.
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700255 self->SetMonitorEnterObject(GetObject());
Elliott Hughes5f791332011-09-15 17:45:30 -0700256 {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700257 ScopedThreadStateChange tsc(self, kBlocked); // Change to blocked and give up mutator_lock_.
258 MutexLock mu2(self, monitor_lock_); // Reacquire monitor_lock_ without mutator_lock_ for Wait.
259 if (owner_ != NULL) { // Did the owner_ give the lock up?
260 monitor_contenders_.Wait(self); // Still contended so wait.
261 // Woken from contention.
262 if (log_contention) {
263 uint64_t wait_ms = MilliTime() - wait_start_ms;
264 uint32_t sample_percent;
265 if (wait_ms >= lock_profiling_threshold_) {
266 sample_percent = 100;
267 } else {
268 sample_percent = 100 * wait_ms / lock_profiling_threshold_;
269 }
270 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
271 const char* owners_filename;
272 uint32_t owners_line_number;
273 TranslateLocation(owners_method, owners_dex_pc, &owners_filename, &owners_line_number);
274 LogContentionEvent(self, wait_ms, sample_percent, owners_filename, owners_line_number);
275 }
276 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700277 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700278 }
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700279 self->SetMonitorEnterObject(nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700280 monitor_lock_.Lock(self); // Reacquire locks in order.
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700281 --num_waiters_;
Elliott Hughesfc861622011-10-17 17:57:47 -0700282 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700283}
284
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800285static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
286 __attribute__((format(printf, 1, 2)));
287
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700288static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700289 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800290 va_list args;
291 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800292 Thread* self = Thread::Current();
293 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
294 self->ThrowNewExceptionV(throw_location, "Ljava/lang/IllegalMonitorStateException;", fmt, args);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700295 if (!Runtime::Current()->IsStarted() || VLOG_IS_ON(monitor)) {
Brian Carlstrom64277f32012-03-26 23:53:34 -0700296 std::ostringstream ss;
Ian Rogers62d6c772013-02-27 08:32:07 -0800297 self->Dump(ss);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700298 LOG(Runtime::Current()->IsStarted() ? INFO : ERROR)
299 << self->GetException(NULL)->Dump() << "\n" << ss.str();
Brian Carlstrom64277f32012-03-26 23:53:34 -0700300 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800301 va_end(args);
302}
303
Elliott Hughesd4237412012-02-21 11:24:45 -0800304static std::string ThreadToString(Thread* thread) {
305 if (thread == NULL) {
306 return "NULL";
307 }
308 std::ostringstream oss;
309 // TODO: alternatively, we could just return the thread's name.
310 oss << *thread;
311 return oss.str();
312}
313
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800314void Monitor::FailedUnlock(mirror::Object* o, Thread* expected_owner, Thread* found_owner,
Elliott Hughesffb465f2012-03-01 18:46:05 -0800315 Monitor* monitor) {
316 Thread* current_owner = NULL;
317 std::string current_owner_string;
318 std::string expected_owner_string;
319 std::string found_owner_string;
320 {
321 // TODO: isn't this too late to prevent threads from disappearing?
322 // Acquire thread list lock so threads won't disappear from under us.
Ian Rogers50b35e22012-10-04 10:09:15 -0700323 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Elliott Hughesffb465f2012-03-01 18:46:05 -0800324 // Re-read owner now that we hold lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700325 current_owner = (monitor != NULL) ? monitor->GetOwner() : NULL;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800326 // Get short descriptions of the threads involved.
327 current_owner_string = ThreadToString(current_owner);
328 expected_owner_string = ThreadToString(expected_owner);
329 found_owner_string = ThreadToString(found_owner);
330 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800331 if (current_owner == NULL) {
332 if (found_owner == NULL) {
333 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
334 " on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800335 PrettyTypeOf(o).c_str(),
336 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800337 } else {
338 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800339 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
340 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800341 found_owner_string.c_str(),
342 PrettyTypeOf(o).c_str(),
343 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800344 }
345 } else {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800346 if (found_owner == NULL) {
347 // Race: originally there was no owner, there is now
348 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
349 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800350 current_owner_string.c_str(),
351 PrettyTypeOf(o).c_str(),
352 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800353 } else {
354 if (found_owner != current_owner) {
355 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800356 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
357 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800358 found_owner_string.c_str(),
359 current_owner_string.c_str(),
360 PrettyTypeOf(o).c_str(),
361 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800362 } else {
363 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
364 " on thread '%s",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800365 current_owner_string.c_str(),
366 PrettyTypeOf(o).c_str(),
367 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800368 }
369 }
370 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700371}
372
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700373bool Monitor::Unlock(Thread* self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700374 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700375 MutexLock mu(self, monitor_lock_);
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800376 Thread* owner = owner_;
377 if (owner == self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700378 // We own the monitor, so nobody else can be in here.
379 if (lock_count_ == 0) {
380 owner_ = NULL;
jeffhao33dc7712011-11-09 17:54:24 -0800381 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700382 locking_dex_pc_ = 0;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700383 // Wake a contender.
384 monitor_contenders_.Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700385 } else {
386 --lock_count_;
387 }
388 } else {
389 // We don't own this, so we're not allowed to unlock it.
390 // The JNI spec says that we should throw IllegalMonitorStateException
391 // in this case.
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700392 FailedUnlock(GetObject(), self, owner, this);
Elliott Hughes5f791332011-09-15 17:45:30 -0700393 return false;
394 }
395 return true;
396}
397
Elliott Hughes5f791332011-09-15 17:45:30 -0700398/*
399 * Wait on a monitor until timeout, interrupt, or notification. Used for
400 * Object.wait() and (somewhat indirectly) Thread.sleep() and Thread.join().
401 *
402 * If another thread calls Thread.interrupt(), we throw InterruptedException
403 * and return immediately if one of the following are true:
404 * - blocked in wait(), wait(long), or wait(long, int) methods of Object
405 * - blocked in join(), join(long), or join(long, int) methods of Thread
406 * - blocked in sleep(long), or sleep(long, int) methods of Thread
407 * Otherwise, we set the "interrupted" flag.
408 *
409 * Checks to make sure that "ns" is in the range 0-999999
410 * (i.e. fractions of a millisecond) and throws the appropriate
411 * exception if it isn't.
412 *
413 * The spec allows "spurious wakeups", and recommends that all code using
414 * Object.wait() do so in a loop. This appears to derive from concerns
415 * about pthread_cond_wait() on multiprocessor systems. Some commentary
416 * on the web casts doubt on whether these can/should occur.
417 *
418 * Since we're allowed to wake up "early", we clamp extremely long durations
419 * to return at the end of the 32-bit time epoch.
420 */
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800421void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
422 bool interruptShouldThrow, ThreadState why) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700423 DCHECK(self != NULL);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800424 DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
Elliott Hughes5f791332011-09-15 17:45:30 -0700425
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700426 monitor_lock_.Lock(self);
427
Elliott Hughes5f791332011-09-15 17:45:30 -0700428 // Make sure that we hold the lock.
429 if (owner_ != self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700430 monitor_lock_.Unlock(self);
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700431 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700432 return;
433 }
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800434
Elliott Hughesdf42c482013-01-09 12:49:02 -0800435 // We need to turn a zero-length timed wait into a regular wait because
436 // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
437 if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
438 why = kWaiting;
439 }
440
Elliott Hughes5f791332011-09-15 17:45:30 -0700441 // Enforce the timeout range.
442 if (ms < 0 || ns < 0 || ns > 999999) {
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700443 monitor_lock_.Unlock(self);
Ian Rogers62d6c772013-02-27 08:32:07 -0800444 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
445 self->ThrowNewExceptionF(throw_location, "Ljava/lang/IllegalArgumentException;",
Ian Rogersef7d42f2014-01-06 12:55:46 -0800446 "timeout arguments out of range: ms=%" PRId64 " ns=%d", ms, ns);
Elliott Hughes5f791332011-09-15 17:45:30 -0700447 return;
448 }
449
Elliott Hughes5f791332011-09-15 17:45:30 -0700450 /*
451 * Add ourselves to the set of threads waiting on this monitor, and
452 * release our hold. We need to let it go even if we're a few levels
453 * deep in a recursive lock, and we need to restore that later.
454 *
455 * We append to the wait set ahead of clearing the count and owner
456 * fields so the subroutine can check that the calling thread owns
457 * the monitor. Aside from that, the order of member updates is
458 * not order sensitive as we hold the pthread mutex.
459 */
460 AppendToWaitSet(self);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700461 ++num_waiters_;
Ian Rogers0399dde2012-06-06 17:09:28 -0700462 int prev_lock_count = lock_count_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700463 lock_count_ = 0;
464 owner_ = NULL;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800465 mirror::ArtMethod* saved_method = locking_method_;
jeffhao33dc7712011-11-09 17:54:24 -0800466 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700467 uintptr_t saved_dex_pc = locking_dex_pc_;
468 locking_dex_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700469
470 /*
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800471 * Update thread state. If the GC wakes up, it'll ignore us, knowing
Elliott Hughes5f791332011-09-15 17:45:30 -0700472 * that we won't touch any references in this state, and we'll check
473 * our suspend mode before we transition out.
474 */
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800475 self->TransitionFromRunnableToSuspended(why);
Elliott Hughes5f791332011-09-15 17:45:30 -0700476
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800477 bool was_interrupted = false;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700478 {
479 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700480 MutexLock mu(self, *self->GetWaitMutex());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700481
482 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
483 // non-NULL a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
484 // up.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700485 DCHECK(self->GetWaitMonitor() == nullptr);
486 self->SetWaitMonitor(this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700487
488 // Release the monitor lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700489 monitor_contenders_.Signal(self);
490 monitor_lock_.Unlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700491
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800492 // Handle the case where the thread was interrupted before we called wait().
Ian Rogersdd7624d2014-03-14 17:43:00 -0700493 if (self->IsInterruptedLocked()) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800494 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700495 } else {
496 // Wait for a notification or a timeout to occur.
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800497 if (why == kWaiting) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700498 self->GetWaitConditionVariable()->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700499 } else {
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800500 DCHECK(why == kTimedWaiting || why == kSleeping) << why;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700501 self->GetWaitConditionVariable()->TimedWait(self, ms, ns);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700502 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700503 if (self->IsInterruptedLocked()) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800504 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700505 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700506 self->SetInterruptedLocked(false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700507 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700508 }
509
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700510 // Set self->status back to kRunnable, and self-suspend if needed.
511 self->TransitionFromSuspendedToRunnable();
Elliott Hughes5f791332011-09-15 17:45:30 -0700512
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800513 {
514 // We reset the thread's wait_monitor_ field after transitioning back to runnable so
515 // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
516 // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
517 // are waiting on "null".)
Ian Rogersdd7624d2014-03-14 17:43:00 -0700518 MutexLock mu(self, *self->GetWaitMutex());
519 DCHECK(self->GetWaitMonitor() != nullptr);
520 self->SetWaitMonitor(nullptr);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800521 }
522
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700523 // Re-acquire the monitor and lock.
Elliott Hughes5f791332011-09-15 17:45:30 -0700524 Lock(self);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700525 monitor_lock_.Lock(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700526 self->GetWaitMutex()->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700527
Elliott Hughes5f791332011-09-15 17:45:30 -0700528 /*
529 * We remove our thread from wait set after restoring the count
530 * and owner fields so the subroutine can check that the calling
531 * thread owns the monitor. Aside from that, the order of member
532 * updates is not order sensitive as we hold the pthread mutex.
533 */
534 owner_ = self;
Ian Rogers0399dde2012-06-06 17:09:28 -0700535 lock_count_ = prev_lock_count;
536 locking_method_ = saved_method;
537 locking_dex_pc_ = saved_dex_pc;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700538 --num_waiters_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700539 RemoveFromWaitSet(self);
540
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700541 monitor_lock_.Unlock(self);
542
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800543 if (was_interrupted) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700544 /*
545 * We were interrupted while waiting, or somebody interrupted an
546 * un-interruptible thread earlier and we're bailing out immediately.
547 *
548 * The doc sayeth: "The interrupted status of the current thread is
549 * cleared when this exception is thrown."
550 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700551 {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700552 MutexLock mu(self, *self->GetWaitMutex());
553 self->SetInterruptedLocked(false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700554 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700555 if (interruptShouldThrow) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800556 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
557 self->ThrowNewException(throw_location, "Ljava/lang/InterruptedException;", NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700558 }
559 }
560}
561
562void Monitor::Notify(Thread* self) {
563 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700564 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700565 // Make sure that we hold the lock.
566 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800567 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700568 return;
569 }
570 // Signal the first waiting thread in the wait set.
571 while (wait_set_ != NULL) {
572 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700573 wait_set_ = thread->GetWaitNext();
574 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700575
576 // Check to see if the thread is still waiting.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700577 MutexLock mu(self, *thread->GetWaitMutex());
578 if (thread->GetWaitMonitor() != nullptr) {
579 thread->GetWaitConditionVariable()->Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700580 return;
581 }
582 }
583}
584
585void Monitor::NotifyAll(Thread* self) {
586 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700587 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700588 // Make sure that we hold the lock.
589 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800590 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700591 return;
592 }
593 // Signal all threads in the wait set.
594 while (wait_set_ != NULL) {
595 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700596 wait_set_ = thread->GetWaitNext();
597 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700598 thread->Notify();
599 }
600}
601
Mathieu Chartier590fee92013-09-13 13:46:47 -0700602bool Monitor::Deflate(Thread* self, mirror::Object* obj) {
603 DCHECK(obj != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700604 // Don't need volatile since we only deflate with mutators suspended.
605 LockWord lw(obj->GetLockWord(false));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700606 // If the lock isn't an inflated monitor, then we don't need to deflate anything.
607 if (lw.GetState() == LockWord::kFatLocked) {
608 Monitor* monitor = lw.FatLockMonitor();
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700609 DCHECK(monitor != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700610 MutexLock mu(self, monitor->monitor_lock_);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700611 // Can't deflate if we have anybody waiting on the CV.
612 if (monitor->num_waiters_ > 0) {
613 return false;
614 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700615 Thread* owner = monitor->owner_;
616 if (owner != nullptr) {
617 // Can't deflate if we are locked and have a hash code.
618 if (monitor->HasHashCode()) {
619 return false;
620 }
621 // Can't deflate if our lock count is too high.
622 if (monitor->lock_count_ > LockWord::kThinLockMaxCount) {
623 return false;
624 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700625 // Deflate to a thin lock.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700626 obj->SetLockWord(LockWord::FromThinLockId(owner->GetThreadId(), monitor->lock_count_), false);
627 VLOG(monitor) << "Deflated " << obj << " to thin lock " << owner->GetTid() << " / "
628 << monitor->lock_count_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700629 } else if (monitor->HasHashCode()) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700630 obj->SetLockWord(LockWord::FromHashCode(monitor->GetHashCode()), false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700631 VLOG(monitor) << "Deflated " << obj << " to hash monitor " << monitor->GetHashCode();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700632 } else {
633 // No lock and no hash, just put an empty lock word inside the object.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700634 obj->SetLockWord(LockWord(), false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700635 VLOG(monitor) << "Deflated" << obj << " to empty lock word";
Mathieu Chartier590fee92013-09-13 13:46:47 -0700636 }
637 // The monitor is deflated, mark the object as nullptr so that we know to delete it during the
638 // next GC.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700639 monitor->obj_ = GcRoot<mirror::Object>(nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700640 }
641 return true;
642}
643
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700644void Monitor::Inflate(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code) {
Andreas Gampe74240812014-04-17 10:35:09 -0700645 DCHECK(self != nullptr);
646 DCHECK(obj != nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700647 // Allocate and acquire a new monitor.
Andreas Gampe74240812014-04-17 10:35:09 -0700648 Monitor* m = MonitorPool::CreateMonitor(self, owner, obj, hash_code);
649 DCHECK(m != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700650 if (m->Install(self)) {
Haifeng Li86ab7912014-05-16 10:47:59 +0800651 if (owner != nullptr) {
652 VLOG(monitor) << "monitor: thread" << owner->GetThreadId()
Andreas Gampe74240812014-04-17 10:35:09 -0700653 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800654 } else {
655 VLOG(monitor) << "monitor: Inflate with hashcode " << hash_code
Andreas Gampe74240812014-04-17 10:35:09 -0700656 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800657 }
Andreas Gampe74240812014-04-17 10:35:09 -0700658 Runtime::Current()->GetMonitorList()->Add(m);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700659 CHECK_EQ(obj->GetLockWord(true).GetState(), LockWord::kFatLocked);
Andreas Gampe74240812014-04-17 10:35:09 -0700660 } else {
661 MonitorPool::ReleaseMonitor(self, m);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700662 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700663}
664
Mathieu Chartier0cd81352014-05-22 16:48:55 -0700665void Monitor::InflateThinLocked(Thread* self, Handle<mirror::Object> obj, LockWord lock_word,
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700666 uint32_t hash_code) {
667 DCHECK_EQ(lock_word.GetState(), LockWord::kThinLocked);
668 uint32_t owner_thread_id = lock_word.ThinLockOwner();
669 if (owner_thread_id == self->GetThreadId()) {
670 // We own the monitor, we can easily inflate it.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700671 Inflate(self, self, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700672 } else {
673 ThreadList* thread_list = Runtime::Current()->GetThreadList();
674 // Suspend the owner, inflate. First change to blocked and give up mutator_lock_.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700675 self->SetMonitorEnterObject(obj.Get());
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700676 bool timed_out;
677 Thread* owner;
678 {
679 ScopedThreadStateChange tsc(self, kBlocked);
Ian Rogersf3d874c2014-07-17 18:52:42 -0700680 // Take suspend thread lock to avoid races with threads trying to suspend this one.
681 MutexLock mu(self, *Locks::thread_list_suspend_thread_lock_);
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700682 owner = thread_list->SuspendThreadByThreadId(owner_thread_id, false, &timed_out);
683 }
684 if (owner != nullptr) {
685 // We succeeded in suspending the thread, check the lock's status didn't change.
686 lock_word = obj->GetLockWord(true);
687 if (lock_word.GetState() == LockWord::kThinLocked &&
688 lock_word.ThinLockOwner() == owner_thread_id) {
689 // Go ahead and inflate the lock.
690 Inflate(self, owner, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700691 }
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700692 thread_list->Resume(owner, false);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700693 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700694 self->SetMonitorEnterObject(nullptr);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700695 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700696}
697
Ian Rogers719d1a32014-03-06 12:13:39 -0800698// Fool annotalysis into thinking that the lock on obj is acquired.
699static mirror::Object* FakeLock(mirror::Object* obj)
700 EXCLUSIVE_LOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
701 return obj;
702}
703
704// Fool annotalysis into thinking that the lock on obj is release.
705static mirror::Object* FakeUnlock(mirror::Object* obj)
706 UNLOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
707 return obj;
708}
709
Mathieu Chartiere7e8a5f2014-02-14 16:59:41 -0800710mirror::Object* Monitor::MonitorEnter(Thread* self, mirror::Object* obj) {
Elliott Hughes4681c802011-09-25 18:04:37 -0700711 DCHECK(self != NULL);
712 DCHECK(obj != NULL);
Ian Rogers719d1a32014-03-06 12:13:39 -0800713 obj = FakeLock(obj);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700714 uint32_t thread_id = self->GetThreadId();
715 size_t contention_count = 0;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700716 StackHandleScope<1> hs(self);
717 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700718 while (true) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700719 LockWord lock_word = h_obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700720 switch (lock_word.GetState()) {
721 case LockWord::kUnlocked: {
722 LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0));
Ian Rogers228602f2014-07-10 02:07:54 -0700723 if (h_obj->CasLockWordWeakSequentiallyConsistent(lock_word, thin_locked)) {
Hans Boehm30359612014-05-21 17:46:23 -0700724 // CasLockWord enforces more than the acquire ordering we need here.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700725 return h_obj.Get(); // Success!
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700726 }
727 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -0700728 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700729 case LockWord::kThinLocked: {
730 uint32_t owner_thread_id = lock_word.ThinLockOwner();
731 if (owner_thread_id == thread_id) {
732 // We own the lock, increase the recursion count.
733 uint32_t new_count = lock_word.ThinLockCount() + 1;
734 if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
735 LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700736 h_obj->SetLockWord(thin_locked, true);
737 return h_obj.Get(); // Success!
Elliott Hughes5f791332011-09-15 17:45:30 -0700738 } else {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700739 // We'd overflow the recursion count, so inflate the monitor.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700740 InflateThinLocked(self, h_obj, lock_word, 0);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700741 }
742 } else {
743 // Contention.
744 contention_count++;
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700745 Runtime* runtime = Runtime::Current();
746 if (contention_count <= runtime->GetMaxSpinsBeforeThinkLockInflation()) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700747 // TODO: Consider switching the thread state to kBlocked when we are yielding.
Mathieu Chartier251755c2014-07-15 18:10:25 -0700748 // Use sched_yield instead of NanoSleep since NanoSleep can wait much longer than the
749 // parameter you pass in. This can cause thread suspension to take excessively long
Mathieu Chartierb363f662014-07-16 13:28:58 -0700750 // and make long pauses. See b/16307460.
Mathieu Chartier251755c2014-07-15 18:10:25 -0700751 sched_yield();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700752 } else {
753 contention_count = 0;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700754 InflateThinLocked(self, h_obj, lock_word, 0);
Elliott Hughes5f791332011-09-15 17:45:30 -0700755 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700756 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700757 continue; // Start from the beginning.
Elliott Hughes5f791332011-09-15 17:45:30 -0700758 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700759 case LockWord::kFatLocked: {
760 Monitor* mon = lock_word.FatLockMonitor();
761 mon->Lock(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700762 return h_obj.Get(); // Success!
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700763 }
Ian Rogers719d1a32014-03-06 12:13:39 -0800764 case LockWord::kHashCode:
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700765 // Inflate with the existing hashcode.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700766 Inflate(self, nullptr, h_obj.Get(), lock_word.GetHashCode());
Ian Rogers719d1a32014-03-06 12:13:39 -0800767 continue; // Start from the beginning.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700768 default: {
769 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700770 return h_obj.Get();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700771 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700772 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700773 }
774}
775
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800776bool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700777 DCHECK(self != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700778 DCHECK(obj != NULL);
Ian Rogers719d1a32014-03-06 12:13:39 -0800779 obj = FakeUnlock(obj);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700780 LockWord lock_word = obj->GetLockWord(true);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700781 StackHandleScope<1> hs(self);
782 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700783 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700784 case LockWord::kHashCode:
785 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700786 case LockWord::kUnlocked:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700787 FailedUnlock(h_obj.Get(), self, nullptr, nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700788 return false; // Failure.
789 case LockWord::kThinLocked: {
790 uint32_t thread_id = self->GetThreadId();
791 uint32_t owner_thread_id = lock_word.ThinLockOwner();
792 if (owner_thread_id != thread_id) {
793 // TODO: there's a race here with the owner dying while we unlock.
794 Thread* owner =
795 Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700796 FailedUnlock(h_obj.Get(), self, owner, nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700797 return false; // Failure.
798 } else {
799 // We own the lock, decrease the recursion count.
800 if (lock_word.ThinLockCount() != 0) {
801 uint32_t new_count = lock_word.ThinLockCount() - 1;
802 LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700803 h_obj->SetLockWord(thin_locked, true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700804 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700805 h_obj->SetLockWord(LockWord(), true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700806 }
807 return true; // Success!
808 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700809 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700810 case LockWord::kFatLocked: {
811 Monitor* mon = lock_word.FatLockMonitor();
812 return mon->Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700813 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700814 default: {
815 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700816 return false;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700817 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700818 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700819}
820
821/*
822 * Object.wait(). Also called for class init.
823 */
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800824void Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800825 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700826 DCHECK(self != nullptr);
827 DCHECK(obj != nullptr);
828 LockWord lock_word = obj->GetLockWord(true);
Ian Rogers6f22fc12014-08-15 11:09:28 -0700829 while (lock_word.GetState() != LockWord::kFatLocked) {
830 switch (lock_word.GetState()) {
831 case LockWord::kHashCode:
832 // Fall-through.
833 case LockWord::kUnlocked:
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700834 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
835 return; // Failure.
Ian Rogers6f22fc12014-08-15 11:09:28 -0700836 case LockWord::kThinLocked: {
837 uint32_t thread_id = self->GetThreadId();
838 uint32_t owner_thread_id = lock_word.ThinLockOwner();
839 if (owner_thread_id != thread_id) {
840 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
841 return; // Failure.
842 } else {
843 // We own the lock, inflate to enqueue ourself on the Monitor. May fail spuriously so
844 // re-load.
845 Inflate(self, self, obj, 0);
846 lock_word = obj->GetLockWord(true);
847 }
848 break;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700849 }
Ian Rogers6f22fc12014-08-15 11:09:28 -0700850 case LockWord::kFatLocked: // Unreachable given the loop condition above. Fall-through.
851 default: {
852 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
853 return;
854 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700855 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700856 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700857 Monitor* mon = lock_word.FatLockMonitor();
858 mon->Wait(self, ms, ns, interruptShouldThrow, why);
Elliott Hughes5f791332011-09-15 17:45:30 -0700859}
860
Ian Rogers13c479e2013-10-11 07:59:01 -0700861void Monitor::DoNotify(Thread* self, mirror::Object* obj, bool notify_all) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700862 DCHECK(self != nullptr);
863 DCHECK(obj != nullptr);
864 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700865 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700866 case LockWord::kHashCode:
867 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700868 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800869 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700870 return; // Failure.
871 case LockWord::kThinLocked: {
872 uint32_t thread_id = self->GetThreadId();
873 uint32_t owner_thread_id = lock_word.ThinLockOwner();
874 if (owner_thread_id != thread_id) {
875 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
876 return; // Failure.
877 } else {
878 // We own the lock but there's no Monitor and therefore no waiters.
879 return; // Success.
880 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700881 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700882 case LockWord::kFatLocked: {
883 Monitor* mon = lock_word.FatLockMonitor();
884 if (notify_all) {
885 mon->NotifyAll(self);
886 } else {
887 mon->Notify(self);
888 }
889 return; // Success.
890 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700891 default: {
892 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
893 return;
894 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700895 }
896}
897
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700898uint32_t Monitor::GetLockOwnerThreadId(mirror::Object* obj) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700899 DCHECK(obj != nullptr);
900 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700901 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700902 case LockWord::kHashCode:
903 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700904 case LockWord::kUnlocked:
905 return ThreadList::kInvalidThreadId;
906 case LockWord::kThinLocked:
907 return lock_word.ThinLockOwner();
908 case LockWord::kFatLocked: {
909 Monitor* mon = lock_word.FatLockMonitor();
910 return mon->GetOwnerThreadId();
Elliott Hughes5f791332011-09-15 17:45:30 -0700911 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700912 default: {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700913 LOG(FATAL) << "Unreachable";
914 return ThreadList::kInvalidThreadId;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700915 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700916 }
917}
918
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700919void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
Ian Rogersd803bc72014-04-01 15:33:03 -0700920 // Determine the wait message and object we're waiting or blocked upon.
921 mirror::Object* pretty_object = nullptr;
922 const char* wait_message = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700923 uint32_t lock_owner = ThreadList::kInvalidThreadId;
Ian Rogersd803bc72014-04-01 15:33:03 -0700924 ThreadState state = thread->GetState();
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800925 if (state == kWaiting || state == kTimedWaiting || state == kSleeping) {
Ian Rogersd803bc72014-04-01 15:33:03 -0700926 wait_message = (state == kSleeping) ? " - sleeping on " : " - waiting on ";
927 Thread* self = Thread::Current();
928 MutexLock mu(self, *thread->GetWaitMutex());
929 Monitor* monitor = thread->GetWaitMonitor();
930 if (monitor != nullptr) {
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700931 pretty_object = monitor->GetObject();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700932 }
Elliott Hughes34e06962012-04-09 13:55:55 -0700933 } else if (state == kBlocked) {
Ian Rogersd803bc72014-04-01 15:33:03 -0700934 wait_message = " - waiting to lock ";
935 pretty_object = thread->GetMonitorEnterObject();
936 if (pretty_object != nullptr) {
937 lock_owner = pretty_object->GetLockOwnerThreadId();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700938 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700939 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700940
Ian Rogersd803bc72014-04-01 15:33:03 -0700941 if (wait_message != nullptr) {
942 if (pretty_object == nullptr) {
943 os << wait_message << "an unknown object";
944 } else {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700945 if ((pretty_object->GetLockWord(true).GetState() == LockWord::kThinLocked) &&
Ian Rogersd803bc72014-04-01 15:33:03 -0700946 Locks::mutator_lock_->IsExclusiveHeld(Thread::Current())) {
947 // Getting the identity hashcode here would result in lock inflation and suspension of the
948 // current thread, which isn't safe if this is the only runnable thread.
949 os << wait_message << StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)",
950 reinterpret_cast<intptr_t>(pretty_object),
951 PrettyTypeOf(pretty_object).c_str());
952 } else {
953 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
954 os << wait_message << StringPrintf("<0x%08x> (a %s)", pretty_object->IdentityHashCode(),
955 PrettyTypeOf(pretty_object).c_str());
956 }
957 }
958 // - waiting to lock <0x613f83d8> (a java.lang.Object) held by thread 5
959 if (lock_owner != ThreadList::kInvalidThreadId) {
960 os << " held by thread " << lock_owner;
961 }
962 os << "\n";
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700963 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700964}
965
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800966mirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800967 // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
968 // definition of contended that includes a monitor a thread is trying to enter...
Ian Rogersdd7624d2014-03-14 17:43:00 -0700969 mirror::Object* result = thread->GetMonitorEnterObject();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700970 if (result == NULL) {
971 // ...but also a monitor that the thread is waiting on.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700972 MutexLock mu(Thread::Current(), *thread->GetWaitMutex());
973 Monitor* monitor = thread->GetWaitMonitor();
Elliott Hughesf9501702013-01-11 11:22:27 -0800974 if (monitor != NULL) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700975 result = monitor->GetObject();
Elliott Hughesf9501702013-01-11 11:22:27 -0800976 }
977 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700978 return result;
Elliott Hughesf9501702013-01-11 11:22:27 -0800979}
980
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800981void Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
Andreas Gampe760172c2014-08-16 13:41:10 -0700982 void* callback_context, bool abort_on_failure) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700983 mirror::ArtMethod* m = stack_visitor->GetMethod();
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700984 CHECK(m != NULL);
985
986 // Native methods are an easy special case.
987 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
988 if (m->IsNative()) {
989 if (m->IsSynchronized()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700990 mirror::Object* jni_this = stack_visitor->GetCurrentHandleScope()->GetReference(0);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800991 callback(jni_this, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700992 }
993 return;
994 }
995
jeffhao61f916c2012-10-25 17:48:51 -0700996 // Proxy methods should not be synchronized.
997 if (m->IsProxyMethod()) {
998 CHECK(!m->IsSynchronized());
999 return;
1000 }
1001
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001002 // <clinit> is another special case. The runtime holds the class lock while calling <clinit>.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001003 if (m->IsClassInitializer()) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001004 callback(m->GetDeclaringClass(), callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001005 // Fall through because there might be synchronization in the user code too.
1006 }
1007
1008 // Is there any reason to believe there's any synchronization in this method?
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001009 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07001010 CHECK(code_item != NULL) << PrettyMethod(m);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001011 if (code_item->tries_size_ == 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001012 return; // No "tries" implies no synchronization, so no held locks to report.
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001013 }
1014
Andreas Gampe760172c2014-08-16 13:41:10 -07001015 // Get the dex pc. If abort_on_failure is false, GetDexPc will not abort in the case it cannot
1016 // find the dex pc, and instead return kDexNoIndex. Then bail out, as it indicates we have an
1017 // inconsistent stack anyways.
1018 uint32_t dex_pc = stack_visitor->GetDexPc(abort_on_failure);
1019 if (!abort_on_failure && dex_pc == DexFile::kDexNoIndex) {
1020 LOG(ERROR) << "Could not find dex_pc for " << PrettyMethod(m);
1021 return;
1022 }
1023
Elliott Hughes80537bb2013-01-04 16:37:26 -08001024 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
1025 // the locks held in this stack frame.
1026 std::vector<uint32_t> monitor_enter_dex_pcs;
Andreas Gampe760172c2014-08-16 13:41:10 -07001027 verifier::MethodVerifier::FindLocksAtDexPc(m, dex_pc, &monitor_enter_dex_pcs);
Elliott Hughes80537bb2013-01-04 16:37:26 -08001028 if (monitor_enter_dex_pcs.empty()) {
1029 return;
1030 }
1031
Elliott Hughes80537bb2013-01-04 16:37:26 -08001032 for (size_t i = 0; i < monitor_enter_dex_pcs.size(); ++i) {
1033 // The verifier works in terms of the dex pcs of the monitor-enter instructions.
1034 // We want the registers used by those instructions (so we can read the values out of them).
1035 uint32_t dex_pc = monitor_enter_dex_pcs[i];
1036 uint16_t monitor_enter_instruction = code_item->insns_[dex_pc];
1037
1038 // Quick sanity check.
1039 if ((monitor_enter_instruction & 0xff) != Instruction::MONITOR_ENTER) {
1040 LOG(FATAL) << "expected monitor-enter @" << dex_pc << "; was "
1041 << reinterpret_cast<void*>(monitor_enter_instruction);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001042 }
1043
Elliott Hughes80537bb2013-01-04 16:37:26 -08001044 uint16_t monitor_register = ((monitor_enter_instruction >> 8) & 0xff);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001045 mirror::Object* o = reinterpret_cast<mirror::Object*>(stack_visitor->GetVReg(m, monitor_register,
1046 kReferenceVReg));
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001047 callback(o, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001048 }
1049}
1050
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001051bool Monitor::IsValidLockWord(LockWord lock_word) {
1052 switch (lock_word.GetState()) {
1053 case LockWord::kUnlocked:
1054 // Nothing to check.
1055 return true;
1056 case LockWord::kThinLocked:
1057 // Basic sanity check of owner.
1058 return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
1059 case LockWord::kFatLocked: {
1060 // Check the monitor appears in the monitor list.
1061 Monitor* mon = lock_word.FatLockMonitor();
1062 MonitorList* list = Runtime::Current()->GetMonitorList();
1063 MutexLock mu(Thread::Current(), list->monitor_list_lock_);
1064 for (Monitor* list_mon : list->list_) {
1065 if (mon == list_mon) {
1066 return true; // Found our monitor.
1067 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001068 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001069 return false; // Fail - unowned monitor in an object.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001070 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001071 case LockWord::kHashCode:
1072 return true;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001073 default:
1074 LOG(FATAL) << "Unreachable";
1075 return false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001076 }
1077}
1078
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001079bool Monitor::IsLocked() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1080 MutexLock mu(Thread::Current(), monitor_lock_);
1081 return owner_ != nullptr;
1082}
1083
Ian Rogersef7d42f2014-01-06 12:55:46 -08001084void Monitor::TranslateLocation(mirror::ArtMethod* method, uint32_t dex_pc,
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001085 const char** source_file, uint32_t* line_number) const {
jeffhao33dc7712011-11-09 17:54:24 -08001086 // If method is null, location is unknown
1087 if (method == NULL) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001088 *source_file = "";
1089 *line_number = 0;
jeffhao33dc7712011-11-09 17:54:24 -08001090 return;
1091 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001092 *source_file = method->GetDeclaringClassSourceFile();
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001093 if (*source_file == NULL) {
1094 *source_file = "";
Elliott Hughes12c51e32012-01-17 20:25:05 -08001095 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001096 *line_number = method->GetLineNumFromDexPC(dex_pc);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001097}
1098
1099uint32_t Monitor::GetOwnerThreadId() {
1100 MutexLock mu(Thread::Current(), monitor_lock_);
1101 Thread* owner = owner_;
1102 if (owner != NULL) {
1103 return owner->GetThreadId();
1104 } else {
1105 return ThreadList::kInvalidThreadId;
1106 }
jeffhao33dc7712011-11-09 17:54:24 -08001107}
1108
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001109MonitorList::MonitorList()
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001110 : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock", kMonitorListLock),
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001111 monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001112}
1113
1114MonitorList::~MonitorList() {
Andreas Gampe74240812014-04-17 10:35:09 -07001115 Thread* self = Thread::Current();
1116 MutexLock mu(self, monitor_list_lock_);
1117 // Release all monitors to the pool.
1118 // TODO: Is it an invariant that *all* open monitors are in the list? Then we could
1119 // clear faster in the pool.
1120 MonitorPool::ReleaseMonitors(self, &list_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001121}
1122
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001123void MonitorList::DisallowNewMonitors() {
Ian Rogers50b35e22012-10-04 10:09:15 -07001124 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001125 allow_new_monitors_ = false;
1126}
1127
1128void MonitorList::AllowNewMonitors() {
1129 Thread* self = Thread::Current();
1130 MutexLock mu(self, monitor_list_lock_);
1131 allow_new_monitors_ = true;
1132 monitor_add_condition_.Broadcast(self);
1133}
1134
1135void MonitorList::Add(Monitor* m) {
1136 Thread* self = Thread::Current();
1137 MutexLock mu(self, monitor_list_lock_);
1138 while (UNLIKELY(!allow_new_monitors_)) {
1139 monitor_add_condition_.WaitHoldingLocks(self);
1140 }
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001141 list_.push_front(m);
1142}
1143
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08001144void MonitorList::SweepMonitorList(IsMarkedCallback* callback, void* arg) {
Andreas Gampe74240812014-04-17 10:35:09 -07001145 Thread* self = Thread::Current();
1146 MutexLock mu(self, monitor_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001147 for (auto it = list_.begin(); it != list_.end(); ) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001148 Monitor* m = *it;
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001149 // Disable the read barrier in GetObject() as this is called by GC.
1150 mirror::Object* obj = m->GetObject<kWithoutReadBarrier>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001151 // The object of a monitor can be null if we have deflated it.
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08001152 mirror::Object* new_obj = obj != nullptr ? callback(obj, arg) : nullptr;
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001153 if (new_obj == nullptr) {
1154 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001155 << obj;
Andreas Gampe74240812014-04-17 10:35:09 -07001156 MonitorPool::ReleaseMonitor(self, m);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001157 it = list_.erase(it);
1158 } else {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001159 m->SetObject(new_obj);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001160 ++it;
1161 }
1162 }
1163}
1164
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001165struct MonitorDeflateArgs {
1166 MonitorDeflateArgs() : self(Thread::Current()), deflate_count(0) {}
1167 Thread* const self;
1168 size_t deflate_count;
1169};
1170
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001171static mirror::Object* MonitorDeflateCallback(mirror::Object* object, void* arg)
1172 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001173 MonitorDeflateArgs* args = reinterpret_cast<MonitorDeflateArgs*>(arg);
1174 if (Monitor::Deflate(args->self, object)) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001175 DCHECK_NE(object->GetLockWord(true).GetState(), LockWord::kFatLocked);
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001176 ++args->deflate_count;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001177 // If we deflated, return nullptr so that the monitor gets removed from the array.
1178 return nullptr;
1179 }
1180 return object; // Monitor was not deflated.
1181}
1182
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001183size_t MonitorList::DeflateMonitors() {
1184 MonitorDeflateArgs args;
1185 Locks::mutator_lock_->AssertExclusiveHeld(args.self);
1186 SweepMonitorList(MonitorDeflateCallback, &args);
1187 return args.deflate_count;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001188}
1189
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001190MonitorInfo::MonitorInfo(mirror::Object* obj) : owner_(NULL), entry_count_(0) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001191 DCHECK(obj != nullptr);
1192 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001193 switch (lock_word.GetState()) {
1194 case LockWord::kUnlocked:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001195 // Fall-through.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001196 case LockWord::kForwardingAddress:
1197 // Fall-through.
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001198 case LockWord::kHashCode:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001199 break;
1200 case LockWord::kThinLocked:
1201 owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
1202 entry_count_ = 1 + lock_word.ThinLockCount();
1203 // Thin locks have no waiters.
1204 break;
1205 case LockWord::kFatLocked: {
1206 Monitor* mon = lock_word.FatLockMonitor();
1207 owner_ = mon->owner_;
1208 entry_count_ = 1 + mon->lock_count_;
Ian Rogersdd7624d2014-03-14 17:43:00 -07001209 for (Thread* waiter = mon->wait_set_; waiter != NULL; waiter = waiter->GetWaitNext()) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001210 waiters_.push_back(waiter);
1211 }
1212 break;
Elliott Hughesf327e072013-01-09 16:01:26 -08001213 }
1214 }
1215}
1216
Elliott Hughes5f791332011-09-15 17:45:30 -07001217} // namespace art