blob: af93a56264701b14947deb3a53ca13a17c3d63eb [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 Chartier4e6a31e2013-10-31 10:35:05 -070082Monitor::Monitor(Thread* owner, mirror::Object* obj, int32_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_),
Mathieu Chartier46bc7782013-11-12 17:03:02 -080085 num_waiters_(0),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070086 owner_(owner),
Elliott Hughes5f791332011-09-15 17:45:30 -070087 lock_count_(0),
88 obj_(obj),
89 wait_set_(NULL),
Mathieu Chartierad2541a2013-10-25 10:05:23 -070090 hash_code_(hash_code),
jeffhao33dc7712011-11-09 17:54:24 -080091 locking_method_(NULL),
Ian Rogers0399dde2012-06-06 17:09:28 -070092 locking_dex_pc_(0) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -070093 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
94 // with the owner unlocking the thin-lock.
Mathieu Chartierad2541a2013-10-25 10:05:23 -070095 CHECK(owner == nullptr || owner == Thread::Current() || owner->IsSuspended());
96 // The identity hash code is set for the life time of the monitor.
Ian Rogersd9c4fc92013-10-01 19:45:43 -070097}
98
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -070099int32_t Monitor::GetHashCode() {
100 while (!HasHashCode()) {
101 if (hash_code_.compare_and_swap(0, mirror::Object::GenerateIdentityHashCode())) {
102 break;
103 }
104 }
105 DCHECK(HasHashCode());
106 return hash_code_.load();
107}
108
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700109bool Monitor::Install(Thread* self) {
110 MutexLock mu(self, monitor_lock_); // Uncontended mutex acquisition as monitor isn't yet public.
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700111 CHECK(owner_ == nullptr || owner_ == self || owner_->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700112 // Propagate the lock state.
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700113 LockWord lw(obj_->GetLockWord());
114 switch (lw.GetState()) {
115 case LockWord::kThinLocked: {
116 CHECK_EQ(owner_->GetThreadId(), lw.ThinLockOwner());
117 lock_count_ = lw.ThinLockCount();
118 break;
119 }
120 case LockWord::kHashCode: {
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700121 CHECK_EQ(hash_code_, static_cast<int32_t>(lw.GetHashCode()));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700122 break;
123 }
124 case LockWord::kFatLocked: {
125 // The owner_ is suspended but another thread beat us to install a monitor.
126 return false;
127 }
128 case LockWord::kUnlocked: {
129 LOG(FATAL) << "Inflating unlocked lock word";
130 break;
131 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700132 default: {
133 LOG(FATAL) << "Invalid monitor state " << lw.GetState();
134 return false;
135 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700136 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700137 LockWord fat(this);
138 // Publish the updated lock word, which may race with other threads.
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700139 bool success = obj_->CasLockWord(lw, fat);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700140 // Lock profiling.
Mathieu Chartier9728f912013-10-30 09:45:13 -0700141 if (success && owner_ != nullptr && lock_profiling_threshold_ != 0) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700142 locking_method_ = owner_->GetCurrentMethod(&locking_dex_pc_);
143 }
144 return success;
Elliott Hughes5f791332011-09-15 17:45:30 -0700145}
146
147Monitor::~Monitor() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700148 // Deflated monitors have a null object.
Elliott Hughes5f791332011-09-15 17:45:30 -0700149}
150
151/*
152 * Links a thread into a monitor's wait set. The monitor lock must be
153 * held by the caller of this routine.
154 */
155void Monitor::AppendToWaitSet(Thread* thread) {
156 DCHECK(owner_ == Thread::Current());
157 DCHECK(thread != NULL);
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700158 DCHECK(thread->wait_next_ == NULL) << thread->wait_next_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700159 if (wait_set_ == NULL) {
160 wait_set_ = thread;
161 return;
162 }
163
164 // push_back.
165 Thread* t = wait_set_;
166 while (t->wait_next_ != NULL) {
167 t = t->wait_next_;
168 }
169 t->wait_next_ = thread;
170}
171
172/*
173 * Unlinks a thread from a monitor's wait set. The monitor lock must
174 * be held by the caller of this routine.
175 */
176void Monitor::RemoveFromWaitSet(Thread *thread) {
177 DCHECK(owner_ == Thread::Current());
178 DCHECK(thread != NULL);
179 if (wait_set_ == NULL) {
180 return;
181 }
182 if (wait_set_ == thread) {
183 wait_set_ = thread->wait_next_;
184 thread->wait_next_ = NULL;
185 return;
186 }
187
188 Thread* t = wait_set_;
189 while (t->wait_next_ != NULL) {
190 if (t->wait_next_ == thread) {
191 t->wait_next_ = thread->wait_next_;
192 thread->wait_next_ = NULL;
193 return;
194 }
195 t = t->wait_next_;
196 }
197}
198
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700199void Monitor::SetObject(mirror::Object* object) {
200 obj_ = object;
201}
202
Elliott Hughes5f791332011-09-15 17:45:30 -0700203void Monitor::Lock(Thread* self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700204 MutexLock mu(self, monitor_lock_);
205 while (true) {
206 if (owner_ == NULL) { // Unowned.
207 owner_ = self;
208 CHECK_EQ(lock_count_, 0);
209 // When debugging, save the current monitor holder for future
210 // acquisition failures to use in sampled logging.
211 if (lock_profiling_threshold_ != 0) {
212 locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
213 }
214 return;
215 } else if (owner_ == self) { // Recursive.
216 lock_count_++;
217 return;
218 }
219 // Contended.
220 const bool log_contention = (lock_profiling_threshold_ != 0);
221 uint64_t wait_start_ms = log_contention ? 0 : MilliTime();
222 const mirror::ArtMethod* owners_method = locking_method_;
223 uint32_t owners_dex_pc = locking_dex_pc_;
224 monitor_lock_.Unlock(self); // Let go of locks in order.
Elliott Hughes5f791332011-09-15 17:45:30 -0700225 {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700226 ScopedThreadStateChange tsc(self, kBlocked); // Change to blocked and give up mutator_lock_.
227 MutexLock mu2(self, monitor_lock_); // Reacquire monitor_lock_ without mutator_lock_ for Wait.
228 if (owner_ != NULL) { // Did the owner_ give the lock up?
Mathieu Chartier46bc7782013-11-12 17:03:02 -0800229 ++num_waiters_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700230 monitor_contenders_.Wait(self); // Still contended so wait.
Mathieu Chartier46bc7782013-11-12 17:03:02 -0800231 --num_waiters_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700232 // Woken from contention.
233 if (log_contention) {
234 uint64_t wait_ms = MilliTime() - wait_start_ms;
235 uint32_t sample_percent;
236 if (wait_ms >= lock_profiling_threshold_) {
237 sample_percent = 100;
238 } else {
239 sample_percent = 100 * wait_ms / lock_profiling_threshold_;
240 }
241 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
242 const char* owners_filename;
243 uint32_t owners_line_number;
244 TranslateLocation(owners_method, owners_dex_pc, &owners_filename, &owners_line_number);
245 LogContentionEvent(self, wait_ms, sample_percent, owners_filename, owners_line_number);
246 }
247 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700248 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700249 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700250 monitor_lock_.Lock(self); // Reacquire locks in order.
Elliott Hughesfc861622011-10-17 17:57:47 -0700251 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700252}
253
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800254static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
255 __attribute__((format(printf, 1, 2)));
256
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700257static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700258 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800259 va_list args;
260 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800261 Thread* self = Thread::Current();
262 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
263 self->ThrowNewExceptionV(throw_location, "Ljava/lang/IllegalMonitorStateException;", fmt, args);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700264 if (!Runtime::Current()->IsStarted() || VLOG_IS_ON(monitor)) {
Brian Carlstrom64277f32012-03-26 23:53:34 -0700265 std::ostringstream ss;
Ian Rogers62d6c772013-02-27 08:32:07 -0800266 self->Dump(ss);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700267 LOG(Runtime::Current()->IsStarted() ? INFO : ERROR)
268 << self->GetException(NULL)->Dump() << "\n" << ss.str();
Brian Carlstrom64277f32012-03-26 23:53:34 -0700269 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800270 va_end(args);
271}
272
Elliott Hughesd4237412012-02-21 11:24:45 -0800273static std::string ThreadToString(Thread* thread) {
274 if (thread == NULL) {
275 return "NULL";
276 }
277 std::ostringstream oss;
278 // TODO: alternatively, we could just return the thread's name.
279 oss << *thread;
280 return oss.str();
281}
282
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800283void Monitor::FailedUnlock(mirror::Object* o, Thread* expected_owner, Thread* found_owner,
Elliott Hughesffb465f2012-03-01 18:46:05 -0800284 Monitor* monitor) {
285 Thread* current_owner = NULL;
286 std::string current_owner_string;
287 std::string expected_owner_string;
288 std::string found_owner_string;
289 {
290 // TODO: isn't this too late to prevent threads from disappearing?
291 // Acquire thread list lock so threads won't disappear from under us.
Ian Rogers50b35e22012-10-04 10:09:15 -0700292 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Elliott Hughesffb465f2012-03-01 18:46:05 -0800293 // Re-read owner now that we hold lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700294 current_owner = (monitor != NULL) ? monitor->GetOwner() : NULL;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800295 // Get short descriptions of the threads involved.
296 current_owner_string = ThreadToString(current_owner);
297 expected_owner_string = ThreadToString(expected_owner);
298 found_owner_string = ThreadToString(found_owner);
299 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800300 if (current_owner == NULL) {
301 if (found_owner == NULL) {
302 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
303 " on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800304 PrettyTypeOf(o).c_str(),
305 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800306 } else {
307 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800308 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
309 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800310 found_owner_string.c_str(),
311 PrettyTypeOf(o).c_str(),
312 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800313 }
314 } else {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800315 if (found_owner == NULL) {
316 // Race: originally there was no owner, there is now
317 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
318 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800319 current_owner_string.c_str(),
320 PrettyTypeOf(o).c_str(),
321 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800322 } else {
323 if (found_owner != current_owner) {
324 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800325 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
326 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800327 found_owner_string.c_str(),
328 current_owner_string.c_str(),
329 PrettyTypeOf(o).c_str(),
330 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800331 } else {
332 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
333 " on thread '%s",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800334 current_owner_string.c_str(),
335 PrettyTypeOf(o).c_str(),
336 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800337 }
338 }
339 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700340}
341
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700342bool Monitor::Unlock(Thread* self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700343 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700344 MutexLock mu(self, monitor_lock_);
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800345 Thread* owner = owner_;
346 if (owner == self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700347 // We own the monitor, so nobody else can be in here.
348 if (lock_count_ == 0) {
349 owner_ = NULL;
jeffhao33dc7712011-11-09 17:54:24 -0800350 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700351 locking_dex_pc_ = 0;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700352 // Wake a contender.
353 monitor_contenders_.Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700354 } else {
355 --lock_count_;
356 }
357 } else {
358 // We don't own this, so we're not allowed to unlock it.
359 // The JNI spec says that we should throw IllegalMonitorStateException
360 // in this case.
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800361 FailedUnlock(obj_, self, owner, this);
Elliott Hughes5f791332011-09-15 17:45:30 -0700362 return false;
363 }
364 return true;
365}
366
Elliott Hughes5f791332011-09-15 17:45:30 -0700367/*
368 * Wait on a monitor until timeout, interrupt, or notification. Used for
369 * Object.wait() and (somewhat indirectly) Thread.sleep() and Thread.join().
370 *
371 * If another thread calls Thread.interrupt(), we throw InterruptedException
372 * and return immediately if one of the following are true:
373 * - blocked in wait(), wait(long), or wait(long, int) methods of Object
374 * - blocked in join(), join(long), or join(long, int) methods of Thread
375 * - blocked in sleep(long), or sleep(long, int) methods of Thread
376 * Otherwise, we set the "interrupted" flag.
377 *
378 * Checks to make sure that "ns" is in the range 0-999999
379 * (i.e. fractions of a millisecond) and throws the appropriate
380 * exception if it isn't.
381 *
382 * The spec allows "spurious wakeups", and recommends that all code using
383 * Object.wait() do so in a loop. This appears to derive from concerns
384 * about pthread_cond_wait() on multiprocessor systems. Some commentary
385 * on the web casts doubt on whether these can/should occur.
386 *
387 * Since we're allowed to wake up "early", we clamp extremely long durations
388 * to return at the end of the 32-bit time epoch.
389 */
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800390void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
391 bool interruptShouldThrow, ThreadState why) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700392 DCHECK(self != NULL);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800393 DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
Elliott Hughes5f791332011-09-15 17:45:30 -0700394
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700395 monitor_lock_.Lock(self);
396
Elliott Hughes5f791332011-09-15 17:45:30 -0700397 // Make sure that we hold the lock.
398 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800399 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700400 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700401 return;
402 }
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800403
Elliott Hughesdf42c482013-01-09 12:49:02 -0800404 // We need to turn a zero-length timed wait into a regular wait because
405 // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
406 if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
407 why = kWaiting;
408 }
409
Elliott Hughes5f791332011-09-15 17:45:30 -0700410 // Enforce the timeout range.
411 if (ms < 0 || ns < 0 || ns > 999999) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800412 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
413 self->ThrowNewExceptionF(throw_location, "Ljava/lang/IllegalArgumentException;",
414 "timeout arguments out of range: ms=%lld ns=%d", ms, ns);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700415 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700416 return;
417 }
418
Elliott Hughes5f791332011-09-15 17:45:30 -0700419 /*
420 * Add ourselves to the set of threads waiting on this monitor, and
421 * release our hold. We need to let it go even if we're a few levels
422 * deep in a recursive lock, and we need to restore that later.
423 *
424 * We append to the wait set ahead of clearing the count and owner
425 * fields so the subroutine can check that the calling thread owns
426 * the monitor. Aside from that, the order of member updates is
427 * not order sensitive as we hold the pthread mutex.
428 */
429 AppendToWaitSet(self);
Ian Rogers0399dde2012-06-06 17:09:28 -0700430 int prev_lock_count = lock_count_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700431 lock_count_ = 0;
432 owner_ = NULL;
Brian Carlstromea46f952013-07-30 01:26:50 -0700433 const mirror::ArtMethod* saved_method = locking_method_;
jeffhao33dc7712011-11-09 17:54:24 -0800434 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700435 uintptr_t saved_dex_pc = locking_dex_pc_;
436 locking_dex_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700437
438 /*
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800439 * Update thread state. If the GC wakes up, it'll ignore us, knowing
Elliott Hughes5f791332011-09-15 17:45:30 -0700440 * that we won't touch any references in this state, and we'll check
441 * our suspend mode before we transition out.
442 */
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800443 self->TransitionFromRunnableToSuspended(why);
Elliott Hughes5f791332011-09-15 17:45:30 -0700444
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800445 bool was_interrupted = false;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700446 {
447 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
Ian Rogers50b35e22012-10-04 10:09:15 -0700448 MutexLock mu(self, *self->wait_mutex_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700449
450 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
451 // non-NULL a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
452 // up.
453 DCHECK(self->wait_monitor_ == NULL);
454 self->wait_monitor_ = this;
455
456 // Release the monitor lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700457 monitor_contenders_.Signal(self);
458 monitor_lock_.Unlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700459
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800460 // Handle the case where the thread was interrupted before we called wait().
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700461 if (self->interrupted_) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800462 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700463 } else {
464 // Wait for a notification or a timeout to occur.
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800465 if (why == kWaiting) {
Ian Rogersc604d732012-10-14 16:09:54 -0700466 self->wait_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700467 } else {
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800468 DCHECK(why == kTimedWaiting || why == kSleeping) << why;
Ian Rogersc604d732012-10-14 16:09:54 -0700469 self->wait_cond_->TimedWait(self, ms, ns);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700470 }
471 if (self->interrupted_) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800472 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700473 }
474 self->interrupted_ = false;
475 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700476 }
477
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700478 // Set self->status back to kRunnable, and self-suspend if needed.
479 self->TransitionFromSuspendedToRunnable();
Elliott Hughes5f791332011-09-15 17:45:30 -0700480
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800481 {
482 // We reset the thread's wait_monitor_ field after transitioning back to runnable so
483 // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
484 // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
485 // are waiting on "null".)
486 MutexLock mu(self, *self->wait_mutex_);
487 DCHECK(self->wait_monitor_ != NULL);
488 self->wait_monitor_ = NULL;
489 }
490
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700491 // Re-acquire the monitor and lock.
Elliott Hughes5f791332011-09-15 17:45:30 -0700492 Lock(self);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700493 monitor_lock_.Lock(self);
Ian Rogers81d425b2012-09-27 16:03:43 -0700494 self->wait_mutex_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700495
Elliott Hughes5f791332011-09-15 17:45:30 -0700496 /*
497 * We remove our thread from wait set after restoring the count
498 * and owner fields so the subroutine can check that the calling
499 * thread owns the monitor. Aside from that, the order of member
500 * updates is not order sensitive as we hold the pthread mutex.
501 */
502 owner_ = self;
Ian Rogers0399dde2012-06-06 17:09:28 -0700503 lock_count_ = prev_lock_count;
504 locking_method_ = saved_method;
505 locking_dex_pc_ = saved_dex_pc;
Elliott Hughes5f791332011-09-15 17:45:30 -0700506 RemoveFromWaitSet(self);
507
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800508 if (was_interrupted) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700509 /*
510 * We were interrupted while waiting, or somebody interrupted an
511 * un-interruptible thread earlier and we're bailing out immediately.
512 *
513 * The doc sayeth: "The interrupted status of the current thread is
514 * cleared when this exception is thrown."
515 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700516 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700517 MutexLock mu(self, *self->wait_mutex_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700518 self->interrupted_ = false;
519 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700520 if (interruptShouldThrow) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800521 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
522 self->ThrowNewException(throw_location, "Ljava/lang/InterruptedException;", NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700523 }
524 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700525 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700526}
527
528void Monitor::Notify(Thread* self) {
529 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700530 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700531 // Make sure that we hold the lock.
532 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800533 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700534 return;
535 }
536 // Signal the first waiting thread in the wait set.
537 while (wait_set_ != NULL) {
538 Thread* thread = wait_set_;
539 wait_set_ = thread->wait_next_;
540 thread->wait_next_ = NULL;
541
542 // Check to see if the thread is still waiting.
Ian Rogers50b35e22012-10-04 10:09:15 -0700543 MutexLock mu(self, *thread->wait_mutex_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700544 if (thread->wait_monitor_ != NULL) {
Ian Rogersc604d732012-10-14 16:09:54 -0700545 thread->wait_cond_->Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700546 return;
547 }
548 }
549}
550
551void Monitor::NotifyAll(Thread* self) {
552 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700553 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700554 // Make sure that we hold the lock.
555 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800556 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700557 return;
558 }
559 // Signal all threads in the wait set.
560 while (wait_set_ != NULL) {
561 Thread* thread = wait_set_;
562 wait_set_ = thread->wait_next_;
563 thread->wait_next_ = NULL;
564 thread->Notify();
565 }
566}
567
Mathieu Chartier590fee92013-09-13 13:46:47 -0700568bool Monitor::Deflate(Thread* self, mirror::Object* obj) {
569 DCHECK(obj != nullptr);
570 LockWord lw(obj->GetLockWord());
571 // If the lock isn't an inflated monitor, then we don't need to deflate anything.
572 if (lw.GetState() == LockWord::kFatLocked) {
573 Monitor* monitor = lw.FatLockMonitor();
574 CHECK(monitor != nullptr);
575 MutexLock mu(self, monitor->monitor_lock_);
576 Thread* owner = monitor->owner_;
577 if (owner != nullptr) {
578 // Can't deflate if we are locked and have a hash code.
579 if (monitor->HasHashCode()) {
580 return false;
581 }
582 // Can't deflate if our lock count is too high.
583 if (monitor->lock_count_ > LockWord::kThinLockMaxCount) {
584 return false;
585 }
586 // Can't deflate if we have anybody waiting on the CV.
Mathieu Chartier46bc7782013-11-12 17:03:02 -0800587 if (monitor->num_waiters_ > 0) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700588 return false;
589 }
590 // Deflate to a thin lock.
591 obj->SetLockWord(LockWord::FromThinLockId(owner->GetTid(), monitor->lock_count_));
592 } else if (monitor->HasHashCode()) {
593 obj->SetLockWord(LockWord::FromHashCode(monitor->GetHashCode()));
594 } else {
595 // No lock and no hash, just put an empty lock word inside the object.
596 obj->SetLockWord(LockWord());
597 }
598 // The monitor is deflated, mark the object as nullptr so that we know to delete it during the
599 // next GC.
600 monitor->obj_ = nullptr;
601 }
602 return true;
603}
604
Elliott Hughes5f791332011-09-15 17:45:30 -0700605/*
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700606 * Changes the shape of a monitor from thin to fat, preserving the internal lock state. The calling
607 * thread must own the lock or the owner must be suspended. There's a race with other threads
608 * inflating the lock and so the caller should read the monitor following the call.
Elliott Hughes5f791332011-09-15 17:45:30 -0700609 */
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700610void Monitor::Inflate(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700611 DCHECK(self != NULL);
612 DCHECK(obj != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700613 // Allocate and acquire a new monitor.
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700614 UniquePtr<Monitor> m(new Monitor(owner, obj, hash_code));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700615 if (m->Install(self)) {
616 VLOG(monitor) << "monitor: thread " << owner->GetThreadId()
617 << " created monitor " << m.get() << " for object " << obj;
618 Runtime::Current()->GetMonitorList()->Add(m.release());
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700619 CHECK_EQ(obj->GetLockWord().GetState(), LockWord::kFatLocked);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700620 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700621}
622
Mathieu Chartier590fee92013-09-13 13:46:47 -0700623void Monitor::InflateThinLocked(Thread* self, SirtRef<mirror::Object>& obj, LockWord lock_word,
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700624 uint32_t hash_code) {
625 DCHECK_EQ(lock_word.GetState(), LockWord::kThinLocked);
626 uint32_t owner_thread_id = lock_word.ThinLockOwner();
627 if (owner_thread_id == self->GetThreadId()) {
628 // We own the monitor, we can easily inflate it.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700629 Inflate(self, self, obj.get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700630 } else {
631 ThreadList* thread_list = Runtime::Current()->GetThreadList();
632 // Suspend the owner, inflate. First change to blocked and give up mutator_lock_.
633 ScopedThreadStateChange tsc(self, kBlocked);
634 if (lock_word == obj->GetLockWord()) { // If lock word hasn't changed.
635 bool timed_out;
636 Thread* owner = thread_list->SuspendThreadByThreadId(lock_word.ThinLockOwner(), false,
637 &timed_out);
638 if (owner != nullptr) {
639 // We succeeded in suspending the thread, check the lock's status didn't change.
640 lock_word = obj->GetLockWord();
641 if (lock_word.GetState() == LockWord::kThinLocked &&
642 lock_word.ThinLockOwner() == owner_thread_id) {
643 // Go ahead and inflate the lock.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700644 Inflate(self, owner, obj.get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700645 }
646 thread_list->Resume(owner, false);
647 }
648 }
649 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700650}
651
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800652void Monitor::MonitorEnter(Thread* self, mirror::Object* obj) {
Elliott Hughes4681c802011-09-25 18:04:37 -0700653 DCHECK(self != NULL);
654 DCHECK(obj != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700655 uint32_t thread_id = self->GetThreadId();
656 size_t contention_count = 0;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700657 SirtRef<mirror::Object> sirt_obj(self, obj);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700658 while (true) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700659 LockWord lock_word = sirt_obj->GetLockWord();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700660 switch (lock_word.GetState()) {
661 case LockWord::kUnlocked: {
662 LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700663 if (sirt_obj->CasLockWord(lock_word, thin_locked)) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700664 return; // Success!
665 }
666 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -0700667 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700668 case LockWord::kThinLocked: {
669 uint32_t owner_thread_id = lock_word.ThinLockOwner();
670 if (owner_thread_id == thread_id) {
671 // We own the lock, increase the recursion count.
672 uint32_t new_count = lock_word.ThinLockCount() + 1;
673 if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
674 LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700675 sirt_obj->SetLockWord(thin_locked);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700676 return; // Success!
Elliott Hughes5f791332011-09-15 17:45:30 -0700677 } else {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700678 // We'd overflow the recursion count, so inflate the monitor.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700679 InflateThinLocked(self, sirt_obj, lock_word, 0);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700680 }
681 } else {
682 // Contention.
683 contention_count++;
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700684 Runtime* runtime = Runtime::Current();
685 if (contention_count <= runtime->GetMaxSpinsBeforeThinkLockInflation()) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700686 NanoSleep(1000); // Sleep for 1us and re-attempt.
687 } else {
688 contention_count = 0;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700689 InflateThinLocked(self, sirt_obj, lock_word, 0);
Elliott Hughes5f791332011-09-15 17:45:30 -0700690 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700691 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700692 continue; // Start from the beginning.
Elliott Hughes5f791332011-09-15 17:45:30 -0700693 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700694 case LockWord::kFatLocked: {
695 Monitor* mon = lock_word.FatLockMonitor();
696 mon->Lock(self);
697 return; // Success!
698 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700699 case LockWord::kHashCode: {
700 // Inflate with the existing hashcode.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700701 Inflate(self, nullptr, sirt_obj.get(), lock_word.GetHashCode());
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700702 break;
703 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700704 default: {
705 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
706 return;
707 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700708 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700709 }
710}
711
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800712bool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700713 DCHECK(self != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700714 DCHECK(obj != NULL);
715
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700716 LockWord lock_word = obj->GetLockWord();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700717 SirtRef<mirror::Object> sirt_obj(self, obj);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700718 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700719 case LockWord::kHashCode:
720 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700721 case LockWord::kUnlocked:
Mathieu Chartier590fee92013-09-13 13:46:47 -0700722 FailedUnlock(sirt_obj.get(), self, NULL, NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700723 return false; // Failure.
724 case LockWord::kThinLocked: {
725 uint32_t thread_id = self->GetThreadId();
726 uint32_t owner_thread_id = lock_word.ThinLockOwner();
727 if (owner_thread_id != thread_id) {
728 // TODO: there's a race here with the owner dying while we unlock.
729 Thread* owner =
730 Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700731 FailedUnlock(sirt_obj.get(), self, owner, NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700732 return false; // Failure.
733 } else {
734 // We own the lock, decrease the recursion count.
735 if (lock_word.ThinLockCount() != 0) {
736 uint32_t new_count = lock_word.ThinLockCount() - 1;
737 LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700738 sirt_obj->SetLockWord(thin_locked);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700739 } else {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700740 sirt_obj->SetLockWord(LockWord());
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700741 }
742 return true; // Success!
743 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700744 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700745 case LockWord::kFatLocked: {
746 Monitor* mon = lock_word.FatLockMonitor();
747 return mon->Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700748 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700749 default: {
750 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700751 return false;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700752 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700753 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700754}
755
756/*
757 * Object.wait(). Also called for class init.
758 */
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800759void Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800760 bool interruptShouldThrow, ThreadState why) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700761 DCHECK(self != NULL);
762 DCHECK(obj != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700763
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700764 LockWord lock_word = obj->GetLockWord();
765 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700766 case LockWord::kHashCode:
767 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700768 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800769 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700770 return; // Failure.
771 case LockWord::kThinLocked: {
772 uint32_t thread_id = self->GetThreadId();
773 uint32_t owner_thread_id = lock_word.ThinLockOwner();
774 if (owner_thread_id != thread_id) {
775 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
776 return; // Failure.
777 } else {
778 // We own the lock, inflate to enqueue ourself on the Monitor.
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700779 Inflate(self, self, obj, 0);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700780 lock_word = obj->GetLockWord();
781 }
782 break;
Elliott Hughes5f791332011-09-15 17:45:30 -0700783 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700784 case LockWord::kFatLocked:
785 break; // Already set for a wait.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700786 default: {
787 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
788 return;
789 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700790 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700791 Monitor* mon = lock_word.FatLockMonitor();
792 mon->Wait(self, ms, ns, interruptShouldThrow, why);
Elliott Hughes5f791332011-09-15 17:45:30 -0700793}
794
Ian Rogers13c479e2013-10-11 07:59:01 -0700795void Monitor::DoNotify(Thread* self, mirror::Object* obj, bool notify_all) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700796 DCHECK(self != NULL);
797 DCHECK(obj != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700798
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700799 LockWord lock_word = obj->GetLockWord();
800 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700801 case LockWord::kHashCode:
802 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700803 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800804 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700805 return; // Failure.
806 case LockWord::kThinLocked: {
807 uint32_t thread_id = self->GetThreadId();
808 uint32_t owner_thread_id = lock_word.ThinLockOwner();
809 if (owner_thread_id != thread_id) {
810 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
811 return; // Failure.
812 } else {
813 // We own the lock but there's no Monitor and therefore no waiters.
814 return; // Success.
815 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700816 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700817 case LockWord::kFatLocked: {
818 Monitor* mon = lock_word.FatLockMonitor();
819 if (notify_all) {
820 mon->NotifyAll(self);
821 } else {
822 mon->Notify(self);
823 }
824 return; // Success.
825 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700826 default: {
827 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
828 return;
829 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700830 }
831}
832
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700833uint32_t Monitor::GetLockOwnerThreadId(mirror::Object* obj) {
834 DCHECK(obj != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700835
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700836 LockWord lock_word = obj->GetLockWord();
837 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700838 case LockWord::kHashCode:
839 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700840 case LockWord::kUnlocked:
841 return ThreadList::kInvalidThreadId;
842 case LockWord::kThinLocked:
843 return lock_word.ThinLockOwner();
844 case LockWord::kFatLocked: {
845 Monitor* mon = lock_word.FatLockMonitor();
846 return mon->GetOwnerThreadId();
Elliott Hughes5f791332011-09-15 17:45:30 -0700847 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700848 default: {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700849 LOG(FATAL) << "Unreachable";
850 return ThreadList::kInvalidThreadId;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700851 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700852 }
853}
854
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700855void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800856 ThreadState state = thread->GetState();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700857
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700858 int32_t object_identity_hashcode = 0;
859 uint32_t lock_owner = ThreadList::kInvalidThreadId;
860 std::string pretty_type;
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800861 if (state == kWaiting || state == kTimedWaiting || state == kSleeping) {
862 if (state == kSleeping) {
863 os << " - sleeping on ";
864 } else {
865 os << " - waiting on ";
866 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700867 {
Elliott Hughesf9501702013-01-11 11:22:27 -0800868 Thread* self = Thread::Current();
869 MutexLock mu(self, *thread->wait_mutex_);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800870 Monitor* monitor = thread->wait_monitor_;
871 if (monitor != NULL) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700872 mirror::Object* object = monitor->obj_;
873 object_identity_hashcode = object->IdentityHashCode();
874 pretty_type = PrettyTypeOf(object);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800875 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700876 }
Elliott Hughes34e06962012-04-09 13:55:55 -0700877 } else if (state == kBlocked) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700878 os << " - waiting to lock ";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700879 mirror::Object* object = thread->monitor_enter_object_;
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700880 if (object != NULL) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700881 object_identity_hashcode = object->IdentityHashCode();
882 lock_owner = object->GetLockOwnerThreadId();
883 pretty_type = PrettyTypeOf(object);
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700884 }
885 } else {
886 // We're not waiting on anything.
887 return;
888 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700889
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700890 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700891 os << StringPrintf("<0x%08x> (a %s)", object_identity_hashcode, pretty_type.c_str());
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700892
Elliott Hughesc5dc2ff2013-01-09 13:44:30 -0800893 // - waiting to lock <0x613f83d8> (a java.lang.Object) held by thread 5
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700894 if (lock_owner != ThreadList::kInvalidThreadId) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700895 os << " held by thread " << lock_owner;
896 }
897
898 os << "\n";
899}
900
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800901mirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800902 // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
903 // definition of contended that includes a monitor a thread is trying to enter...
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800904 mirror::Object* result = thread->monitor_enter_object_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700905 if (result == NULL) {
906 // ...but also a monitor that the thread is waiting on.
Elliott Hughesf9501702013-01-11 11:22:27 -0800907 MutexLock mu(Thread::Current(), *thread->wait_mutex_);
908 Monitor* monitor = thread->wait_monitor_;
909 if (monitor != NULL) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700910 result = monitor->GetObject();
Elliott Hughesf9501702013-01-11 11:22:27 -0800911 }
912 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700913 return result;
Elliott Hughesf9501702013-01-11 11:22:27 -0800914}
915
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800916void Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
917 void* callback_context) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700918 mirror::ArtMethod* m = stack_visitor->GetMethod();
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700919 CHECK(m != NULL);
920
921 // Native methods are an easy special case.
922 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
923 if (m->IsNative()) {
924 if (m->IsSynchronized()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800925 mirror::Object* jni_this = stack_visitor->GetCurrentSirt()->GetReference(0);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800926 callback(jni_this, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700927 }
928 return;
929 }
930
jeffhao61f916c2012-10-25 17:48:51 -0700931 // Proxy methods should not be synchronized.
932 if (m->IsProxyMethod()) {
933 CHECK(!m->IsSynchronized());
934 return;
935 }
936
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700937 // <clinit> is another special case. The runtime holds the class lock while calling <clinit>.
938 MethodHelper mh(m);
939 if (mh.IsClassInitializer()) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800940 callback(m->GetDeclaringClass(), callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700941 // Fall through because there might be synchronization in the user code too.
942 }
943
944 // Is there any reason to believe there's any synchronization in this method?
945 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -0700946 CHECK(code_item != NULL) << PrettyMethod(m);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700947 if (code_item->tries_size_ == 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700948 return; // No "tries" implies no synchronization, so no held locks to report.
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700949 }
950
Elliott Hughes80537bb2013-01-04 16:37:26 -0800951 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
952 // the locks held in this stack frame.
953 std::vector<uint32_t> monitor_enter_dex_pcs;
954 verifier::MethodVerifier::FindLocksAtDexPc(m, stack_visitor->GetDexPc(), monitor_enter_dex_pcs);
955 if (monitor_enter_dex_pcs.empty()) {
956 return;
957 }
958
Elliott Hughes80537bb2013-01-04 16:37:26 -0800959 for (size_t i = 0; i < monitor_enter_dex_pcs.size(); ++i) {
960 // The verifier works in terms of the dex pcs of the monitor-enter instructions.
961 // We want the registers used by those instructions (so we can read the values out of them).
962 uint32_t dex_pc = monitor_enter_dex_pcs[i];
963 uint16_t monitor_enter_instruction = code_item->insns_[dex_pc];
964
965 // Quick sanity check.
966 if ((monitor_enter_instruction & 0xff) != Instruction::MONITOR_ENTER) {
967 LOG(FATAL) << "expected monitor-enter @" << dex_pc << "; was "
968 << reinterpret_cast<void*>(monitor_enter_instruction);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700969 }
970
Elliott Hughes80537bb2013-01-04 16:37:26 -0800971 uint16_t monitor_register = ((monitor_enter_instruction >> 8) & 0xff);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800972 mirror::Object* o = reinterpret_cast<mirror::Object*>(stack_visitor->GetVReg(m, monitor_register,
973 kReferenceVReg));
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800974 callback(o, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700975 }
976}
977
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700978bool Monitor::IsValidLockWord(LockWord lock_word) {
979 switch (lock_word.GetState()) {
980 case LockWord::kUnlocked:
981 // Nothing to check.
982 return true;
983 case LockWord::kThinLocked:
984 // Basic sanity check of owner.
985 return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
986 case LockWord::kFatLocked: {
987 // Check the monitor appears in the monitor list.
988 Monitor* mon = lock_word.FatLockMonitor();
989 MonitorList* list = Runtime::Current()->GetMonitorList();
990 MutexLock mu(Thread::Current(), list->monitor_list_lock_);
991 for (Monitor* list_mon : list->list_) {
992 if (mon == list_mon) {
993 return true; // Found our monitor.
994 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700995 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700996 return false; // Fail - unowned monitor in an object.
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700997 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700998 case LockWord::kHashCode:
999 return true;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001000 default:
1001 LOG(FATAL) << "Unreachable";
1002 return false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001003 }
1004}
1005
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001006bool Monitor::IsLocked() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1007 MutexLock mu(Thread::Current(), monitor_lock_);
1008 return owner_ != nullptr;
1009}
1010
Brian Carlstromea46f952013-07-30 01:26:50 -07001011void Monitor::TranslateLocation(const mirror::ArtMethod* method, uint32_t dex_pc,
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001012 const char** source_file, uint32_t* line_number) const {
jeffhao33dc7712011-11-09 17:54:24 -08001013 // If method is null, location is unknown
1014 if (method == NULL) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001015 *source_file = "";
1016 *line_number = 0;
jeffhao33dc7712011-11-09 17:54:24 -08001017 return;
1018 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001019 MethodHelper mh(method);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001020 *source_file = mh.GetDeclaringClassSourceFile();
1021 if (*source_file == NULL) {
1022 *source_file = "";
Elliott Hughes12c51e32012-01-17 20:25:05 -08001023 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001024 *line_number = mh.GetLineNumFromDexPC(dex_pc);
1025}
1026
1027uint32_t Monitor::GetOwnerThreadId() {
1028 MutexLock mu(Thread::Current(), monitor_lock_);
1029 Thread* owner = owner_;
1030 if (owner != NULL) {
1031 return owner->GetThreadId();
1032 } else {
1033 return ThreadList::kInvalidThreadId;
1034 }
jeffhao33dc7712011-11-09 17:54:24 -08001035}
1036
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001037MonitorList::MonitorList()
1038 : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock"),
1039 monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001040}
1041
1042MonitorList::~MonitorList() {
Ian Rogers50b35e22012-10-04 10:09:15 -07001043 MutexLock mu(Thread::Current(), monitor_list_lock_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001044 STLDeleteElements(&list_);
1045}
1046
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001047void MonitorList::DisallowNewMonitors() {
Ian Rogers50b35e22012-10-04 10:09:15 -07001048 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001049 allow_new_monitors_ = false;
1050}
1051
1052void MonitorList::AllowNewMonitors() {
1053 Thread* self = Thread::Current();
1054 MutexLock mu(self, monitor_list_lock_);
1055 allow_new_monitors_ = true;
1056 monitor_add_condition_.Broadcast(self);
1057}
1058
1059void MonitorList::Add(Monitor* m) {
1060 Thread* self = Thread::Current();
1061 MutexLock mu(self, monitor_list_lock_);
1062 while (UNLIKELY(!allow_new_monitors_)) {
1063 monitor_add_condition_.WaitHoldingLocks(self);
1064 }
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001065 list_.push_front(m);
1066}
1067
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001068void MonitorList::SweepMonitorList(RootVisitor visitor, void* arg) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001069 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001070 for (auto it = list_.begin(); it != list_.end(); ) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001071 Monitor* m = *it;
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001072 mirror::Object* obj = m->GetObject();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001073 // The object of a monitor can be null if we have deflated it.
1074 mirror::Object* new_obj = obj != nullptr ? visitor(obj, arg) : nullptr;
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001075 if (new_obj == nullptr) {
1076 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
1077 << m->GetObject();
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001078 delete m;
1079 it = list_.erase(it);
1080 } else {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001081 m->SetObject(new_obj);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001082 ++it;
1083 }
1084 }
1085}
1086
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001087MonitorInfo::MonitorInfo(mirror::Object* obj) : owner_(NULL), entry_count_(0) {
1088 DCHECK(obj != NULL);
1089
1090 LockWord lock_word = obj->GetLockWord();
1091 switch (lock_word.GetState()) {
1092 case LockWord::kUnlocked:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001093 // Fall-through.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001094 case LockWord::kForwardingAddress:
1095 // Fall-through.
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001096 case LockWord::kHashCode:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001097 break;
1098 case LockWord::kThinLocked:
1099 owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
1100 entry_count_ = 1 + lock_word.ThinLockCount();
1101 // Thin locks have no waiters.
1102 break;
1103 case LockWord::kFatLocked: {
1104 Monitor* mon = lock_word.FatLockMonitor();
1105 owner_ = mon->owner_;
1106 entry_count_ = 1 + mon->lock_count_;
1107 for (Thread* waiter = mon->wait_set_; waiter != NULL; waiter = waiter->wait_next_) {
1108 waiters_.push_back(waiter);
1109 }
1110 break;
Elliott Hughesf327e072013-01-09 16:01:26 -08001111 }
1112 }
1113}
1114
Elliott Hughes5f791332011-09-15 17:45:30 -07001115} // namespace art