blob: 2abfd3df41792d69daf98a539fde2feb850412ef [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 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700131 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700132 LockWord fat(this);
133 // Publish the updated lock word, which may race with other threads.
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700134 bool success = obj_->CasLockWord(lw, fat);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700135 // Lock profiling.
Mathieu Chartier9728f912013-10-30 09:45:13 -0700136 if (success && owner_ != nullptr && lock_profiling_threshold_ != 0) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700137 locking_method_ = owner_->GetCurrentMethod(&locking_dex_pc_);
138 }
139 return success;
Elliott Hughes5f791332011-09-15 17:45:30 -0700140}
141
142Monitor::~Monitor() {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700143 CHECK(obj_ != NULL);
144 CHECK_EQ(obj_->GetLockWord().GetState(), LockWord::kFatLocked);
Elliott Hughes5f791332011-09-15 17:45:30 -0700145}
146
147/*
148 * Links a thread into a monitor's wait set. The monitor lock must be
149 * held by the caller of this routine.
150 */
151void Monitor::AppendToWaitSet(Thread* thread) {
152 DCHECK(owner_ == Thread::Current());
153 DCHECK(thread != NULL);
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700154 DCHECK(thread->wait_next_ == NULL) << thread->wait_next_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700155 if (wait_set_ == NULL) {
156 wait_set_ = thread;
157 return;
158 }
159
160 // push_back.
161 Thread* t = wait_set_;
162 while (t->wait_next_ != NULL) {
163 t = t->wait_next_;
164 }
165 t->wait_next_ = thread;
166}
167
168/*
169 * Unlinks a thread from a monitor's wait set. The monitor lock must
170 * be held by the caller of this routine.
171 */
172void Monitor::RemoveFromWaitSet(Thread *thread) {
173 DCHECK(owner_ == Thread::Current());
174 DCHECK(thread != NULL);
175 if (wait_set_ == NULL) {
176 return;
177 }
178 if (wait_set_ == thread) {
179 wait_set_ = thread->wait_next_;
180 thread->wait_next_ = NULL;
181 return;
182 }
183
184 Thread* t = wait_set_;
185 while (t->wait_next_ != NULL) {
186 if (t->wait_next_ == thread) {
187 t->wait_next_ = thread->wait_next_;
188 thread->wait_next_ = NULL;
189 return;
190 }
191 t = t->wait_next_;
192 }
193}
194
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700195void Monitor::SetObject(mirror::Object* object) {
196 obj_ = object;
197}
198
Elliott Hughes5f791332011-09-15 17:45:30 -0700199void Monitor::Lock(Thread* self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700200 MutexLock mu(self, monitor_lock_);
201 while (true) {
202 if (owner_ == NULL) { // Unowned.
203 owner_ = self;
204 CHECK_EQ(lock_count_, 0);
205 // When debugging, save the current monitor holder for future
206 // acquisition failures to use in sampled logging.
207 if (lock_profiling_threshold_ != 0) {
208 locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
209 }
210 return;
211 } else if (owner_ == self) { // Recursive.
212 lock_count_++;
213 return;
214 }
215 // Contended.
216 const bool log_contention = (lock_profiling_threshold_ != 0);
217 uint64_t wait_start_ms = log_contention ? 0 : MilliTime();
218 const mirror::ArtMethod* owners_method = locking_method_;
219 uint32_t owners_dex_pc = locking_dex_pc_;
220 monitor_lock_.Unlock(self); // Let go of locks in order.
Elliott Hughes5f791332011-09-15 17:45:30 -0700221 {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700222 ScopedThreadStateChange tsc(self, kBlocked); // Change to blocked and give up mutator_lock_.
223 MutexLock mu2(self, monitor_lock_); // Reacquire monitor_lock_ without mutator_lock_ for Wait.
224 if (owner_ != NULL) { // Did the owner_ give the lock up?
225 monitor_contenders_.Wait(self); // Still contended so wait.
226 // Woken from contention.
227 if (log_contention) {
228 uint64_t wait_ms = MilliTime() - wait_start_ms;
229 uint32_t sample_percent;
230 if (wait_ms >= lock_profiling_threshold_) {
231 sample_percent = 100;
232 } else {
233 sample_percent = 100 * wait_ms / lock_profiling_threshold_;
234 }
235 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
236 const char* owners_filename;
237 uint32_t owners_line_number;
238 TranslateLocation(owners_method, owners_dex_pc, &owners_filename, &owners_line_number);
239 LogContentionEvent(self, wait_ms, sample_percent, owners_filename, owners_line_number);
240 }
241 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700242 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700243 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700244 monitor_lock_.Lock(self); // Reacquire locks in order.
Elliott Hughesfc861622011-10-17 17:57:47 -0700245 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700246}
247
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800248static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
249 __attribute__((format(printf, 1, 2)));
250
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700251static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700252 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800253 va_list args;
254 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800255 Thread* self = Thread::Current();
256 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
257 self->ThrowNewExceptionV(throw_location, "Ljava/lang/IllegalMonitorStateException;", fmt, args);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700258 if (!Runtime::Current()->IsStarted() || VLOG_IS_ON(monitor)) {
Brian Carlstrom64277f32012-03-26 23:53:34 -0700259 std::ostringstream ss;
Ian Rogers62d6c772013-02-27 08:32:07 -0800260 self->Dump(ss);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700261 LOG(Runtime::Current()->IsStarted() ? INFO : ERROR)
262 << self->GetException(NULL)->Dump() << "\n" << ss.str();
Brian Carlstrom64277f32012-03-26 23:53:34 -0700263 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800264 va_end(args);
265}
266
Elliott Hughesd4237412012-02-21 11:24:45 -0800267static std::string ThreadToString(Thread* thread) {
268 if (thread == NULL) {
269 return "NULL";
270 }
271 std::ostringstream oss;
272 // TODO: alternatively, we could just return the thread's name.
273 oss << *thread;
274 return oss.str();
275}
276
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800277void Monitor::FailedUnlock(mirror::Object* o, Thread* expected_owner, Thread* found_owner,
Elliott Hughesffb465f2012-03-01 18:46:05 -0800278 Monitor* monitor) {
279 Thread* current_owner = NULL;
280 std::string current_owner_string;
281 std::string expected_owner_string;
282 std::string found_owner_string;
283 {
284 // TODO: isn't this too late to prevent threads from disappearing?
285 // Acquire thread list lock so threads won't disappear from under us.
Ian Rogers50b35e22012-10-04 10:09:15 -0700286 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Elliott Hughesffb465f2012-03-01 18:46:05 -0800287 // Re-read owner now that we hold lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700288 current_owner = (monitor != NULL) ? monitor->GetOwner() : NULL;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800289 // Get short descriptions of the threads involved.
290 current_owner_string = ThreadToString(current_owner);
291 expected_owner_string = ThreadToString(expected_owner);
292 found_owner_string = ThreadToString(found_owner);
293 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800294 if (current_owner == NULL) {
295 if (found_owner == NULL) {
296 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
297 " on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800298 PrettyTypeOf(o).c_str(),
299 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800300 } else {
301 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800302 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
303 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800304 found_owner_string.c_str(),
305 PrettyTypeOf(o).c_str(),
306 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800307 }
308 } else {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800309 if (found_owner == NULL) {
310 // Race: originally there was no owner, there is now
311 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
312 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800313 current_owner_string.c_str(),
314 PrettyTypeOf(o).c_str(),
315 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800316 } else {
317 if (found_owner != current_owner) {
318 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800319 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
320 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800321 found_owner_string.c_str(),
322 current_owner_string.c_str(),
323 PrettyTypeOf(o).c_str(),
324 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800325 } else {
326 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
327 " on thread '%s",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800328 current_owner_string.c_str(),
329 PrettyTypeOf(o).c_str(),
330 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800331 }
332 }
333 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700334}
335
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700336bool Monitor::Unlock(Thread* self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700337 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700338 MutexLock mu(self, monitor_lock_);
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800339 Thread* owner = owner_;
340 if (owner == self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700341 // We own the monitor, so nobody else can be in here.
342 if (lock_count_ == 0) {
343 owner_ = NULL;
jeffhao33dc7712011-11-09 17:54:24 -0800344 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700345 locking_dex_pc_ = 0;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700346 // Wake a contender.
347 monitor_contenders_.Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700348 } else {
349 --lock_count_;
350 }
351 } else {
352 // We don't own this, so we're not allowed to unlock it.
353 // The JNI spec says that we should throw IllegalMonitorStateException
354 // in this case.
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800355 FailedUnlock(obj_, self, owner, this);
Elliott Hughes5f791332011-09-15 17:45:30 -0700356 return false;
357 }
358 return true;
359}
360
Elliott Hughes5f791332011-09-15 17:45:30 -0700361/*
362 * Wait on a monitor until timeout, interrupt, or notification. Used for
363 * Object.wait() and (somewhat indirectly) Thread.sleep() and Thread.join().
364 *
365 * If another thread calls Thread.interrupt(), we throw InterruptedException
366 * and return immediately if one of the following are true:
367 * - blocked in wait(), wait(long), or wait(long, int) methods of Object
368 * - blocked in join(), join(long), or join(long, int) methods of Thread
369 * - blocked in sleep(long), or sleep(long, int) methods of Thread
370 * Otherwise, we set the "interrupted" flag.
371 *
372 * Checks to make sure that "ns" is in the range 0-999999
373 * (i.e. fractions of a millisecond) and throws the appropriate
374 * exception if it isn't.
375 *
376 * The spec allows "spurious wakeups", and recommends that all code using
377 * Object.wait() do so in a loop. This appears to derive from concerns
378 * about pthread_cond_wait() on multiprocessor systems. Some commentary
379 * on the web casts doubt on whether these can/should occur.
380 *
381 * Since we're allowed to wake up "early", we clamp extremely long durations
382 * to return at the end of the 32-bit time epoch.
383 */
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800384void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
385 bool interruptShouldThrow, ThreadState why) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700386 DCHECK(self != NULL);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800387 DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
Elliott Hughes5f791332011-09-15 17:45:30 -0700388
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700389 monitor_lock_.Lock(self);
390
Elliott Hughes5f791332011-09-15 17:45:30 -0700391 // Make sure that we hold the lock.
392 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800393 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700394 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700395 return;
396 }
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800397
Elliott Hughesdf42c482013-01-09 12:49:02 -0800398 // We need to turn a zero-length timed wait into a regular wait because
399 // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
400 if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
401 why = kWaiting;
402 }
403
Elliott Hughes5f791332011-09-15 17:45:30 -0700404 // Enforce the timeout range.
405 if (ms < 0 || ns < 0 || ns > 999999) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800406 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
407 self->ThrowNewExceptionF(throw_location, "Ljava/lang/IllegalArgumentException;",
408 "timeout arguments out of range: ms=%lld ns=%d", ms, ns);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700409 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700410 return;
411 }
412
Elliott Hughes5f791332011-09-15 17:45:30 -0700413 /*
414 * Add ourselves to the set of threads waiting on this monitor, and
415 * release our hold. We need to let it go even if we're a few levels
416 * deep in a recursive lock, and we need to restore that later.
417 *
418 * We append to the wait set ahead of clearing the count and owner
419 * fields so the subroutine can check that the calling thread owns
420 * the monitor. Aside from that, the order of member updates is
421 * not order sensitive as we hold the pthread mutex.
422 */
423 AppendToWaitSet(self);
Ian Rogers0399dde2012-06-06 17:09:28 -0700424 int prev_lock_count = lock_count_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700425 lock_count_ = 0;
426 owner_ = NULL;
Brian Carlstromea46f952013-07-30 01:26:50 -0700427 const mirror::ArtMethod* saved_method = locking_method_;
jeffhao33dc7712011-11-09 17:54:24 -0800428 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700429 uintptr_t saved_dex_pc = locking_dex_pc_;
430 locking_dex_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700431
432 /*
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800433 * Update thread state. If the GC wakes up, it'll ignore us, knowing
Elliott Hughes5f791332011-09-15 17:45:30 -0700434 * that we won't touch any references in this state, and we'll check
435 * our suspend mode before we transition out.
436 */
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800437 self->TransitionFromRunnableToSuspended(why);
Elliott Hughes5f791332011-09-15 17:45:30 -0700438
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800439 bool was_interrupted = false;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700440 {
441 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
Ian Rogers50b35e22012-10-04 10:09:15 -0700442 MutexLock mu(self, *self->wait_mutex_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700443
444 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
445 // non-NULL a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
446 // up.
447 DCHECK(self->wait_monitor_ == NULL);
448 self->wait_monitor_ = this;
449
450 // Release the monitor lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700451 monitor_contenders_.Signal(self);
452 monitor_lock_.Unlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700453
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800454 // Handle the case where the thread was interrupted before we called wait().
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700455 if (self->interrupted_) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800456 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700457 } else {
458 // Wait for a notification or a timeout to occur.
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800459 if (why == kWaiting) {
Ian Rogersc604d732012-10-14 16:09:54 -0700460 self->wait_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700461 } else {
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800462 DCHECK(why == kTimedWaiting || why == kSleeping) << why;
Ian Rogersc604d732012-10-14 16:09:54 -0700463 self->wait_cond_->TimedWait(self, ms, ns);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700464 }
465 if (self->interrupted_) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800466 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700467 }
468 self->interrupted_ = false;
469 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700470 }
471
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700472 // Set self->status back to kRunnable, and self-suspend if needed.
473 self->TransitionFromSuspendedToRunnable();
Elliott Hughes5f791332011-09-15 17:45:30 -0700474
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800475 {
476 // We reset the thread's wait_monitor_ field after transitioning back to runnable so
477 // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
478 // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
479 // are waiting on "null".)
480 MutexLock mu(self, *self->wait_mutex_);
481 DCHECK(self->wait_monitor_ != NULL);
482 self->wait_monitor_ = NULL;
483 }
484
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700485 // Re-acquire the monitor and lock.
Elliott Hughes5f791332011-09-15 17:45:30 -0700486 Lock(self);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700487 monitor_lock_.Lock(self);
Ian Rogers81d425b2012-09-27 16:03:43 -0700488 self->wait_mutex_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700489
Elliott Hughes5f791332011-09-15 17:45:30 -0700490 /*
491 * We remove our thread from wait set after restoring the count
492 * and owner fields so the subroutine can check that the calling
493 * thread owns the monitor. Aside from that, the order of member
494 * updates is not order sensitive as we hold the pthread mutex.
495 */
496 owner_ = self;
Ian Rogers0399dde2012-06-06 17:09:28 -0700497 lock_count_ = prev_lock_count;
498 locking_method_ = saved_method;
499 locking_dex_pc_ = saved_dex_pc;
Elliott Hughes5f791332011-09-15 17:45:30 -0700500 RemoveFromWaitSet(self);
501
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800502 if (was_interrupted) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700503 /*
504 * We were interrupted while waiting, or somebody interrupted an
505 * un-interruptible thread earlier and we're bailing out immediately.
506 *
507 * The doc sayeth: "The interrupted status of the current thread is
508 * cleared when this exception is thrown."
509 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700510 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700511 MutexLock mu(self, *self->wait_mutex_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700512 self->interrupted_ = false;
513 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700514 if (interruptShouldThrow) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800515 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
516 self->ThrowNewException(throw_location, "Ljava/lang/InterruptedException;", NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700517 }
518 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700519 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700520}
521
522void Monitor::Notify(Thread* self) {
523 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700524 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700525 // Make sure that we hold the lock.
526 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800527 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700528 return;
529 }
530 // Signal the first waiting thread in the wait set.
531 while (wait_set_ != NULL) {
532 Thread* thread = wait_set_;
533 wait_set_ = thread->wait_next_;
534 thread->wait_next_ = NULL;
535
536 // Check to see if the thread is still waiting.
Ian Rogers50b35e22012-10-04 10:09:15 -0700537 MutexLock mu(self, *thread->wait_mutex_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700538 if (thread->wait_monitor_ != NULL) {
Ian Rogersc604d732012-10-14 16:09:54 -0700539 thread->wait_cond_->Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700540 return;
541 }
542 }
543}
544
545void Monitor::NotifyAll(Thread* self) {
546 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700547 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700548 // Make sure that we hold the lock.
549 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800550 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700551 return;
552 }
553 // Signal all threads in the wait set.
554 while (wait_set_ != NULL) {
555 Thread* thread = wait_set_;
556 wait_set_ = thread->wait_next_;
557 thread->wait_next_ = NULL;
558 thread->Notify();
559 }
560}
561
562/*
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700563 * Changes the shape of a monitor from thin to fat, preserving the internal lock state. The calling
564 * thread must own the lock or the owner must be suspended. There's a race with other threads
565 * inflating the lock and so the caller should read the monitor following the call.
Elliott Hughes5f791332011-09-15 17:45:30 -0700566 */
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700567void Monitor::Inflate(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700568 DCHECK(self != NULL);
569 DCHECK(obj != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700570 // Allocate and acquire a new monitor.
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700571 UniquePtr<Monitor> m(new Monitor(owner, obj, hash_code));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700572 if (m->Install(self)) {
573 VLOG(monitor) << "monitor: thread " << owner->GetThreadId()
574 << " created monitor " << m.get() << " for object " << obj;
575 Runtime::Current()->GetMonitorList()->Add(m.release());
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700576 CHECK_EQ(obj->GetLockWord().GetState(), LockWord::kFatLocked);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700577 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700578}
579
580void Monitor::InflateThinLocked(Thread* self, mirror::Object* obj, LockWord lock_word,
581 uint32_t hash_code) {
582 DCHECK_EQ(lock_word.GetState(), LockWord::kThinLocked);
583 uint32_t owner_thread_id = lock_word.ThinLockOwner();
584 if (owner_thread_id == self->GetThreadId()) {
585 // We own the monitor, we can easily inflate it.
586 Inflate(self, self, obj, hash_code);
587 } else {
588 ThreadList* thread_list = Runtime::Current()->GetThreadList();
589 // Suspend the owner, inflate. First change to blocked and give up mutator_lock_.
590 ScopedThreadStateChange tsc(self, kBlocked);
591 if (lock_word == obj->GetLockWord()) { // If lock word hasn't changed.
592 bool timed_out;
593 Thread* owner = thread_list->SuspendThreadByThreadId(lock_word.ThinLockOwner(), false,
594 &timed_out);
595 if (owner != nullptr) {
596 // We succeeded in suspending the thread, check the lock's status didn't change.
597 lock_word = obj->GetLockWord();
598 if (lock_word.GetState() == LockWord::kThinLocked &&
599 lock_word.ThinLockOwner() == owner_thread_id) {
600 // Go ahead and inflate the lock.
601 Inflate(self, owner, obj, hash_code);
602 }
603 thread_list->Resume(owner, false);
604 }
605 }
606 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700607}
608
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800609void Monitor::MonitorEnter(Thread* self, mirror::Object* obj) {
Elliott Hughes4681c802011-09-25 18:04:37 -0700610 DCHECK(self != NULL);
611 DCHECK(obj != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700612 uint32_t thread_id = self->GetThreadId();
613 size_t contention_count = 0;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700614 while (true) {
615 LockWord lock_word = obj->GetLockWord();
616 switch (lock_word.GetState()) {
617 case LockWord::kUnlocked: {
618 LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0));
619 if (obj->CasLockWord(lock_word, thin_locked)) {
620 return; // Success!
621 }
622 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -0700623 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700624 case LockWord::kThinLocked: {
625 uint32_t owner_thread_id = lock_word.ThinLockOwner();
626 if (owner_thread_id == thread_id) {
627 // We own the lock, increase the recursion count.
628 uint32_t new_count = lock_word.ThinLockCount() + 1;
629 if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
630 LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count));
631 obj->SetLockWord(thin_locked);
632 return; // Success!
Elliott Hughes5f791332011-09-15 17:45:30 -0700633 } else {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700634 // We'd overflow the recursion count, so inflate the monitor.
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700635 InflateThinLocked(self, obj, lock_word, 0);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700636 }
637 } else {
638 // Contention.
639 contention_count++;
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700640 Runtime* runtime = Runtime::Current();
641 if (contention_count <= runtime->GetMaxSpinsBeforeThinkLockInflation()) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700642 NanoSleep(1000); // Sleep for 1us and re-attempt.
643 } else {
644 contention_count = 0;
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700645 InflateThinLocked(self, obj, lock_word, 0);
Elliott Hughes5f791332011-09-15 17:45:30 -0700646 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700647 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700648 continue; // Start from the beginning.
Elliott Hughes5f791332011-09-15 17:45:30 -0700649 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700650 case LockWord::kFatLocked: {
651 Monitor* mon = lock_word.FatLockMonitor();
652 mon->Lock(self);
653 return; // Success!
654 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700655 case LockWord::kHashCode: {
656 // Inflate with the existing hashcode.
657 Inflate(self, nullptr, obj, lock_word.GetHashCode());
658 break;
659 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700660 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700661 }
662}
663
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800664bool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700665 DCHECK(self != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700666 DCHECK(obj != NULL);
667
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700668 LockWord lock_word = obj->GetLockWord();
669 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700670 case LockWord::kHashCode:
671 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700672 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800673 FailedUnlock(obj, self, NULL, NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700674 return false; // Failure.
675 case LockWord::kThinLocked: {
676 uint32_t thread_id = self->GetThreadId();
677 uint32_t owner_thread_id = lock_word.ThinLockOwner();
678 if (owner_thread_id != thread_id) {
679 // TODO: there's a race here with the owner dying while we unlock.
680 Thread* owner =
681 Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
682 FailedUnlock(obj, self, owner, NULL);
683 return false; // Failure.
684 } else {
685 // We own the lock, decrease the recursion count.
686 if (lock_word.ThinLockCount() != 0) {
687 uint32_t new_count = lock_word.ThinLockCount() - 1;
688 LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count));
689 obj->SetLockWord(thin_locked);
690 } else {
691 obj->SetLockWord(LockWord());
692 }
693 return true; // Success!
694 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700695 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700696 case LockWord::kFatLocked: {
697 Monitor* mon = lock_word.FatLockMonitor();
698 return mon->Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700699 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700700 default:
701 LOG(FATAL) << "Unreachable";
702 return false;
Elliott Hughes5f791332011-09-15 17:45:30 -0700703 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700704}
705
706/*
707 * Object.wait(). Also called for class init.
708 */
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800709void Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800710 bool interruptShouldThrow, ThreadState why) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700711 DCHECK(self != NULL);
712 DCHECK(obj != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700713
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700714 LockWord lock_word = obj->GetLockWord();
715 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:
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800719 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700720 return; // 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 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
726 return; // Failure.
727 } else {
728 // We own the lock, inflate to enqueue ourself on the Monitor.
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700729 Inflate(self, self, obj, 0);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700730 lock_word = obj->GetLockWord();
731 }
732 break;
Elliott Hughes5f791332011-09-15 17:45:30 -0700733 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700734 case LockWord::kFatLocked:
735 break; // Already set for a wait.
Elliott Hughes5f791332011-09-15 17:45:30 -0700736 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700737 Monitor* mon = lock_word.FatLockMonitor();
738 mon->Wait(self, ms, ns, interruptShouldThrow, why);
Elliott Hughes5f791332011-09-15 17:45:30 -0700739}
740
Ian Rogers13c479e2013-10-11 07:59:01 -0700741void Monitor::DoNotify(Thread* self, mirror::Object* obj, bool notify_all) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700742 DCHECK(self != NULL);
743 DCHECK(obj != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700744
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700745 LockWord lock_word = obj->GetLockWord();
746 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700747 case LockWord::kHashCode:
748 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700749 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800750 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700751 return; // Failure.
752 case LockWord::kThinLocked: {
753 uint32_t thread_id = self->GetThreadId();
754 uint32_t owner_thread_id = lock_word.ThinLockOwner();
755 if (owner_thread_id != thread_id) {
756 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
757 return; // Failure.
758 } else {
759 // We own the lock but there's no Monitor and therefore no waiters.
760 return; // Success.
761 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700762 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700763 case LockWord::kFatLocked: {
764 Monitor* mon = lock_word.FatLockMonitor();
765 if (notify_all) {
766 mon->NotifyAll(self);
767 } else {
768 mon->Notify(self);
769 }
770 return; // Success.
771 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700772 }
773}
774
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700775uint32_t Monitor::GetLockOwnerThreadId(mirror::Object* obj) {
776 DCHECK(obj != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700777
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700778 LockWord lock_word = obj->GetLockWord();
779 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700780 case LockWord::kHashCode:
781 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700782 case LockWord::kUnlocked:
783 return ThreadList::kInvalidThreadId;
784 case LockWord::kThinLocked:
785 return lock_word.ThinLockOwner();
786 case LockWord::kFatLocked: {
787 Monitor* mon = lock_word.FatLockMonitor();
788 return mon->GetOwnerThreadId();
Elliott Hughes5f791332011-09-15 17:45:30 -0700789 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700790 default:
791 LOG(FATAL) << "Unreachable";
792 return ThreadList::kInvalidThreadId;
Elliott Hughes5f791332011-09-15 17:45:30 -0700793 }
794}
795
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700796void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800797 ThreadState state = thread->GetState();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700798
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700799 int32_t object_identity_hashcode = 0;
800 uint32_t lock_owner = ThreadList::kInvalidThreadId;
801 std::string pretty_type;
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800802 if (state == kWaiting || state == kTimedWaiting || state == kSleeping) {
803 if (state == kSleeping) {
804 os << " - sleeping on ";
805 } else {
806 os << " - waiting on ";
807 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700808 {
Elliott Hughesf9501702013-01-11 11:22:27 -0800809 Thread* self = Thread::Current();
810 MutexLock mu(self, *thread->wait_mutex_);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800811 Monitor* monitor = thread->wait_monitor_;
812 if (monitor != NULL) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700813 mirror::Object* object = monitor->obj_;
814 object_identity_hashcode = object->IdentityHashCode();
815 pretty_type = PrettyTypeOf(object);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800816 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700817 }
Elliott Hughes34e06962012-04-09 13:55:55 -0700818 } else if (state == kBlocked) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700819 os << " - waiting to lock ";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700820 mirror::Object* object = thread->monitor_enter_object_;
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700821 if (object != NULL) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700822 object_identity_hashcode = object->IdentityHashCode();
823 lock_owner = object->GetLockOwnerThreadId();
824 pretty_type = PrettyTypeOf(object);
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700825 }
826 } else {
827 // We're not waiting on anything.
828 return;
829 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700830
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700831 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700832 os << StringPrintf("<0x%08x> (a %s)", object_identity_hashcode, pretty_type.c_str());
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700833
Elliott Hughesc5dc2ff2013-01-09 13:44:30 -0800834 // - waiting to lock <0x613f83d8> (a java.lang.Object) held by thread 5
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700835 if (lock_owner != ThreadList::kInvalidThreadId) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700836 os << " held by thread " << lock_owner;
837 }
838
839 os << "\n";
840}
841
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800842mirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800843 // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
844 // definition of contended that includes a monitor a thread is trying to enter...
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800845 mirror::Object* result = thread->monitor_enter_object_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700846 if (result == NULL) {
847 // ...but also a monitor that the thread is waiting on.
Elliott Hughesf9501702013-01-11 11:22:27 -0800848 MutexLock mu(Thread::Current(), *thread->wait_mutex_);
849 Monitor* monitor = thread->wait_monitor_;
850 if (monitor != NULL) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700851 result = monitor->GetObject();
Elliott Hughesf9501702013-01-11 11:22:27 -0800852 }
853 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700854 return result;
Elliott Hughesf9501702013-01-11 11:22:27 -0800855}
856
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800857void Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
858 void* callback_context) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700859 mirror::ArtMethod* m = stack_visitor->GetMethod();
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700860 CHECK(m != NULL);
861
862 // Native methods are an easy special case.
863 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
864 if (m->IsNative()) {
865 if (m->IsSynchronized()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800866 mirror::Object* jni_this = stack_visitor->GetCurrentSirt()->GetReference(0);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800867 callback(jni_this, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700868 }
869 return;
870 }
871
jeffhao61f916c2012-10-25 17:48:51 -0700872 // Proxy methods should not be synchronized.
873 if (m->IsProxyMethod()) {
874 CHECK(!m->IsSynchronized());
875 return;
876 }
877
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700878 // <clinit> is another special case. The runtime holds the class lock while calling <clinit>.
879 MethodHelper mh(m);
880 if (mh.IsClassInitializer()) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800881 callback(m->GetDeclaringClass(), callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700882 // Fall through because there might be synchronization in the user code too.
883 }
884
885 // Is there any reason to believe there's any synchronization in this method?
886 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -0700887 CHECK(code_item != NULL) << PrettyMethod(m);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700888 if (code_item->tries_size_ == 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700889 return; // No "tries" implies no synchronization, so no held locks to report.
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700890 }
891
Elliott Hughes80537bb2013-01-04 16:37:26 -0800892 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
893 // the locks held in this stack frame.
894 std::vector<uint32_t> monitor_enter_dex_pcs;
895 verifier::MethodVerifier::FindLocksAtDexPc(m, stack_visitor->GetDexPc(), monitor_enter_dex_pcs);
896 if (monitor_enter_dex_pcs.empty()) {
897 return;
898 }
899
Elliott Hughes80537bb2013-01-04 16:37:26 -0800900 for (size_t i = 0; i < monitor_enter_dex_pcs.size(); ++i) {
901 // The verifier works in terms of the dex pcs of the monitor-enter instructions.
902 // We want the registers used by those instructions (so we can read the values out of them).
903 uint32_t dex_pc = monitor_enter_dex_pcs[i];
904 uint16_t monitor_enter_instruction = code_item->insns_[dex_pc];
905
906 // Quick sanity check.
907 if ((monitor_enter_instruction & 0xff) != Instruction::MONITOR_ENTER) {
908 LOG(FATAL) << "expected monitor-enter @" << dex_pc << "; was "
909 << reinterpret_cast<void*>(monitor_enter_instruction);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700910 }
911
Elliott Hughes80537bb2013-01-04 16:37:26 -0800912 uint16_t monitor_register = ((monitor_enter_instruction >> 8) & 0xff);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800913 mirror::Object* o = reinterpret_cast<mirror::Object*>(stack_visitor->GetVReg(m, monitor_register,
914 kReferenceVReg));
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800915 callback(o, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700916 }
917}
918
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700919bool Monitor::IsValidLockWord(LockWord lock_word) {
920 switch (lock_word.GetState()) {
921 case LockWord::kUnlocked:
922 // Nothing to check.
923 return true;
924 case LockWord::kThinLocked:
925 // Basic sanity check of owner.
926 return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
927 case LockWord::kFatLocked: {
928 // Check the monitor appears in the monitor list.
929 Monitor* mon = lock_word.FatLockMonitor();
930 MonitorList* list = Runtime::Current()->GetMonitorList();
931 MutexLock mu(Thread::Current(), list->monitor_list_lock_);
932 for (Monitor* list_mon : list->list_) {
933 if (mon == list_mon) {
934 return true; // Found our monitor.
935 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700936 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700937 return false; // Fail - unowned monitor in an object.
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700938 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700939 case LockWord::kHashCode:
940 return true;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700941 default:
942 LOG(FATAL) << "Unreachable";
943 return false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700944 }
945}
946
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700947bool Monitor::IsLocked() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
948 MutexLock mu(Thread::Current(), monitor_lock_);
949 return owner_ != nullptr;
950}
951
Brian Carlstromea46f952013-07-30 01:26:50 -0700952void Monitor::TranslateLocation(const mirror::ArtMethod* method, uint32_t dex_pc,
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700953 const char** source_file, uint32_t* line_number) const {
jeffhao33dc7712011-11-09 17:54:24 -0800954 // If method is null, location is unknown
955 if (method == NULL) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700956 *source_file = "";
957 *line_number = 0;
jeffhao33dc7712011-11-09 17:54:24 -0800958 return;
959 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800960 MethodHelper mh(method);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700961 *source_file = mh.GetDeclaringClassSourceFile();
962 if (*source_file == NULL) {
963 *source_file = "";
Elliott Hughes12c51e32012-01-17 20:25:05 -0800964 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700965 *line_number = mh.GetLineNumFromDexPC(dex_pc);
966}
967
968uint32_t Monitor::GetOwnerThreadId() {
969 MutexLock mu(Thread::Current(), monitor_lock_);
970 Thread* owner = owner_;
971 if (owner != NULL) {
972 return owner->GetThreadId();
973 } else {
974 return ThreadList::kInvalidThreadId;
975 }
jeffhao33dc7712011-11-09 17:54:24 -0800976}
977
Mathieu Chartierc11d9b82013-09-19 10:01:59 -0700978MonitorList::MonitorList()
979 : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock"),
980 monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700981}
982
983MonitorList::~MonitorList() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700984 MutexLock mu(Thread::Current(), monitor_list_lock_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700985 STLDeleteElements(&list_);
986}
987
Mathieu Chartierc11d9b82013-09-19 10:01:59 -0700988void MonitorList::DisallowNewMonitors() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700989 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -0700990 allow_new_monitors_ = false;
991}
992
993void MonitorList::AllowNewMonitors() {
994 Thread* self = Thread::Current();
995 MutexLock mu(self, monitor_list_lock_);
996 allow_new_monitors_ = true;
997 monitor_add_condition_.Broadcast(self);
998}
999
1000void MonitorList::Add(Monitor* m) {
1001 Thread* self = Thread::Current();
1002 MutexLock mu(self, monitor_list_lock_);
1003 while (UNLIKELY(!allow_new_monitors_)) {
1004 monitor_add_condition_.WaitHoldingLocks(self);
1005 }
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001006 list_.push_front(m);
1007}
1008
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001009void MonitorList::SweepMonitorList(RootVisitor visitor, void* arg) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001010 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001011 for (auto it = list_.begin(); it != list_.end(); ) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001012 Monitor* m = *it;
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001013 mirror::Object* obj = m->GetObject();
1014 mirror::Object* new_obj = visitor(obj, arg);
1015 if (new_obj == nullptr) {
1016 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
1017 << m->GetObject();
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001018 delete m;
1019 it = list_.erase(it);
1020 } else {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001021 m->SetObject(new_obj);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001022 ++it;
1023 }
1024 }
1025}
1026
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001027MonitorInfo::MonitorInfo(mirror::Object* obj) : owner_(NULL), entry_count_(0) {
1028 DCHECK(obj != NULL);
1029
1030 LockWord lock_word = obj->GetLockWord();
1031 switch (lock_word.GetState()) {
1032 case LockWord::kUnlocked:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001033 // Fall-through.
1034 case LockWord::kHashCode:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001035 break;
1036 case LockWord::kThinLocked:
1037 owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
1038 entry_count_ = 1 + lock_word.ThinLockCount();
1039 // Thin locks have no waiters.
1040 break;
1041 case LockWord::kFatLocked: {
1042 Monitor* mon = lock_word.FatLockMonitor();
1043 owner_ = mon->owner_;
1044 entry_count_ = 1 + mon->lock_count_;
1045 for (Thread* waiter = mon->wait_set_; waiter != NULL; waiter = waiter->wait_next_) {
1046 waiters_.push_back(waiter);
1047 }
1048 break;
Elliott Hughesf327e072013-01-09 16:01:26 -08001049 }
1050 }
1051}
1052
Elliott Hughes5f791332011-09-15 17:45:30 -07001053} // namespace art