blob: b1bf84f4983c789fc3e3838c6494e401cd4b03f0 [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 Rogers6d4d9fc2011-11-30 16:24:48 -080031#include "object_utils.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070032#include "scoped_thread_state_change.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070033#include "thread.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070034#include "thread_list.h"
Elliott Hughes08fc03a2012-06-26 17:34:00 -070035#include "verifier/method_verifier.h"
Elliott Hughes044288f2012-06-25 14:46:39 -070036#include "well_known_classes.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070037
38namespace art {
39
40/*
Ian Rogersd9c4fc92013-10-01 19:45:43 -070041 * Every Object has a monitor associated with it, but not every Object is actually locked. Even
42 * the ones that are locked do not need a full-fledged monitor until a) there is actual contention
43 * or b) wait() is called on the Object.
Elliott Hughes5f791332011-09-15 17:45:30 -070044 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070045 * For Android, we have implemented a scheme similar to the one described in Bacon et al.'s
46 * "Thin locks: featherweight synchronization for Java" (ACM 1998). Things are even easier for us,
47 * though, because we have a full 32 bits to work with.
Elliott Hughes5f791332011-09-15 17:45:30 -070048 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070049 * The two states of an Object's lock are referred to as "thin" and "fat". A lock may transition
50 * from the "thin" state to the "fat" state and this transition is referred to as inflation. Once
51 * a lock has been inflated it remains in the "fat" state indefinitely.
Elliott Hughes5f791332011-09-15 17:45:30 -070052 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070053 * The lock value itself is stored in mirror::Object::monitor_ and the representation is described
54 * in the LockWord value type.
Elliott Hughes54e7df12011-09-16 11:47:04 -070055 *
Elliott Hughes5f791332011-09-15 17:45:30 -070056 * Monitors provide:
57 * - mutually exclusive access to resources
58 * - a way for multiple threads to wait for notification
59 *
60 * In effect, they fill the role of both mutexes and condition variables.
61 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070062 * Only one thread can own the monitor at any time. There may be several threads waiting on it
63 * (the wait call unlocks it). One or more waiting threads may be getting interrupted or notified
64 * at any given time.
Elliott Hughes5f791332011-09-15 17:45:30 -070065 */
Elliott Hughes54e7df12011-09-16 11:47:04 -070066
Elliott Hughesfc861622011-10-17 17:57:47 -070067bool (*Monitor::is_sensitive_thread_hook_)() = NULL;
Elliott Hughesfc861622011-10-17 17:57:47 -070068uint32_t Monitor::lock_profiling_threshold_ = 0;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070069
Elliott Hughesfc861622011-10-17 17:57:47 -070070bool Monitor::IsSensitiveThread() {
71 if (is_sensitive_thread_hook_ != NULL) {
72 return (*is_sensitive_thread_hook_)();
73 }
74 return false;
75}
76
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -080077void Monitor::Init(uint32_t lock_profiling_threshold, bool (*is_sensitive_thread_hook)()) {
Elliott Hughesfc861622011-10-17 17:57:47 -070078 lock_profiling_threshold_ = lock_profiling_threshold;
79 is_sensitive_thread_hook_ = is_sensitive_thread_hook;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070080}
81
Mathieu Chartierad2541a2013-10-25 10:05:23 -070082Monitor::Monitor(Thread* owner, mirror::Object* obj, uint32_t hash_code)
Ian Rogers00f7d0e2012-07-19 15:28:27 -070083 : monitor_lock_("a monitor lock", kMonitorLock),
Ian Rogersd9c4fc92013-10-01 19:45:43 -070084 monitor_contenders_("monitor contenders", monitor_lock_),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070085 owner_(owner),
Elliott Hughes5f791332011-09-15 17:45:30 -070086 lock_count_(0),
87 obj_(obj),
88 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 Rogers0399dde2012-06-06 17:09:28 -070091 locking_dex_pc_(0) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -070092 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
93 // with the owner unlocking the thin-lock.
Mathieu Chartierad2541a2013-10-25 10:05:23 -070094 CHECK(owner == nullptr || owner == Thread::Current() || owner->IsSuspended());
95 // The identity hash code is set for the life time of the monitor.
Ian Rogersd9c4fc92013-10-01 19:45:43 -070096}
97
98bool Monitor::Install(Thread* self) {
99 MutexLock mu(self, monitor_lock_); // Uncontended mutex acquisition as monitor isn't yet public.
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700100 CHECK(owner_ == nullptr || owner_ == self || owner_->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700101 // Propagate the lock state.
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700102 LockWord lw(obj_->GetLockWord());
103 switch (lw.GetState()) {
104 case LockWord::kThinLocked: {
105 CHECK_EQ(owner_->GetThreadId(), lw.ThinLockOwner());
106 lock_count_ = lw.ThinLockCount();
107 break;
108 }
109 case LockWord::kHashCode: {
110 CHECK_EQ(hash_code_, lw.GetHashCode());
111 break;
112 }
113 case LockWord::kFatLocked: {
114 // The owner_ is suspended but another thread beat us to install a monitor.
115 return false;
116 }
117 case LockWord::kUnlocked: {
118 LOG(FATAL) << "Inflating unlocked lock word";
119 break;
120 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700121 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700122 LockWord fat(this);
123 // Publish the updated lock word, which may race with other threads.
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700124 bool success = obj_->CasLockWord(lw, fat);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700125 // Lock profiling.
126 if (success && lock_profiling_threshold_ != 0) {
127 locking_method_ = owner_->GetCurrentMethod(&locking_dex_pc_);
128 }
129 return success;
Elliott Hughes5f791332011-09-15 17:45:30 -0700130}
131
132Monitor::~Monitor() {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700133 CHECK(obj_ != NULL);
134 CHECK_EQ(obj_->GetLockWord().GetState(), LockWord::kFatLocked);
Elliott Hughes5f791332011-09-15 17:45:30 -0700135}
136
137/*
138 * Links a thread into a monitor's wait set. The monitor lock must be
139 * held by the caller of this routine.
140 */
141void Monitor::AppendToWaitSet(Thread* thread) {
142 DCHECK(owner_ == Thread::Current());
143 DCHECK(thread != NULL);
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700144 DCHECK(thread->wait_next_ == NULL) << thread->wait_next_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700145 if (wait_set_ == NULL) {
146 wait_set_ = thread;
147 return;
148 }
149
150 // push_back.
151 Thread* t = wait_set_;
152 while (t->wait_next_ != NULL) {
153 t = t->wait_next_;
154 }
155 t->wait_next_ = thread;
156}
157
158/*
159 * Unlinks a thread from a monitor's wait set. The monitor lock must
160 * be held by the caller of this routine.
161 */
162void Monitor::RemoveFromWaitSet(Thread *thread) {
163 DCHECK(owner_ == Thread::Current());
164 DCHECK(thread != NULL);
165 if (wait_set_ == NULL) {
166 return;
167 }
168 if (wait_set_ == thread) {
169 wait_set_ = thread->wait_next_;
170 thread->wait_next_ = NULL;
171 return;
172 }
173
174 Thread* t = wait_set_;
175 while (t->wait_next_ != NULL) {
176 if (t->wait_next_ == thread) {
177 t->wait_next_ = thread->wait_next_;
178 thread->wait_next_ = NULL;
179 return;
180 }
181 t = t->wait_next_;
182 }
183}
184
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700185void Monitor::SetObject(mirror::Object* object) {
186 obj_ = object;
187}
188
Elliott Hughes5f791332011-09-15 17:45:30 -0700189void Monitor::Lock(Thread* self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700190 MutexLock mu(self, monitor_lock_);
191 while (true) {
192 if (owner_ == NULL) { // Unowned.
193 owner_ = self;
194 CHECK_EQ(lock_count_, 0);
195 // When debugging, save the current monitor holder for future
196 // acquisition failures to use in sampled logging.
197 if (lock_profiling_threshold_ != 0) {
198 locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
199 }
200 return;
201 } else if (owner_ == self) { // Recursive.
202 lock_count_++;
203 return;
204 }
205 // Contended.
206 const bool log_contention = (lock_profiling_threshold_ != 0);
207 uint64_t wait_start_ms = log_contention ? 0 : MilliTime();
208 const mirror::ArtMethod* owners_method = locking_method_;
209 uint32_t owners_dex_pc = locking_dex_pc_;
210 monitor_lock_.Unlock(self); // Let go of locks in order.
Elliott Hughes5f791332011-09-15 17:45:30 -0700211 {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700212 ScopedThreadStateChange tsc(self, kBlocked); // Change to blocked and give up mutator_lock_.
213 MutexLock mu2(self, monitor_lock_); // Reacquire monitor_lock_ without mutator_lock_ for Wait.
214 if (owner_ != NULL) { // Did the owner_ give the lock up?
215 monitor_contenders_.Wait(self); // Still contended so wait.
216 // Woken from contention.
217 if (log_contention) {
218 uint64_t wait_ms = MilliTime() - wait_start_ms;
219 uint32_t sample_percent;
220 if (wait_ms >= lock_profiling_threshold_) {
221 sample_percent = 100;
222 } else {
223 sample_percent = 100 * wait_ms / lock_profiling_threshold_;
224 }
225 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
226 const char* owners_filename;
227 uint32_t owners_line_number;
228 TranslateLocation(owners_method, owners_dex_pc, &owners_filename, &owners_line_number);
229 LogContentionEvent(self, wait_ms, sample_percent, owners_filename, owners_line_number);
230 }
231 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700232 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700233 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700234 monitor_lock_.Lock(self); // Reacquire locks in order.
Elliott Hughesfc861622011-10-17 17:57:47 -0700235 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700236}
237
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800238static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
239 __attribute__((format(printf, 1, 2)));
240
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700241static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700242 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800243 va_list args;
244 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800245 Thread* self = Thread::Current();
246 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
247 self->ThrowNewExceptionV(throw_location, "Ljava/lang/IllegalMonitorStateException;", fmt, args);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700248 if (!Runtime::Current()->IsStarted() || VLOG_IS_ON(monitor)) {
Brian Carlstrom64277f32012-03-26 23:53:34 -0700249 std::ostringstream ss;
Ian Rogers62d6c772013-02-27 08:32:07 -0800250 self->Dump(ss);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700251 LOG(Runtime::Current()->IsStarted() ? INFO : ERROR)
252 << self->GetException(NULL)->Dump() << "\n" << ss.str();
Brian Carlstrom64277f32012-03-26 23:53:34 -0700253 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800254 va_end(args);
255}
256
Elliott Hughesd4237412012-02-21 11:24:45 -0800257static std::string ThreadToString(Thread* thread) {
258 if (thread == NULL) {
259 return "NULL";
260 }
261 std::ostringstream oss;
262 // TODO: alternatively, we could just return the thread's name.
263 oss << *thread;
264 return oss.str();
265}
266
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800267void Monitor::FailedUnlock(mirror::Object* o, Thread* expected_owner, Thread* found_owner,
Elliott Hughesffb465f2012-03-01 18:46:05 -0800268 Monitor* monitor) {
269 Thread* current_owner = NULL;
270 std::string current_owner_string;
271 std::string expected_owner_string;
272 std::string found_owner_string;
273 {
274 // TODO: isn't this too late to prevent threads from disappearing?
275 // Acquire thread list lock so threads won't disappear from under us.
Ian Rogers50b35e22012-10-04 10:09:15 -0700276 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Elliott Hughesffb465f2012-03-01 18:46:05 -0800277 // Re-read owner now that we hold lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700278 current_owner = (monitor != NULL) ? monitor->GetOwner() : NULL;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800279 // Get short descriptions of the threads involved.
280 current_owner_string = ThreadToString(current_owner);
281 expected_owner_string = ThreadToString(expected_owner);
282 found_owner_string = ThreadToString(found_owner);
283 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800284 if (current_owner == NULL) {
285 if (found_owner == NULL) {
286 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
287 " on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800288 PrettyTypeOf(o).c_str(),
289 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800290 } else {
291 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800292 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
293 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800294 found_owner_string.c_str(),
295 PrettyTypeOf(o).c_str(),
296 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800297 }
298 } else {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800299 if (found_owner == NULL) {
300 // Race: originally there was no owner, there is now
301 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
302 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800303 current_owner_string.c_str(),
304 PrettyTypeOf(o).c_str(),
305 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800306 } else {
307 if (found_owner != current_owner) {
308 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800309 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
310 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800311 found_owner_string.c_str(),
312 current_owner_string.c_str(),
313 PrettyTypeOf(o).c_str(),
314 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800315 } else {
316 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
317 " on thread '%s",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800318 current_owner_string.c_str(),
319 PrettyTypeOf(o).c_str(),
320 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800321 }
322 }
323 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700324}
325
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700326bool Monitor::Unlock(Thread* self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700327 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700328 MutexLock mu(self, monitor_lock_);
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800329 Thread* owner = owner_;
330 if (owner == self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700331 // We own the monitor, so nobody else can be in here.
332 if (lock_count_ == 0) {
333 owner_ = NULL;
jeffhao33dc7712011-11-09 17:54:24 -0800334 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700335 locking_dex_pc_ = 0;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700336 // Wake a contender.
337 monitor_contenders_.Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700338 } else {
339 --lock_count_;
340 }
341 } else {
342 // We don't own this, so we're not allowed to unlock it.
343 // The JNI spec says that we should throw IllegalMonitorStateException
344 // in this case.
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800345 FailedUnlock(obj_, self, owner, this);
Elliott Hughes5f791332011-09-15 17:45:30 -0700346 return false;
347 }
348 return true;
349}
350
Elliott Hughes5f791332011-09-15 17:45:30 -0700351/*
352 * Wait on a monitor until timeout, interrupt, or notification. Used for
353 * Object.wait() and (somewhat indirectly) Thread.sleep() and Thread.join().
354 *
355 * If another thread calls Thread.interrupt(), we throw InterruptedException
356 * and return immediately if one of the following are true:
357 * - blocked in wait(), wait(long), or wait(long, int) methods of Object
358 * - blocked in join(), join(long), or join(long, int) methods of Thread
359 * - blocked in sleep(long), or sleep(long, int) methods of Thread
360 * Otherwise, we set the "interrupted" flag.
361 *
362 * Checks to make sure that "ns" is in the range 0-999999
363 * (i.e. fractions of a millisecond) and throws the appropriate
364 * exception if it isn't.
365 *
366 * The spec allows "spurious wakeups", and recommends that all code using
367 * Object.wait() do so in a loop. This appears to derive from concerns
368 * about pthread_cond_wait() on multiprocessor systems. Some commentary
369 * on the web casts doubt on whether these can/should occur.
370 *
371 * Since we're allowed to wake up "early", we clamp extremely long durations
372 * to return at the end of the 32-bit time epoch.
373 */
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800374void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
375 bool interruptShouldThrow, ThreadState why) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700376 DCHECK(self != NULL);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800377 DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
Elliott Hughes5f791332011-09-15 17:45:30 -0700378
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700379 monitor_lock_.Lock(self);
380
Elliott Hughes5f791332011-09-15 17:45:30 -0700381 // Make sure that we hold the lock.
382 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800383 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700384 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700385 return;
386 }
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800387
Elliott Hughesdf42c482013-01-09 12:49:02 -0800388 // We need to turn a zero-length timed wait into a regular wait because
389 // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
390 if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
391 why = kWaiting;
392 }
393
Elliott Hughes5f791332011-09-15 17:45:30 -0700394 // Enforce the timeout range.
395 if (ms < 0 || ns < 0 || ns > 999999) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800396 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
397 self->ThrowNewExceptionF(throw_location, "Ljava/lang/IllegalArgumentException;",
398 "timeout arguments out of range: ms=%lld ns=%d", ms, ns);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700399 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700400 return;
401 }
402
Elliott Hughes5f791332011-09-15 17:45:30 -0700403 /*
404 * Add ourselves to the set of threads waiting on this monitor, and
405 * release our hold. We need to let it go even if we're a few levels
406 * deep in a recursive lock, and we need to restore that later.
407 *
408 * We append to the wait set ahead of clearing the count and owner
409 * fields so the subroutine can check that the calling thread owns
410 * the monitor. Aside from that, the order of member updates is
411 * not order sensitive as we hold the pthread mutex.
412 */
413 AppendToWaitSet(self);
Ian Rogers0399dde2012-06-06 17:09:28 -0700414 int prev_lock_count = lock_count_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700415 lock_count_ = 0;
416 owner_ = NULL;
Brian Carlstromea46f952013-07-30 01:26:50 -0700417 const mirror::ArtMethod* saved_method = locking_method_;
jeffhao33dc7712011-11-09 17:54:24 -0800418 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700419 uintptr_t saved_dex_pc = locking_dex_pc_;
420 locking_dex_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700421
422 /*
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800423 * Update thread state. If the GC wakes up, it'll ignore us, knowing
Elliott Hughes5f791332011-09-15 17:45:30 -0700424 * that we won't touch any references in this state, and we'll check
425 * our suspend mode before we transition out.
426 */
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800427 self->TransitionFromRunnableToSuspended(why);
Elliott Hughes5f791332011-09-15 17:45:30 -0700428
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800429 bool was_interrupted = false;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700430 {
431 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
Ian Rogers50b35e22012-10-04 10:09:15 -0700432 MutexLock mu(self, *self->wait_mutex_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700433
434 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
435 // non-NULL a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
436 // up.
437 DCHECK(self->wait_monitor_ == NULL);
438 self->wait_monitor_ = this;
439
440 // Release the monitor lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700441 monitor_contenders_.Signal(self);
442 monitor_lock_.Unlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700443
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800444 // Handle the case where the thread was interrupted before we called wait().
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700445 if (self->interrupted_) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800446 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700447 } else {
448 // Wait for a notification or a timeout to occur.
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800449 if (why == kWaiting) {
Ian Rogersc604d732012-10-14 16:09:54 -0700450 self->wait_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700451 } else {
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800452 DCHECK(why == kTimedWaiting || why == kSleeping) << why;
Ian Rogersc604d732012-10-14 16:09:54 -0700453 self->wait_cond_->TimedWait(self, ms, ns);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700454 }
455 if (self->interrupted_) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800456 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700457 }
458 self->interrupted_ = false;
459 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700460 }
461
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700462 // Set self->status back to kRunnable, and self-suspend if needed.
463 self->TransitionFromSuspendedToRunnable();
Elliott Hughes5f791332011-09-15 17:45:30 -0700464
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800465 {
466 // We reset the thread's wait_monitor_ field after transitioning back to runnable so
467 // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
468 // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
469 // are waiting on "null".)
470 MutexLock mu(self, *self->wait_mutex_);
471 DCHECK(self->wait_monitor_ != NULL);
472 self->wait_monitor_ = NULL;
473 }
474
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700475 // Re-acquire the monitor and lock.
Elliott Hughes5f791332011-09-15 17:45:30 -0700476 Lock(self);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700477 monitor_lock_.Lock(self);
Ian Rogers81d425b2012-09-27 16:03:43 -0700478 self->wait_mutex_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700479
Elliott Hughes5f791332011-09-15 17:45:30 -0700480 /*
481 * We remove our thread from wait set after restoring the count
482 * and owner fields so the subroutine can check that the calling
483 * thread owns the monitor. Aside from that, the order of member
484 * updates is not order sensitive as we hold the pthread mutex.
485 */
486 owner_ = self;
Ian Rogers0399dde2012-06-06 17:09:28 -0700487 lock_count_ = prev_lock_count;
488 locking_method_ = saved_method;
489 locking_dex_pc_ = saved_dex_pc;
Elliott Hughes5f791332011-09-15 17:45:30 -0700490 RemoveFromWaitSet(self);
491
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800492 if (was_interrupted) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700493 /*
494 * We were interrupted while waiting, or somebody interrupted an
495 * un-interruptible thread earlier and we're bailing out immediately.
496 *
497 * The doc sayeth: "The interrupted status of the current thread is
498 * cleared when this exception is thrown."
499 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700500 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700501 MutexLock mu(self, *self->wait_mutex_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700502 self->interrupted_ = false;
503 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700504 if (interruptShouldThrow) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800505 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
506 self->ThrowNewException(throw_location, "Ljava/lang/InterruptedException;", NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700507 }
508 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700509 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700510}
511
512void Monitor::Notify(Thread* self) {
513 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700514 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700515 // Make sure that we hold the lock.
516 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800517 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700518 return;
519 }
520 // Signal the first waiting thread in the wait set.
521 while (wait_set_ != NULL) {
522 Thread* thread = wait_set_;
523 wait_set_ = thread->wait_next_;
524 thread->wait_next_ = NULL;
525
526 // Check to see if the thread is still waiting.
Ian Rogers50b35e22012-10-04 10:09:15 -0700527 MutexLock mu(self, *thread->wait_mutex_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700528 if (thread->wait_monitor_ != NULL) {
Ian Rogersc604d732012-10-14 16:09:54 -0700529 thread->wait_cond_->Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700530 return;
531 }
532 }
533}
534
535void Monitor::NotifyAll(Thread* self) {
536 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700537 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700538 // Make sure that we hold the lock.
539 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800540 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700541 return;
542 }
543 // Signal all threads in the wait set.
544 while (wait_set_ != NULL) {
545 Thread* thread = wait_set_;
546 wait_set_ = thread->wait_next_;
547 thread->wait_next_ = NULL;
548 thread->Notify();
549 }
550}
551
552/*
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700553 * Changes the shape of a monitor from thin to fat, preserving the internal lock state. The calling
554 * thread must own the lock or the owner must be suspended. There's a race with other threads
555 * inflating the lock and so the caller should read the monitor following the call.
Elliott Hughes5f791332011-09-15 17:45:30 -0700556 */
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700557void Monitor::Inflate(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700558 DCHECK(self != NULL);
559 DCHECK(obj != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700560 // Allocate and acquire a new monitor.
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700561 UniquePtr<Monitor> m(new Monitor(owner, obj, hash_code));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700562 if (m->Install(self)) {
563 VLOG(monitor) << "monitor: thread " << owner->GetThreadId()
564 << " created monitor " << m.get() << " for object " << obj;
565 Runtime::Current()->GetMonitorList()->Add(m.release());
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700566 CHECK_EQ(obj->GetLockWord().GetState(), LockWord::kFatLocked);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700567 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700568}
569
570void Monitor::InflateThinLocked(Thread* self, mirror::Object* obj, LockWord lock_word,
571 uint32_t hash_code) {
572 DCHECK_EQ(lock_word.GetState(), LockWord::kThinLocked);
573 uint32_t owner_thread_id = lock_word.ThinLockOwner();
574 if (owner_thread_id == self->GetThreadId()) {
575 // We own the monitor, we can easily inflate it.
576 Inflate(self, self, obj, hash_code);
577 } else {
578 ThreadList* thread_list = Runtime::Current()->GetThreadList();
579 // Suspend the owner, inflate. First change to blocked and give up mutator_lock_.
580 ScopedThreadStateChange tsc(self, kBlocked);
581 if (lock_word == obj->GetLockWord()) { // If lock word hasn't changed.
582 bool timed_out;
583 Thread* owner = thread_list->SuspendThreadByThreadId(lock_word.ThinLockOwner(), false,
584 &timed_out);
585 if (owner != nullptr) {
586 // We succeeded in suspending the thread, check the lock's status didn't change.
587 lock_word = obj->GetLockWord();
588 if (lock_word.GetState() == LockWord::kThinLocked &&
589 lock_word.ThinLockOwner() == owner_thread_id) {
590 // Go ahead and inflate the lock.
591 Inflate(self, owner, obj, hash_code);
592 }
593 thread_list->Resume(owner, false);
594 }
595 }
596 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700597}
598
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800599void Monitor::MonitorEnter(Thread* self, mirror::Object* obj) {
Elliott Hughes4681c802011-09-25 18:04:37 -0700600 DCHECK(self != NULL);
601 DCHECK(obj != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700602 uint32_t thread_id = self->GetThreadId();
603 size_t contention_count = 0;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700604 while (true) {
605 LockWord lock_word = obj->GetLockWord();
606 switch (lock_word.GetState()) {
607 case LockWord::kUnlocked: {
608 LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0));
609 if (obj->CasLockWord(lock_word, thin_locked)) {
610 return; // Success!
611 }
612 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -0700613 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700614 case LockWord::kThinLocked: {
615 uint32_t owner_thread_id = lock_word.ThinLockOwner();
616 if (owner_thread_id == thread_id) {
617 // We own the lock, increase the recursion count.
618 uint32_t new_count = lock_word.ThinLockCount() + 1;
619 if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
620 LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count));
621 obj->SetLockWord(thin_locked);
622 return; // Success!
Elliott Hughes5f791332011-09-15 17:45:30 -0700623 } else {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700624 // We'd overflow the recursion count, so inflate the monitor.
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700625 InflateThinLocked(self, obj, lock_word, mirror::Object::GenerateIdentityHashCode());
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700626 }
627 } else {
628 // Contention.
629 contention_count++;
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700630 Runtime* runtime = Runtime::Current();
631 if (contention_count <= runtime->GetMaxSpinsBeforeThinkLockInflation()) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700632 NanoSleep(1000); // Sleep for 1us and re-attempt.
633 } else {
634 contention_count = 0;
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700635 InflateThinLocked(self, obj, lock_word, mirror::Object::GenerateIdentityHashCode());
Elliott Hughes5f791332011-09-15 17:45:30 -0700636 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700637 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700638 continue; // Start from the beginning.
Elliott Hughes5f791332011-09-15 17:45:30 -0700639 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700640 case LockWord::kFatLocked: {
641 Monitor* mon = lock_word.FatLockMonitor();
642 mon->Lock(self);
643 return; // Success!
644 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700645 case LockWord::kHashCode: {
646 // Inflate with the existing hashcode.
647 Inflate(self, nullptr, obj, lock_word.GetHashCode());
648 break;
649 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700650 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700651 }
652}
653
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800654bool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700655 DCHECK(self != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700656 DCHECK(obj != NULL);
657
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700658 LockWord lock_word = obj->GetLockWord();
659 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700660 case LockWord::kHashCode:
661 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700662 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800663 FailedUnlock(obj, self, NULL, NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700664 return false; // Failure.
665 case LockWord::kThinLocked: {
666 uint32_t thread_id = self->GetThreadId();
667 uint32_t owner_thread_id = lock_word.ThinLockOwner();
668 if (owner_thread_id != thread_id) {
669 // TODO: there's a race here with the owner dying while we unlock.
670 Thread* owner =
671 Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
672 FailedUnlock(obj, self, owner, NULL);
673 return false; // Failure.
674 } else {
675 // We own the lock, decrease the recursion count.
676 if (lock_word.ThinLockCount() != 0) {
677 uint32_t new_count = lock_word.ThinLockCount() - 1;
678 LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count));
679 obj->SetLockWord(thin_locked);
680 } else {
681 obj->SetLockWord(LockWord());
682 }
683 return true; // Success!
684 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700685 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700686 case LockWord::kFatLocked: {
687 Monitor* mon = lock_word.FatLockMonitor();
688 return mon->Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700689 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700690 default:
691 LOG(FATAL) << "Unreachable";
692 return false;
Elliott Hughes5f791332011-09-15 17:45:30 -0700693 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700694}
695
696/*
697 * Object.wait(). Also called for class init.
698 */
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800699void Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800700 bool interruptShouldThrow, ThreadState why) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700701 DCHECK(self != NULL);
702 DCHECK(obj != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700703
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700704 LockWord lock_word = obj->GetLockWord();
705 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700706 case LockWord::kHashCode:
707 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700708 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800709 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700710 return; // Failure.
711 case LockWord::kThinLocked: {
712 uint32_t thread_id = self->GetThreadId();
713 uint32_t owner_thread_id = lock_word.ThinLockOwner();
714 if (owner_thread_id != thread_id) {
715 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
716 return; // Failure.
717 } else {
718 // We own the lock, inflate to enqueue ourself on the Monitor.
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700719 Inflate(self, self, obj, mirror::Object::GenerateIdentityHashCode());
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700720 lock_word = obj->GetLockWord();
721 }
722 break;
Elliott Hughes5f791332011-09-15 17:45:30 -0700723 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700724 case LockWord::kFatLocked:
725 break; // Already set for a wait.
Elliott Hughes5f791332011-09-15 17:45:30 -0700726 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700727 Monitor* mon = lock_word.FatLockMonitor();
728 mon->Wait(self, ms, ns, interruptShouldThrow, why);
Elliott Hughes5f791332011-09-15 17:45:30 -0700729}
730
Ian Rogers13c479e2013-10-11 07:59:01 -0700731void Monitor::DoNotify(Thread* self, mirror::Object* obj, bool notify_all) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700732 DCHECK(self != NULL);
733 DCHECK(obj != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700734
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700735 LockWord lock_word = obj->GetLockWord();
736 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700737 case LockWord::kHashCode:
738 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700739 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800740 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700741 return; // Failure.
742 case LockWord::kThinLocked: {
743 uint32_t thread_id = self->GetThreadId();
744 uint32_t owner_thread_id = lock_word.ThinLockOwner();
745 if (owner_thread_id != thread_id) {
746 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
747 return; // Failure.
748 } else {
749 // We own the lock but there's no Monitor and therefore no waiters.
750 return; // Success.
751 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700752 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700753 case LockWord::kFatLocked: {
754 Monitor* mon = lock_word.FatLockMonitor();
755 if (notify_all) {
756 mon->NotifyAll(self);
757 } else {
758 mon->Notify(self);
759 }
760 return; // Success.
761 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700762 }
763}
764
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700765uint32_t Monitor::GetLockOwnerThreadId(mirror::Object* obj) {
766 DCHECK(obj != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700767
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700768 LockWord lock_word = obj->GetLockWord();
769 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700770 case LockWord::kHashCode:
771 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700772 case LockWord::kUnlocked:
773 return ThreadList::kInvalidThreadId;
774 case LockWord::kThinLocked:
775 return lock_word.ThinLockOwner();
776 case LockWord::kFatLocked: {
777 Monitor* mon = lock_word.FatLockMonitor();
778 return mon->GetOwnerThreadId();
Elliott Hughes5f791332011-09-15 17:45:30 -0700779 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700780 default:
781 LOG(FATAL) << "Unreachable";
782 return ThreadList::kInvalidThreadId;
Elliott Hughes5f791332011-09-15 17:45:30 -0700783 }
784}
785
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700786void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800787 ThreadState state = thread->GetState();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700788
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700789 int32_t object_identity_hashcode = 0;
790 uint32_t lock_owner = ThreadList::kInvalidThreadId;
791 std::string pretty_type;
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800792 if (state == kWaiting || state == kTimedWaiting || state == kSleeping) {
793 if (state == kSleeping) {
794 os << " - sleeping on ";
795 } else {
796 os << " - waiting on ";
797 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700798 {
Elliott Hughesf9501702013-01-11 11:22:27 -0800799 Thread* self = Thread::Current();
800 MutexLock mu(self, *thread->wait_mutex_);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800801 Monitor* monitor = thread->wait_monitor_;
802 if (monitor != NULL) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700803 mirror::Object* object = monitor->obj_;
804 object_identity_hashcode = object->IdentityHashCode();
805 pretty_type = PrettyTypeOf(object);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800806 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700807 }
Elliott Hughes34e06962012-04-09 13:55:55 -0700808 } else if (state == kBlocked) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700809 os << " - waiting to lock ";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700810 mirror::Object* object = thread->monitor_enter_object_;
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700811 if (object != NULL) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700812 object_identity_hashcode = object->IdentityHashCode();
813 lock_owner = object->GetLockOwnerThreadId();
814 pretty_type = PrettyTypeOf(object);
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700815 }
816 } else {
817 // We're not waiting on anything.
818 return;
819 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700820
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700821 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700822 os << StringPrintf("<0x%08x> (a %s)", object_identity_hashcode, pretty_type.c_str());
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700823
Elliott Hughesc5dc2ff2013-01-09 13:44:30 -0800824 // - waiting to lock <0x613f83d8> (a java.lang.Object) held by thread 5
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700825 if (lock_owner != ThreadList::kInvalidThreadId) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700826 os << " held by thread " << lock_owner;
827 }
828
829 os << "\n";
830}
831
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800832mirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800833 // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
834 // definition of contended that includes a monitor a thread is trying to enter...
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800835 mirror::Object* result = thread->monitor_enter_object_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700836 if (result == NULL) {
837 // ...but also a monitor that the thread is waiting on.
Elliott Hughesf9501702013-01-11 11:22:27 -0800838 MutexLock mu(Thread::Current(), *thread->wait_mutex_);
839 Monitor* monitor = thread->wait_monitor_;
840 if (monitor != NULL) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700841 result = monitor->GetObject();
Elliott Hughesf9501702013-01-11 11:22:27 -0800842 }
843 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700844 return result;
Elliott Hughesf9501702013-01-11 11:22:27 -0800845}
846
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800847void Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
848 void* callback_context) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700849 mirror::ArtMethod* m = stack_visitor->GetMethod();
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700850 CHECK(m != NULL);
851
852 // Native methods are an easy special case.
853 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
854 if (m->IsNative()) {
855 if (m->IsSynchronized()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800856 mirror::Object* jni_this = stack_visitor->GetCurrentSirt()->GetReference(0);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800857 callback(jni_this, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700858 }
859 return;
860 }
861
jeffhao61f916c2012-10-25 17:48:51 -0700862 // Proxy methods should not be synchronized.
863 if (m->IsProxyMethod()) {
864 CHECK(!m->IsSynchronized());
865 return;
866 }
867
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700868 // <clinit> is another special case. The runtime holds the class lock while calling <clinit>.
869 MethodHelper mh(m);
870 if (mh.IsClassInitializer()) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800871 callback(m->GetDeclaringClass(), callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700872 // Fall through because there might be synchronization in the user code too.
873 }
874
875 // Is there any reason to believe there's any synchronization in this method?
876 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -0700877 CHECK(code_item != NULL) << PrettyMethod(m);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700878 if (code_item->tries_size_ == 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700879 return; // No "tries" implies no synchronization, so no held locks to report.
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700880 }
881
Elliott Hughes80537bb2013-01-04 16:37:26 -0800882 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
883 // the locks held in this stack frame.
884 std::vector<uint32_t> monitor_enter_dex_pcs;
885 verifier::MethodVerifier::FindLocksAtDexPc(m, stack_visitor->GetDexPc(), monitor_enter_dex_pcs);
886 if (monitor_enter_dex_pcs.empty()) {
887 return;
888 }
889
Elliott Hughes80537bb2013-01-04 16:37:26 -0800890 for (size_t i = 0; i < monitor_enter_dex_pcs.size(); ++i) {
891 // The verifier works in terms of the dex pcs of the monitor-enter instructions.
892 // We want the registers used by those instructions (so we can read the values out of them).
893 uint32_t dex_pc = monitor_enter_dex_pcs[i];
894 uint16_t monitor_enter_instruction = code_item->insns_[dex_pc];
895
896 // Quick sanity check.
897 if ((monitor_enter_instruction & 0xff) != Instruction::MONITOR_ENTER) {
898 LOG(FATAL) << "expected monitor-enter @" << dex_pc << "; was "
899 << reinterpret_cast<void*>(monitor_enter_instruction);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700900 }
901
Elliott Hughes80537bb2013-01-04 16:37:26 -0800902 uint16_t monitor_register = ((monitor_enter_instruction >> 8) & 0xff);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800903 mirror::Object* o = reinterpret_cast<mirror::Object*>(stack_visitor->GetVReg(m, monitor_register,
904 kReferenceVReg));
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800905 callback(o, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700906 }
907}
908
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700909bool Monitor::IsValidLockWord(LockWord lock_word) {
910 switch (lock_word.GetState()) {
911 case LockWord::kUnlocked:
912 // Nothing to check.
913 return true;
914 case LockWord::kThinLocked:
915 // Basic sanity check of owner.
916 return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
917 case LockWord::kFatLocked: {
918 // Check the monitor appears in the monitor list.
919 Monitor* mon = lock_word.FatLockMonitor();
920 MonitorList* list = Runtime::Current()->GetMonitorList();
921 MutexLock mu(Thread::Current(), list->monitor_list_lock_);
922 for (Monitor* list_mon : list->list_) {
923 if (mon == list_mon) {
924 return true; // Found our monitor.
925 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700926 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700927 return false; // Fail - unowned monitor in an object.
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700928 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700929 case LockWord::kHashCode:
930 return true;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700931 default:
932 LOG(FATAL) << "Unreachable";
933 return false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700934 }
935}
936
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700937bool Monitor::IsLocked() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
938 MutexLock mu(Thread::Current(), monitor_lock_);
939 return owner_ != nullptr;
940}
941
Brian Carlstromea46f952013-07-30 01:26:50 -0700942void Monitor::TranslateLocation(const mirror::ArtMethod* method, uint32_t dex_pc,
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700943 const char** source_file, uint32_t* line_number) const {
jeffhao33dc7712011-11-09 17:54:24 -0800944 // If method is null, location is unknown
945 if (method == NULL) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700946 *source_file = "";
947 *line_number = 0;
jeffhao33dc7712011-11-09 17:54:24 -0800948 return;
949 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800950 MethodHelper mh(method);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700951 *source_file = mh.GetDeclaringClassSourceFile();
952 if (*source_file == NULL) {
953 *source_file = "";
Elliott Hughes12c51e32012-01-17 20:25:05 -0800954 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700955 *line_number = mh.GetLineNumFromDexPC(dex_pc);
956}
957
958uint32_t Monitor::GetOwnerThreadId() {
959 MutexLock mu(Thread::Current(), monitor_lock_);
960 Thread* owner = owner_;
961 if (owner != NULL) {
962 return owner->GetThreadId();
963 } else {
964 return ThreadList::kInvalidThreadId;
965 }
jeffhao33dc7712011-11-09 17:54:24 -0800966}
967
Mathieu Chartierc11d9b82013-09-19 10:01:59 -0700968MonitorList::MonitorList()
969 : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock"),
970 monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700971}
972
973MonitorList::~MonitorList() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700974 MutexLock mu(Thread::Current(), monitor_list_lock_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700975 STLDeleteElements(&list_);
976}
977
Mathieu Chartierc11d9b82013-09-19 10:01:59 -0700978void MonitorList::DisallowNewMonitors() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700979 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -0700980 allow_new_monitors_ = false;
981}
982
983void MonitorList::AllowNewMonitors() {
984 Thread* self = Thread::Current();
985 MutexLock mu(self, monitor_list_lock_);
986 allow_new_monitors_ = true;
987 monitor_add_condition_.Broadcast(self);
988}
989
990void MonitorList::Add(Monitor* m) {
991 Thread* self = Thread::Current();
992 MutexLock mu(self, monitor_list_lock_);
993 while (UNLIKELY(!allow_new_monitors_)) {
994 monitor_add_condition_.WaitHoldingLocks(self);
995 }
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700996 list_.push_front(m);
997}
998
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700999void MonitorList::SweepMonitorList(RootVisitor visitor, void* arg) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001000 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001001 for (auto it = list_.begin(); it != list_.end(); ) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001002 Monitor* m = *it;
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001003 mirror::Object* obj = m->GetObject();
1004 mirror::Object* new_obj = visitor(obj, arg);
1005 if (new_obj == nullptr) {
1006 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
1007 << m->GetObject();
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001008 delete m;
1009 it = list_.erase(it);
1010 } else {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001011 m->SetObject(new_obj);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001012 ++it;
1013 }
1014 }
1015}
1016
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001017MonitorInfo::MonitorInfo(mirror::Object* obj) : owner_(NULL), entry_count_(0) {
1018 DCHECK(obj != NULL);
1019
1020 LockWord lock_word = obj->GetLockWord();
1021 switch (lock_word.GetState()) {
1022 case LockWord::kUnlocked:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001023 // Fall-through.
1024 case LockWord::kHashCode:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001025 break;
1026 case LockWord::kThinLocked:
1027 owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
1028 entry_count_ = 1 + lock_word.ThinLockCount();
1029 // Thin locks have no waiters.
1030 break;
1031 case LockWord::kFatLocked: {
1032 Monitor* mon = lock_word.FatLockMonitor();
1033 owner_ = mon->owner_;
1034 entry_count_ = 1 + mon->lock_count_;
1035 for (Thread* waiter = mon->wait_set_; waiter != NULL; waiter = waiter->wait_next_) {
1036 waiters_.push_back(waiter);
1037 }
1038 break;
Elliott Hughesf327e072013-01-09 16:01:26 -08001039 }
1040 }
1041}
1042
Elliott Hughes5f791332011-09-15 17:45:30 -07001043} // namespace art