blob: 7fada9ef81a6fa0c7fd363aba8722410978f692d [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_),
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
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -070098int32_t Monitor::GetHashCode() {
99 while (!HasHashCode()) {
100 if (hash_code_.compare_and_swap(0, mirror::Object::GenerateIdentityHashCode())) {
101 break;
102 }
103 }
104 DCHECK(HasHashCode());
105 return hash_code_.load();
106}
107
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700108bool Monitor::Install(Thread* self) {
109 MutexLock mu(self, monitor_lock_); // Uncontended mutex acquisition as monitor isn't yet public.
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700110 CHECK(owner_ == nullptr || owner_ == self || owner_->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700111 // Propagate the lock state.
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700112 LockWord lw(obj_->GetLockWord());
113 switch (lw.GetState()) {
114 case LockWord::kThinLocked: {
115 CHECK_EQ(owner_->GetThreadId(), lw.ThinLockOwner());
116 lock_count_ = lw.ThinLockCount();
117 break;
118 }
119 case LockWord::kHashCode: {
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700120 CHECK_EQ(hash_code_, static_cast<int32_t>(lw.GetHashCode()));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700121 break;
122 }
123 case LockWord::kFatLocked: {
124 // The owner_ is suspended but another thread beat us to install a monitor.
125 return false;
126 }
127 case LockWord::kUnlocked: {
128 LOG(FATAL) << "Inflating unlocked lock word";
129 break;
130 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700131 default: {
132 LOG(FATAL) << "Invalid monitor state " << lw.GetState();
133 return false;
134 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700135 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700136 LockWord fat(this);
137 // Publish the updated lock word, which may race with other threads.
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700138 bool success = obj_->CasLockWord(lw, fat);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700139 // Lock profiling.
Mathieu Chartier9728f912013-10-30 09:45:13 -0700140 if (success && owner_ != nullptr && lock_profiling_threshold_ != 0) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700141 locking_method_ = owner_->GetCurrentMethod(&locking_dex_pc_);
142 }
143 return success;
Elliott Hughes5f791332011-09-15 17:45:30 -0700144}
145
146Monitor::~Monitor() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700147 // Deflated monitors have a null object.
Elliott Hughes5f791332011-09-15 17:45:30 -0700148}
149
150/*
151 * Links a thread into a monitor's wait set. The monitor lock must be
152 * held by the caller of this routine.
153 */
154void Monitor::AppendToWaitSet(Thread* thread) {
155 DCHECK(owner_ == Thread::Current());
156 DCHECK(thread != NULL);
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700157 DCHECK(thread->wait_next_ == NULL) << thread->wait_next_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700158 if (wait_set_ == NULL) {
159 wait_set_ = thread;
160 return;
161 }
162
163 // push_back.
164 Thread* t = wait_set_;
165 while (t->wait_next_ != NULL) {
166 t = t->wait_next_;
167 }
168 t->wait_next_ = thread;
169}
170
171/*
172 * Unlinks a thread from a monitor's wait set. The monitor lock must
173 * be held by the caller of this routine.
174 */
175void Monitor::RemoveFromWaitSet(Thread *thread) {
176 DCHECK(owner_ == Thread::Current());
177 DCHECK(thread != NULL);
178 if (wait_set_ == NULL) {
179 return;
180 }
181 if (wait_set_ == thread) {
182 wait_set_ = thread->wait_next_;
183 thread->wait_next_ = NULL;
184 return;
185 }
186
187 Thread* t = wait_set_;
188 while (t->wait_next_ != NULL) {
189 if (t->wait_next_ == thread) {
190 t->wait_next_ = thread->wait_next_;
191 thread->wait_next_ = NULL;
192 return;
193 }
194 t = t->wait_next_;
195 }
196}
197
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700198void Monitor::SetObject(mirror::Object* object) {
199 obj_ = object;
200}
201
Elliott Hughes5f791332011-09-15 17:45:30 -0700202void Monitor::Lock(Thread* self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700203 MutexLock mu(self, monitor_lock_);
204 while (true) {
205 if (owner_ == NULL) { // Unowned.
206 owner_ = self;
207 CHECK_EQ(lock_count_, 0);
208 // When debugging, save the current monitor holder for future
209 // acquisition failures to use in sampled logging.
210 if (lock_profiling_threshold_ != 0) {
211 locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
212 }
213 return;
214 } else if (owner_ == self) { // Recursive.
215 lock_count_++;
216 return;
217 }
218 // Contended.
219 const bool log_contention = (lock_profiling_threshold_ != 0);
220 uint64_t wait_start_ms = log_contention ? 0 : MilliTime();
221 const mirror::ArtMethod* owners_method = locking_method_;
222 uint32_t owners_dex_pc = locking_dex_pc_;
223 monitor_lock_.Unlock(self); // Let go of locks in order.
Elliott Hughes5f791332011-09-15 17:45:30 -0700224 {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700225 ScopedThreadStateChange tsc(self, kBlocked); // Change to blocked and give up mutator_lock_.
226 MutexLock mu2(self, monitor_lock_); // Reacquire monitor_lock_ without mutator_lock_ for Wait.
227 if (owner_ != NULL) { // Did the owner_ give the lock up?
228 monitor_contenders_.Wait(self); // Still contended so wait.
229 // Woken from contention.
230 if (log_contention) {
231 uint64_t wait_ms = MilliTime() - wait_start_ms;
232 uint32_t sample_percent;
233 if (wait_ms >= lock_profiling_threshold_) {
234 sample_percent = 100;
235 } else {
236 sample_percent = 100 * wait_ms / lock_profiling_threshold_;
237 }
238 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
239 const char* owners_filename;
240 uint32_t owners_line_number;
241 TranslateLocation(owners_method, owners_dex_pc, &owners_filename, &owners_line_number);
242 LogContentionEvent(self, wait_ms, sample_percent, owners_filename, owners_line_number);
243 }
244 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700245 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700246 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700247 monitor_lock_.Lock(self); // Reacquire locks in order.
Elliott Hughesfc861622011-10-17 17:57:47 -0700248 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700249}
250
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800251static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
252 __attribute__((format(printf, 1, 2)));
253
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700254static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700255 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800256 va_list args;
257 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800258 Thread* self = Thread::Current();
259 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
260 self->ThrowNewExceptionV(throw_location, "Ljava/lang/IllegalMonitorStateException;", fmt, args);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700261 if (!Runtime::Current()->IsStarted() || VLOG_IS_ON(monitor)) {
Brian Carlstrom64277f32012-03-26 23:53:34 -0700262 std::ostringstream ss;
Ian Rogers62d6c772013-02-27 08:32:07 -0800263 self->Dump(ss);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700264 LOG(Runtime::Current()->IsStarted() ? INFO : ERROR)
265 << self->GetException(NULL)->Dump() << "\n" << ss.str();
Brian Carlstrom64277f32012-03-26 23:53:34 -0700266 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800267 va_end(args);
268}
269
Elliott Hughesd4237412012-02-21 11:24:45 -0800270static std::string ThreadToString(Thread* thread) {
271 if (thread == NULL) {
272 return "NULL";
273 }
274 std::ostringstream oss;
275 // TODO: alternatively, we could just return the thread's name.
276 oss << *thread;
277 return oss.str();
278}
279
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800280void Monitor::FailedUnlock(mirror::Object* o, Thread* expected_owner, Thread* found_owner,
Elliott Hughesffb465f2012-03-01 18:46:05 -0800281 Monitor* monitor) {
282 Thread* current_owner = NULL;
283 std::string current_owner_string;
284 std::string expected_owner_string;
285 std::string found_owner_string;
286 {
287 // TODO: isn't this too late to prevent threads from disappearing?
288 // Acquire thread list lock so threads won't disappear from under us.
Ian Rogers50b35e22012-10-04 10:09:15 -0700289 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Elliott Hughesffb465f2012-03-01 18:46:05 -0800290 // Re-read owner now that we hold lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700291 current_owner = (monitor != NULL) ? monitor->GetOwner() : NULL;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800292 // Get short descriptions of the threads involved.
293 current_owner_string = ThreadToString(current_owner);
294 expected_owner_string = ThreadToString(expected_owner);
295 found_owner_string = ThreadToString(found_owner);
296 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800297 if (current_owner == NULL) {
298 if (found_owner == NULL) {
299 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
300 " on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800301 PrettyTypeOf(o).c_str(),
302 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800303 } else {
304 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800305 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
306 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800307 found_owner_string.c_str(),
308 PrettyTypeOf(o).c_str(),
309 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800310 }
311 } else {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800312 if (found_owner == NULL) {
313 // Race: originally there was no owner, there is now
314 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
315 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800316 current_owner_string.c_str(),
317 PrettyTypeOf(o).c_str(),
318 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800319 } else {
320 if (found_owner != current_owner) {
321 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800322 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
323 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800324 found_owner_string.c_str(),
325 current_owner_string.c_str(),
326 PrettyTypeOf(o).c_str(),
327 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800328 } else {
329 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
330 " on thread '%s",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800331 current_owner_string.c_str(),
332 PrettyTypeOf(o).c_str(),
333 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800334 }
335 }
336 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700337}
338
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700339bool Monitor::Unlock(Thread* self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700340 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700341 MutexLock mu(self, monitor_lock_);
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800342 Thread* owner = owner_;
343 if (owner == self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700344 // We own the monitor, so nobody else can be in here.
345 if (lock_count_ == 0) {
346 owner_ = NULL;
jeffhao33dc7712011-11-09 17:54:24 -0800347 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700348 locking_dex_pc_ = 0;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700349 // Wake a contender.
350 monitor_contenders_.Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700351 } else {
352 --lock_count_;
353 }
354 } else {
355 // We don't own this, so we're not allowed to unlock it.
356 // The JNI spec says that we should throw IllegalMonitorStateException
357 // in this case.
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800358 FailedUnlock(obj_, self, owner, this);
Elliott Hughes5f791332011-09-15 17:45:30 -0700359 return false;
360 }
361 return true;
362}
363
Elliott Hughes5f791332011-09-15 17:45:30 -0700364/*
365 * Wait on a monitor until timeout, interrupt, or notification. Used for
366 * Object.wait() and (somewhat indirectly) Thread.sleep() and Thread.join().
367 *
368 * If another thread calls Thread.interrupt(), we throw InterruptedException
369 * and return immediately if one of the following are true:
370 * - blocked in wait(), wait(long), or wait(long, int) methods of Object
371 * - blocked in join(), join(long), or join(long, int) methods of Thread
372 * - blocked in sleep(long), or sleep(long, int) methods of Thread
373 * Otherwise, we set the "interrupted" flag.
374 *
375 * Checks to make sure that "ns" is in the range 0-999999
376 * (i.e. fractions of a millisecond) and throws the appropriate
377 * exception if it isn't.
378 *
379 * The spec allows "spurious wakeups", and recommends that all code using
380 * Object.wait() do so in a loop. This appears to derive from concerns
381 * about pthread_cond_wait() on multiprocessor systems. Some commentary
382 * on the web casts doubt on whether these can/should occur.
383 *
384 * Since we're allowed to wake up "early", we clamp extremely long durations
385 * to return at the end of the 32-bit time epoch.
386 */
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800387void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
388 bool interruptShouldThrow, ThreadState why) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700389 DCHECK(self != NULL);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800390 DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
Elliott Hughes5f791332011-09-15 17:45:30 -0700391
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700392 monitor_lock_.Lock(self);
393
Elliott Hughes5f791332011-09-15 17:45:30 -0700394 // Make sure that we hold the lock.
395 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800396 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700397 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700398 return;
399 }
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800400
Elliott Hughesdf42c482013-01-09 12:49:02 -0800401 // We need to turn a zero-length timed wait into a regular wait because
402 // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
403 if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
404 why = kWaiting;
405 }
406
Elliott Hughes5f791332011-09-15 17:45:30 -0700407 // Enforce the timeout range.
408 if (ms < 0 || ns < 0 || ns > 999999) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800409 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
410 self->ThrowNewExceptionF(throw_location, "Ljava/lang/IllegalArgumentException;",
411 "timeout arguments out of range: ms=%lld ns=%d", ms, ns);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700412 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700413 return;
414 }
415
Elliott Hughes5f791332011-09-15 17:45:30 -0700416 /*
417 * Add ourselves to the set of threads waiting on this monitor, and
418 * release our hold. We need to let it go even if we're a few levels
419 * deep in a recursive lock, and we need to restore that later.
420 *
421 * We append to the wait set ahead of clearing the count and owner
422 * fields so the subroutine can check that the calling thread owns
423 * the monitor. Aside from that, the order of member updates is
424 * not order sensitive as we hold the pthread mutex.
425 */
426 AppendToWaitSet(self);
Ian Rogers0399dde2012-06-06 17:09:28 -0700427 int prev_lock_count = lock_count_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700428 lock_count_ = 0;
429 owner_ = NULL;
Brian Carlstromea46f952013-07-30 01:26:50 -0700430 const mirror::ArtMethod* saved_method = locking_method_;
jeffhao33dc7712011-11-09 17:54:24 -0800431 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700432 uintptr_t saved_dex_pc = locking_dex_pc_;
433 locking_dex_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700434
435 /*
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800436 * Update thread state. If the GC wakes up, it'll ignore us, knowing
Elliott Hughes5f791332011-09-15 17:45:30 -0700437 * that we won't touch any references in this state, and we'll check
438 * our suspend mode before we transition out.
439 */
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800440 self->TransitionFromRunnableToSuspended(why);
Elliott Hughes5f791332011-09-15 17:45:30 -0700441
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800442 bool was_interrupted = false;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700443 {
444 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
Ian Rogers50b35e22012-10-04 10:09:15 -0700445 MutexLock mu(self, *self->wait_mutex_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700446
447 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
448 // non-NULL a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
449 // up.
450 DCHECK(self->wait_monitor_ == NULL);
451 self->wait_monitor_ = this;
452
453 // Release the monitor lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700454 monitor_contenders_.Signal(self);
455 monitor_lock_.Unlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700456
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800457 // Handle the case where the thread was interrupted before we called wait().
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700458 if (self->interrupted_) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800459 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700460 } else {
461 // Wait for a notification or a timeout to occur.
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800462 if (why == kWaiting) {
Ian Rogersc604d732012-10-14 16:09:54 -0700463 self->wait_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700464 } else {
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800465 DCHECK(why == kTimedWaiting || why == kSleeping) << why;
Ian Rogersc604d732012-10-14 16:09:54 -0700466 self->wait_cond_->TimedWait(self, ms, ns);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700467 }
468 if (self->interrupted_) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800469 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700470 }
471 self->interrupted_ = false;
472 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700473 }
474
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700475 // Set self->status back to kRunnable, and self-suspend if needed.
476 self->TransitionFromSuspendedToRunnable();
Elliott Hughes5f791332011-09-15 17:45:30 -0700477
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800478 {
479 // We reset the thread's wait_monitor_ field after transitioning back to runnable so
480 // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
481 // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
482 // are waiting on "null".)
483 MutexLock mu(self, *self->wait_mutex_);
484 DCHECK(self->wait_monitor_ != NULL);
485 self->wait_monitor_ = NULL;
486 }
487
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700488 // Re-acquire the monitor and lock.
Elliott Hughes5f791332011-09-15 17:45:30 -0700489 Lock(self);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700490 monitor_lock_.Lock(self);
Ian Rogers81d425b2012-09-27 16:03:43 -0700491 self->wait_mutex_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700492
Elliott Hughes5f791332011-09-15 17:45:30 -0700493 /*
494 * We remove our thread from wait set after restoring the count
495 * and owner fields so the subroutine can check that the calling
496 * thread owns the monitor. Aside from that, the order of member
497 * updates is not order sensitive as we hold the pthread mutex.
498 */
499 owner_ = self;
Ian Rogers0399dde2012-06-06 17:09:28 -0700500 lock_count_ = prev_lock_count;
501 locking_method_ = saved_method;
502 locking_dex_pc_ = saved_dex_pc;
Elliott Hughes5f791332011-09-15 17:45:30 -0700503 RemoveFromWaitSet(self);
504
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800505 if (was_interrupted) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700506 /*
507 * We were interrupted while waiting, or somebody interrupted an
508 * un-interruptible thread earlier and we're bailing out immediately.
509 *
510 * The doc sayeth: "The interrupted status of the current thread is
511 * cleared when this exception is thrown."
512 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700513 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700514 MutexLock mu(self, *self->wait_mutex_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700515 self->interrupted_ = false;
516 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700517 if (interruptShouldThrow) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800518 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
519 self->ThrowNewException(throw_location, "Ljava/lang/InterruptedException;", NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700520 }
521 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700522 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700523}
524
525void Monitor::Notify(Thread* self) {
526 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700527 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700528 // Make sure that we hold the lock.
529 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800530 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700531 return;
532 }
533 // Signal the first waiting thread in the wait set.
534 while (wait_set_ != NULL) {
535 Thread* thread = wait_set_;
536 wait_set_ = thread->wait_next_;
537 thread->wait_next_ = NULL;
538
539 // Check to see if the thread is still waiting.
Ian Rogers50b35e22012-10-04 10:09:15 -0700540 MutexLock mu(self, *thread->wait_mutex_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700541 if (thread->wait_monitor_ != NULL) {
Ian Rogersc604d732012-10-14 16:09:54 -0700542 thread->wait_cond_->Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700543 return;
544 }
545 }
546}
547
548void Monitor::NotifyAll(Thread* self) {
549 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700550 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700551 // Make sure that we hold the lock.
552 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800553 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700554 return;
555 }
556 // Signal all threads in the wait set.
557 while (wait_set_ != NULL) {
558 Thread* thread = wait_set_;
559 wait_set_ = thread->wait_next_;
560 thread->wait_next_ = NULL;
561 thread->Notify();
562 }
563}
564
Mathieu Chartier590fee92013-09-13 13:46:47 -0700565bool Monitor::Deflate(Thread* self, mirror::Object* obj) {
566 DCHECK(obj != nullptr);
567 LockWord lw(obj->GetLockWord());
568 // If the lock isn't an inflated monitor, then we don't need to deflate anything.
569 if (lw.GetState() == LockWord::kFatLocked) {
570 Monitor* monitor = lw.FatLockMonitor();
571 CHECK(monitor != nullptr);
572 MutexLock mu(self, monitor->monitor_lock_);
573 Thread* owner = monitor->owner_;
574 if (owner != nullptr) {
575 // Can't deflate if we are locked and have a hash code.
576 if (monitor->HasHashCode()) {
577 return false;
578 }
579 // Can't deflate if our lock count is too high.
580 if (monitor->lock_count_ > LockWord::kThinLockMaxCount) {
581 return false;
582 }
583 // Can't deflate if we have anybody waiting on the CV.
584 if (monitor->monitor_contenders_.GetNumWaiters() > 0) {
585 return false;
586 }
587 // Deflate to a thin lock.
588 obj->SetLockWord(LockWord::FromThinLockId(owner->GetTid(), monitor->lock_count_));
589 } else if (monitor->HasHashCode()) {
590 obj->SetLockWord(LockWord::FromHashCode(monitor->GetHashCode()));
591 } else {
592 // No lock and no hash, just put an empty lock word inside the object.
593 obj->SetLockWord(LockWord());
594 }
595 // The monitor is deflated, mark the object as nullptr so that we know to delete it during the
596 // next GC.
597 monitor->obj_ = nullptr;
598 }
599 return true;
600}
601
Elliott Hughes5f791332011-09-15 17:45:30 -0700602/*
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700603 * Changes the shape of a monitor from thin to fat, preserving the internal lock state. The calling
604 * thread must own the lock or the owner must be suspended. There's a race with other threads
605 * inflating the lock and so the caller should read the monitor following the call.
Elliott Hughes5f791332011-09-15 17:45:30 -0700606 */
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700607void Monitor::Inflate(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700608 DCHECK(self != NULL);
609 DCHECK(obj != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700610 // Allocate and acquire a new monitor.
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700611 UniquePtr<Monitor> m(new Monitor(owner, obj, hash_code));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700612 if (m->Install(self)) {
613 VLOG(monitor) << "monitor: thread " << owner->GetThreadId()
614 << " created monitor " << m.get() << " for object " << obj;
615 Runtime::Current()->GetMonitorList()->Add(m.release());
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700616 CHECK_EQ(obj->GetLockWord().GetState(), LockWord::kFatLocked);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700617 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700618}
619
Mathieu Chartier590fee92013-09-13 13:46:47 -0700620void Monitor::InflateThinLocked(Thread* self, SirtRef<mirror::Object>& obj, LockWord lock_word,
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700621 uint32_t hash_code) {
622 DCHECK_EQ(lock_word.GetState(), LockWord::kThinLocked);
623 uint32_t owner_thread_id = lock_word.ThinLockOwner();
624 if (owner_thread_id == self->GetThreadId()) {
625 // We own the monitor, we can easily inflate it.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700626 Inflate(self, self, obj.get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700627 } else {
628 ThreadList* thread_list = Runtime::Current()->GetThreadList();
629 // Suspend the owner, inflate. First change to blocked and give up mutator_lock_.
630 ScopedThreadStateChange tsc(self, kBlocked);
631 if (lock_word == obj->GetLockWord()) { // If lock word hasn't changed.
632 bool timed_out;
633 Thread* owner = thread_list->SuspendThreadByThreadId(lock_word.ThinLockOwner(), false,
634 &timed_out);
635 if (owner != nullptr) {
636 // We succeeded in suspending the thread, check the lock's status didn't change.
637 lock_word = obj->GetLockWord();
638 if (lock_word.GetState() == LockWord::kThinLocked &&
639 lock_word.ThinLockOwner() == owner_thread_id) {
640 // Go ahead and inflate the lock.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700641 Inflate(self, owner, obj.get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700642 }
643 thread_list->Resume(owner, false);
644 }
645 }
646 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700647}
648
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800649void Monitor::MonitorEnter(Thread* self, mirror::Object* obj) {
Elliott Hughes4681c802011-09-25 18:04:37 -0700650 DCHECK(self != NULL);
651 DCHECK(obj != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700652 uint32_t thread_id = self->GetThreadId();
653 size_t contention_count = 0;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700654 SirtRef<mirror::Object> sirt_obj(self, obj);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700655 while (true) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700656 LockWord lock_word = sirt_obj->GetLockWord();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700657 switch (lock_word.GetState()) {
658 case LockWord::kUnlocked: {
659 LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700660 if (sirt_obj->CasLockWord(lock_word, thin_locked)) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700661 return; // Success!
662 }
663 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -0700664 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700665 case LockWord::kThinLocked: {
666 uint32_t owner_thread_id = lock_word.ThinLockOwner();
667 if (owner_thread_id == thread_id) {
668 // We own the lock, increase the recursion count.
669 uint32_t new_count = lock_word.ThinLockCount() + 1;
670 if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
671 LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700672 sirt_obj->SetLockWord(thin_locked);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700673 return; // Success!
Elliott Hughes5f791332011-09-15 17:45:30 -0700674 } else {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700675 // We'd overflow the recursion count, so inflate the monitor.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700676 InflateThinLocked(self, sirt_obj, lock_word, 0);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700677 }
678 } else {
679 // Contention.
680 contention_count++;
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700681 Runtime* runtime = Runtime::Current();
682 if (contention_count <= runtime->GetMaxSpinsBeforeThinkLockInflation()) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700683 NanoSleep(1000); // Sleep for 1us and re-attempt.
684 } else {
685 contention_count = 0;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700686 InflateThinLocked(self, sirt_obj, lock_word, 0);
Elliott Hughes5f791332011-09-15 17:45:30 -0700687 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700688 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700689 continue; // Start from the beginning.
Elliott Hughes5f791332011-09-15 17:45:30 -0700690 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700691 case LockWord::kFatLocked: {
692 Monitor* mon = lock_word.FatLockMonitor();
693 mon->Lock(self);
694 return; // Success!
695 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700696 case LockWord::kHashCode: {
697 // Inflate with the existing hashcode.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700698 Inflate(self, nullptr, sirt_obj.get(), lock_word.GetHashCode());
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700699 break;
700 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700701 default: {
702 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
703 return;
704 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700705 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700706 }
707}
708
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800709bool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700710 DCHECK(self != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700711 DCHECK(obj != NULL);
712
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700713 LockWord lock_word = obj->GetLockWord();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700714 SirtRef<mirror::Object> sirt_obj(self, obj);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700715 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700716 case LockWord::kHashCode:
717 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700718 case LockWord::kUnlocked:
Mathieu Chartier590fee92013-09-13 13:46:47 -0700719 FailedUnlock(sirt_obj.get(), self, NULL, NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700720 return false; // Failure.
721 case LockWord::kThinLocked: {
722 uint32_t thread_id = self->GetThreadId();
723 uint32_t owner_thread_id = lock_word.ThinLockOwner();
724 if (owner_thread_id != thread_id) {
725 // TODO: there's a race here with the owner dying while we unlock.
726 Thread* owner =
727 Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700728 FailedUnlock(sirt_obj.get(), self, owner, NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700729 return false; // Failure.
730 } else {
731 // We own the lock, decrease the recursion count.
732 if (lock_word.ThinLockCount() != 0) {
733 uint32_t new_count = lock_word.ThinLockCount() - 1;
734 LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700735 sirt_obj->SetLockWord(thin_locked);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700736 } else {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700737 sirt_obj->SetLockWord(LockWord());
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700738 }
739 return true; // Success!
740 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700741 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700742 case LockWord::kFatLocked: {
743 Monitor* mon = lock_word.FatLockMonitor();
744 return mon->Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700745 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700746 default: {
747 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700748 return false;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700749 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700750 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700751}
752
753/*
754 * Object.wait(). Also called for class init.
755 */
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800756void Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800757 bool interruptShouldThrow, ThreadState why) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700758 DCHECK(self != NULL);
759 DCHECK(obj != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700760
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700761 LockWord lock_word = obj->GetLockWord();
762 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700763 case LockWord::kHashCode:
764 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700765 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800766 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700767 return; // Failure.
768 case LockWord::kThinLocked: {
769 uint32_t thread_id = self->GetThreadId();
770 uint32_t owner_thread_id = lock_word.ThinLockOwner();
771 if (owner_thread_id != thread_id) {
772 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
773 return; // Failure.
774 } else {
775 // We own the lock, inflate to enqueue ourself on the Monitor.
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700776 Inflate(self, self, obj, 0);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700777 lock_word = obj->GetLockWord();
778 }
779 break;
Elliott Hughes5f791332011-09-15 17:45:30 -0700780 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700781 case LockWord::kFatLocked:
782 break; // Already set for a wait.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700783 default: {
784 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
785 return;
786 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700787 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700788 Monitor* mon = lock_word.FatLockMonitor();
789 mon->Wait(self, ms, ns, interruptShouldThrow, why);
Elliott Hughes5f791332011-09-15 17:45:30 -0700790}
791
Ian Rogers13c479e2013-10-11 07:59:01 -0700792void Monitor::DoNotify(Thread* self, mirror::Object* obj, bool notify_all) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700793 DCHECK(self != NULL);
794 DCHECK(obj != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700795
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700796 LockWord lock_word = obj->GetLockWord();
797 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700798 case LockWord::kHashCode:
799 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700800 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800801 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700802 return; // Failure.
803 case LockWord::kThinLocked: {
804 uint32_t thread_id = self->GetThreadId();
805 uint32_t owner_thread_id = lock_word.ThinLockOwner();
806 if (owner_thread_id != thread_id) {
807 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
808 return; // Failure.
809 } else {
810 // We own the lock but there's no Monitor and therefore no waiters.
811 return; // Success.
812 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700813 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700814 case LockWord::kFatLocked: {
815 Monitor* mon = lock_word.FatLockMonitor();
816 if (notify_all) {
817 mon->NotifyAll(self);
818 } else {
819 mon->Notify(self);
820 }
821 return; // Success.
822 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700823 default: {
824 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
825 return;
826 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700827 }
828}
829
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700830uint32_t Monitor::GetLockOwnerThreadId(mirror::Object* obj) {
831 DCHECK(obj != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700832
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700833 LockWord lock_word = obj->GetLockWord();
834 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700835 case LockWord::kHashCode:
836 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700837 case LockWord::kUnlocked:
838 return ThreadList::kInvalidThreadId;
839 case LockWord::kThinLocked:
840 return lock_word.ThinLockOwner();
841 case LockWord::kFatLocked: {
842 Monitor* mon = lock_word.FatLockMonitor();
843 return mon->GetOwnerThreadId();
Elliott Hughes5f791332011-09-15 17:45:30 -0700844 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700845 default: {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700846 LOG(FATAL) << "Unreachable";
847 return ThreadList::kInvalidThreadId;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700848 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700849 }
850}
851
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700852void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800853 ThreadState state = thread->GetState();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700854
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700855 int32_t object_identity_hashcode = 0;
856 uint32_t lock_owner = ThreadList::kInvalidThreadId;
857 std::string pretty_type;
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800858 if (state == kWaiting || state == kTimedWaiting || state == kSleeping) {
859 if (state == kSleeping) {
860 os << " - sleeping on ";
861 } else {
862 os << " - waiting on ";
863 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700864 {
Elliott Hughesf9501702013-01-11 11:22:27 -0800865 Thread* self = Thread::Current();
866 MutexLock mu(self, *thread->wait_mutex_);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800867 Monitor* monitor = thread->wait_monitor_;
868 if (monitor != NULL) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700869 mirror::Object* object = monitor->obj_;
870 object_identity_hashcode = object->IdentityHashCode();
871 pretty_type = PrettyTypeOf(object);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800872 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700873 }
Elliott Hughes34e06962012-04-09 13:55:55 -0700874 } else if (state == kBlocked) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700875 os << " - waiting to lock ";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700876 mirror::Object* object = thread->monitor_enter_object_;
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700877 if (object != NULL) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700878 object_identity_hashcode = object->IdentityHashCode();
879 lock_owner = object->GetLockOwnerThreadId();
880 pretty_type = PrettyTypeOf(object);
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700881 }
882 } else {
883 // We're not waiting on anything.
884 return;
885 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700886
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700887 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700888 os << StringPrintf("<0x%08x> (a %s)", object_identity_hashcode, pretty_type.c_str());
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700889
Elliott Hughesc5dc2ff2013-01-09 13:44:30 -0800890 // - waiting to lock <0x613f83d8> (a java.lang.Object) held by thread 5
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700891 if (lock_owner != ThreadList::kInvalidThreadId) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700892 os << " held by thread " << lock_owner;
893 }
894
895 os << "\n";
896}
897
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800898mirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800899 // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
900 // definition of contended that includes a monitor a thread is trying to enter...
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800901 mirror::Object* result = thread->monitor_enter_object_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700902 if (result == NULL) {
903 // ...but also a monitor that the thread is waiting on.
Elliott Hughesf9501702013-01-11 11:22:27 -0800904 MutexLock mu(Thread::Current(), *thread->wait_mutex_);
905 Monitor* monitor = thread->wait_monitor_;
906 if (monitor != NULL) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700907 result = monitor->GetObject();
Elliott Hughesf9501702013-01-11 11:22:27 -0800908 }
909 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700910 return result;
Elliott Hughesf9501702013-01-11 11:22:27 -0800911}
912
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800913void Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
914 void* callback_context) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700915 mirror::ArtMethod* m = stack_visitor->GetMethod();
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700916 CHECK(m != NULL);
917
918 // Native methods are an easy special case.
919 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
920 if (m->IsNative()) {
921 if (m->IsSynchronized()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800922 mirror::Object* jni_this = stack_visitor->GetCurrentSirt()->GetReference(0);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800923 callback(jni_this, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700924 }
925 return;
926 }
927
jeffhao61f916c2012-10-25 17:48:51 -0700928 // Proxy methods should not be synchronized.
929 if (m->IsProxyMethod()) {
930 CHECK(!m->IsSynchronized());
931 return;
932 }
933
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700934 // <clinit> is another special case. The runtime holds the class lock while calling <clinit>.
935 MethodHelper mh(m);
936 if (mh.IsClassInitializer()) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800937 callback(m->GetDeclaringClass(), callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700938 // Fall through because there might be synchronization in the user code too.
939 }
940
941 // Is there any reason to believe there's any synchronization in this method?
942 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -0700943 CHECK(code_item != NULL) << PrettyMethod(m);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700944 if (code_item->tries_size_ == 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700945 return; // No "tries" implies no synchronization, so no held locks to report.
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700946 }
947
Elliott Hughes80537bb2013-01-04 16:37:26 -0800948 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
949 // the locks held in this stack frame.
950 std::vector<uint32_t> monitor_enter_dex_pcs;
951 verifier::MethodVerifier::FindLocksAtDexPc(m, stack_visitor->GetDexPc(), monitor_enter_dex_pcs);
952 if (monitor_enter_dex_pcs.empty()) {
953 return;
954 }
955
Elliott Hughes80537bb2013-01-04 16:37:26 -0800956 for (size_t i = 0; i < monitor_enter_dex_pcs.size(); ++i) {
957 // The verifier works in terms of the dex pcs of the monitor-enter instructions.
958 // We want the registers used by those instructions (so we can read the values out of them).
959 uint32_t dex_pc = monitor_enter_dex_pcs[i];
960 uint16_t monitor_enter_instruction = code_item->insns_[dex_pc];
961
962 // Quick sanity check.
963 if ((monitor_enter_instruction & 0xff) != Instruction::MONITOR_ENTER) {
964 LOG(FATAL) << "expected monitor-enter @" << dex_pc << "; was "
965 << reinterpret_cast<void*>(monitor_enter_instruction);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700966 }
967
Elliott Hughes80537bb2013-01-04 16:37:26 -0800968 uint16_t monitor_register = ((monitor_enter_instruction >> 8) & 0xff);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800969 mirror::Object* o = reinterpret_cast<mirror::Object*>(stack_visitor->GetVReg(m, monitor_register,
970 kReferenceVReg));
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800971 callback(o, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700972 }
973}
974
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700975bool Monitor::IsValidLockWord(LockWord lock_word) {
976 switch (lock_word.GetState()) {
977 case LockWord::kUnlocked:
978 // Nothing to check.
979 return true;
980 case LockWord::kThinLocked:
981 // Basic sanity check of owner.
982 return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
983 case LockWord::kFatLocked: {
984 // Check the monitor appears in the monitor list.
985 Monitor* mon = lock_word.FatLockMonitor();
986 MonitorList* list = Runtime::Current()->GetMonitorList();
987 MutexLock mu(Thread::Current(), list->monitor_list_lock_);
988 for (Monitor* list_mon : list->list_) {
989 if (mon == list_mon) {
990 return true; // Found our monitor.
991 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700992 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700993 return false; // Fail - unowned monitor in an object.
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700994 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700995 case LockWord::kHashCode:
996 return true;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700997 default:
998 LOG(FATAL) << "Unreachable";
999 return false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001000 }
1001}
1002
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001003bool Monitor::IsLocked() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1004 MutexLock mu(Thread::Current(), monitor_lock_);
1005 return owner_ != nullptr;
1006}
1007
Brian Carlstromea46f952013-07-30 01:26:50 -07001008void Monitor::TranslateLocation(const mirror::ArtMethod* method, uint32_t dex_pc,
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001009 const char** source_file, uint32_t* line_number) const {
jeffhao33dc7712011-11-09 17:54:24 -08001010 // If method is null, location is unknown
1011 if (method == NULL) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001012 *source_file = "";
1013 *line_number = 0;
jeffhao33dc7712011-11-09 17:54:24 -08001014 return;
1015 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001016 MethodHelper mh(method);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001017 *source_file = mh.GetDeclaringClassSourceFile();
1018 if (*source_file == NULL) {
1019 *source_file = "";
Elliott Hughes12c51e32012-01-17 20:25:05 -08001020 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001021 *line_number = mh.GetLineNumFromDexPC(dex_pc);
1022}
1023
1024uint32_t Monitor::GetOwnerThreadId() {
1025 MutexLock mu(Thread::Current(), monitor_lock_);
1026 Thread* owner = owner_;
1027 if (owner != NULL) {
1028 return owner->GetThreadId();
1029 } else {
1030 return ThreadList::kInvalidThreadId;
1031 }
jeffhao33dc7712011-11-09 17:54:24 -08001032}
1033
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001034MonitorList::MonitorList()
1035 : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock"),
1036 monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001037}
1038
1039MonitorList::~MonitorList() {
Ian Rogers50b35e22012-10-04 10:09:15 -07001040 MutexLock mu(Thread::Current(), monitor_list_lock_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001041 STLDeleteElements(&list_);
1042}
1043
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001044void MonitorList::DisallowNewMonitors() {
Ian Rogers50b35e22012-10-04 10:09:15 -07001045 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001046 allow_new_monitors_ = false;
1047}
1048
1049void MonitorList::AllowNewMonitors() {
1050 Thread* self = Thread::Current();
1051 MutexLock mu(self, monitor_list_lock_);
1052 allow_new_monitors_ = true;
1053 monitor_add_condition_.Broadcast(self);
1054}
1055
1056void MonitorList::Add(Monitor* m) {
1057 Thread* self = Thread::Current();
1058 MutexLock mu(self, monitor_list_lock_);
1059 while (UNLIKELY(!allow_new_monitors_)) {
1060 monitor_add_condition_.WaitHoldingLocks(self);
1061 }
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001062 list_.push_front(m);
1063}
1064
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001065void MonitorList::SweepMonitorList(RootVisitor visitor, void* arg) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001066 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001067 for (auto it = list_.begin(); it != list_.end(); ) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001068 Monitor* m = *it;
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001069 mirror::Object* obj = m->GetObject();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001070 // The object of a monitor can be null if we have deflated it.
1071 mirror::Object* new_obj = obj != nullptr ? visitor(obj, arg) : nullptr;
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001072 if (new_obj == nullptr) {
1073 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
1074 << m->GetObject();
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001075 delete m;
1076 it = list_.erase(it);
1077 } else {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001078 m->SetObject(new_obj);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001079 ++it;
1080 }
1081 }
1082}
1083
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001084MonitorInfo::MonitorInfo(mirror::Object* obj) : owner_(NULL), entry_count_(0) {
1085 DCHECK(obj != NULL);
1086
1087 LockWord lock_word = obj->GetLockWord();
1088 switch (lock_word.GetState()) {
1089 case LockWord::kUnlocked:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001090 // Fall-through.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001091 case LockWord::kForwardingAddress:
1092 // Fall-through.
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001093 case LockWord::kHashCode:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001094 break;
1095 case LockWord::kThinLocked:
1096 owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
1097 entry_count_ = 1 + lock_word.ThinLockCount();
1098 // Thin locks have no waiters.
1099 break;
1100 case LockWord::kFatLocked: {
1101 Monitor* mon = lock_word.FatLockMonitor();
1102 owner_ = mon->owner_;
1103 entry_count_ = 1 + mon->lock_count_;
1104 for (Thread* waiter = mon->wait_set_; waiter != NULL; waiter = waiter->wait_next_) {
1105 waiters_.push_back(waiter);
1106 }
1107 break;
Elliott Hughesf327e072013-01-09 16:01:26 -08001108 }
1109 }
1110}
1111
Elliott Hughes5f791332011-09-15 17:45:30 -07001112} // namespace art