blob: 1ceaa5dd99bdb82292b46cdebd96c5f04e7a8c06 [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
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080082Monitor::Monitor(Thread* owner, mirror::Object* obj)
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),
jeffhao33dc7712011-11-09 17:54:24 -080089 locking_method_(NULL),
Ian Rogers0399dde2012-06-06 17:09:28 -070090 locking_dex_pc_(0) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -070091 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
92 // with the owner unlocking the thin-lock.
93 CHECK(owner == Thread::Current() || owner->IsSuspended());
94}
95
96bool Monitor::Install(Thread* self) {
97 MutexLock mu(self, monitor_lock_); // Uncontended mutex acquisition as monitor isn't yet public.
98 CHECK(owner_ == self || owner_->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -070099 // Propagate the lock state.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700100 LockWord thin(obj_->GetLockWord());
101 if (thin.GetState() != LockWord::kThinLocked) {
102 // The owner_ is suspended but another thread beat us to install a monitor.
103 CHECK_EQ(thin.GetState(), LockWord::kFatLocked);
104 return false;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700105 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700106 CHECK_EQ(owner_->GetThreadId(), thin.ThinLockOwner());
107 lock_count_ = thin.ThinLockCount();
108 LockWord fat(this);
109 // Publish the updated lock word, which may race with other threads.
110 bool success = obj_->CasLockWord(thin, fat);
111 // Lock profiling.
112 if (success && lock_profiling_threshold_ != 0) {
113 locking_method_ = owner_->GetCurrentMethod(&locking_dex_pc_);
114 }
115 return success;
Elliott Hughes5f791332011-09-15 17:45:30 -0700116}
117
118Monitor::~Monitor() {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700119 CHECK(obj_ != NULL);
120 CHECK_EQ(obj_->GetLockWord().GetState(), LockWord::kFatLocked);
Elliott Hughes5f791332011-09-15 17:45:30 -0700121}
122
123/*
124 * Links a thread into a monitor's wait set. The monitor lock must be
125 * held by the caller of this routine.
126 */
127void Monitor::AppendToWaitSet(Thread* thread) {
128 DCHECK(owner_ == Thread::Current());
129 DCHECK(thread != NULL);
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700130 DCHECK(thread->wait_next_ == NULL) << thread->wait_next_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700131 if (wait_set_ == NULL) {
132 wait_set_ = thread;
133 return;
134 }
135
136 // push_back.
137 Thread* t = wait_set_;
138 while (t->wait_next_ != NULL) {
139 t = t->wait_next_;
140 }
141 t->wait_next_ = thread;
142}
143
144/*
145 * Unlinks a thread from a monitor's wait set. The monitor lock must
146 * be held by the caller of this routine.
147 */
148void Monitor::RemoveFromWaitSet(Thread *thread) {
149 DCHECK(owner_ == Thread::Current());
150 DCHECK(thread != NULL);
151 if (wait_set_ == NULL) {
152 return;
153 }
154 if (wait_set_ == thread) {
155 wait_set_ = thread->wait_next_;
156 thread->wait_next_ = NULL;
157 return;
158 }
159
160 Thread* t = wait_set_;
161 while (t->wait_next_ != NULL) {
162 if (t->wait_next_ == thread) {
163 t->wait_next_ = thread->wait_next_;
164 thread->wait_next_ = NULL;
165 return;
166 }
167 t = t->wait_next_;
168 }
169}
170
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700171void Monitor::SetObject(mirror::Object* object) {
172 obj_ = object;
173}
174
Elliott Hughes5f791332011-09-15 17:45:30 -0700175void Monitor::Lock(Thread* self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700176 MutexLock mu(self, monitor_lock_);
177 while (true) {
178 if (owner_ == NULL) { // Unowned.
179 owner_ = self;
180 CHECK_EQ(lock_count_, 0);
181 // When debugging, save the current monitor holder for future
182 // acquisition failures to use in sampled logging.
183 if (lock_profiling_threshold_ != 0) {
184 locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
185 }
186 return;
187 } else if (owner_ == self) { // Recursive.
188 lock_count_++;
189 return;
190 }
191 // Contended.
192 const bool log_contention = (lock_profiling_threshold_ != 0);
193 uint64_t wait_start_ms = log_contention ? 0 : MilliTime();
194 const mirror::ArtMethod* owners_method = locking_method_;
195 uint32_t owners_dex_pc = locking_dex_pc_;
196 monitor_lock_.Unlock(self); // Let go of locks in order.
Elliott Hughes5f791332011-09-15 17:45:30 -0700197 {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700198 ScopedThreadStateChange tsc(self, kBlocked); // Change to blocked and give up mutator_lock_.
199 MutexLock mu2(self, monitor_lock_); // Reacquire monitor_lock_ without mutator_lock_ for Wait.
200 if (owner_ != NULL) { // Did the owner_ give the lock up?
201 monitor_contenders_.Wait(self); // Still contended so wait.
202 // Woken from contention.
203 if (log_contention) {
204 uint64_t wait_ms = MilliTime() - wait_start_ms;
205 uint32_t sample_percent;
206 if (wait_ms >= lock_profiling_threshold_) {
207 sample_percent = 100;
208 } else {
209 sample_percent = 100 * wait_ms / lock_profiling_threshold_;
210 }
211 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
212 const char* owners_filename;
213 uint32_t owners_line_number;
214 TranslateLocation(owners_method, owners_dex_pc, &owners_filename, &owners_line_number);
215 LogContentionEvent(self, wait_ms, sample_percent, owners_filename, owners_line_number);
216 }
217 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700218 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700219 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700220 monitor_lock_.Lock(self); // Reacquire locks in order.
Elliott Hughesfc861622011-10-17 17:57:47 -0700221 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700222}
223
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800224static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
225 __attribute__((format(printf, 1, 2)));
226
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700227static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700228 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800229 va_list args;
230 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800231 Thread* self = Thread::Current();
232 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
233 self->ThrowNewExceptionV(throw_location, "Ljava/lang/IllegalMonitorStateException;", fmt, args);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700234 if (!Runtime::Current()->IsStarted() || VLOG_IS_ON(monitor)) {
Brian Carlstrom64277f32012-03-26 23:53:34 -0700235 std::ostringstream ss;
Ian Rogers62d6c772013-02-27 08:32:07 -0800236 self->Dump(ss);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700237 LOG(Runtime::Current()->IsStarted() ? INFO : ERROR)
238 << self->GetException(NULL)->Dump() << "\n" << ss.str();
Brian Carlstrom64277f32012-03-26 23:53:34 -0700239 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800240 va_end(args);
241}
242
Elliott Hughesd4237412012-02-21 11:24:45 -0800243static std::string ThreadToString(Thread* thread) {
244 if (thread == NULL) {
245 return "NULL";
246 }
247 std::ostringstream oss;
248 // TODO: alternatively, we could just return the thread's name.
249 oss << *thread;
250 return oss.str();
251}
252
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800253void Monitor::FailedUnlock(mirror::Object* o, Thread* expected_owner, Thread* found_owner,
Elliott Hughesffb465f2012-03-01 18:46:05 -0800254 Monitor* monitor) {
255 Thread* current_owner = NULL;
256 std::string current_owner_string;
257 std::string expected_owner_string;
258 std::string found_owner_string;
259 {
260 // TODO: isn't this too late to prevent threads from disappearing?
261 // Acquire thread list lock so threads won't disappear from under us.
Ian Rogers50b35e22012-10-04 10:09:15 -0700262 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Elliott Hughesffb465f2012-03-01 18:46:05 -0800263 // Re-read owner now that we hold lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700264 current_owner = (monitor != NULL) ? monitor->GetOwner() : NULL;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800265 // Get short descriptions of the threads involved.
266 current_owner_string = ThreadToString(current_owner);
267 expected_owner_string = ThreadToString(expected_owner);
268 found_owner_string = ThreadToString(found_owner);
269 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800270 if (current_owner == NULL) {
271 if (found_owner == NULL) {
272 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
273 " on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800274 PrettyTypeOf(o).c_str(),
275 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800276 } else {
277 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800278 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
279 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800280 found_owner_string.c_str(),
281 PrettyTypeOf(o).c_str(),
282 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800283 }
284 } else {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800285 if (found_owner == NULL) {
286 // Race: originally there was no owner, there is now
287 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
288 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800289 current_owner_string.c_str(),
290 PrettyTypeOf(o).c_str(),
291 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800292 } else {
293 if (found_owner != current_owner) {
294 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800295 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
296 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800297 found_owner_string.c_str(),
298 current_owner_string.c_str(),
299 PrettyTypeOf(o).c_str(),
300 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800301 } else {
302 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
303 " on thread '%s",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800304 current_owner_string.c_str(),
305 PrettyTypeOf(o).c_str(),
306 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800307 }
308 }
309 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700310}
311
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700312bool Monitor::Unlock(Thread* self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700313 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700314 MutexLock mu(self, monitor_lock_);
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800315 Thread* owner = owner_;
316 if (owner == self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700317 // We own the monitor, so nobody else can be in here.
318 if (lock_count_ == 0) {
319 owner_ = NULL;
jeffhao33dc7712011-11-09 17:54:24 -0800320 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700321 locking_dex_pc_ = 0;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700322 // Wake a contender.
323 monitor_contenders_.Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700324 } else {
325 --lock_count_;
326 }
327 } else {
328 // We don't own this, so we're not allowed to unlock it.
329 // The JNI spec says that we should throw IllegalMonitorStateException
330 // in this case.
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800331 FailedUnlock(obj_, self, owner, this);
Elliott Hughes5f791332011-09-15 17:45:30 -0700332 return false;
333 }
334 return true;
335}
336
Elliott Hughes5f791332011-09-15 17:45:30 -0700337/*
338 * Wait on a monitor until timeout, interrupt, or notification. Used for
339 * Object.wait() and (somewhat indirectly) Thread.sleep() and Thread.join().
340 *
341 * If another thread calls Thread.interrupt(), we throw InterruptedException
342 * and return immediately if one of the following are true:
343 * - blocked in wait(), wait(long), or wait(long, int) methods of Object
344 * - blocked in join(), join(long), or join(long, int) methods of Thread
345 * - blocked in sleep(long), or sleep(long, int) methods of Thread
346 * Otherwise, we set the "interrupted" flag.
347 *
348 * Checks to make sure that "ns" is in the range 0-999999
349 * (i.e. fractions of a millisecond) and throws the appropriate
350 * exception if it isn't.
351 *
352 * The spec allows "spurious wakeups", and recommends that all code using
353 * Object.wait() do so in a loop. This appears to derive from concerns
354 * about pthread_cond_wait() on multiprocessor systems. Some commentary
355 * on the web casts doubt on whether these can/should occur.
356 *
357 * Since we're allowed to wake up "early", we clamp extremely long durations
358 * to return at the end of the 32-bit time epoch.
359 */
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800360void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
361 bool interruptShouldThrow, ThreadState why) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700362 DCHECK(self != NULL);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800363 DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
Elliott Hughes5f791332011-09-15 17:45:30 -0700364
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700365 monitor_lock_.Lock(self);
366
Elliott Hughes5f791332011-09-15 17:45:30 -0700367 // Make sure that we hold the lock.
368 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800369 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700370 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700371 return;
372 }
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800373
Elliott Hughesdf42c482013-01-09 12:49:02 -0800374 // We need to turn a zero-length timed wait into a regular wait because
375 // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
376 if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
377 why = kWaiting;
378 }
379
Elliott Hughes5f791332011-09-15 17:45:30 -0700380 // Enforce the timeout range.
381 if (ms < 0 || ns < 0 || ns > 999999) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800382 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
383 self->ThrowNewExceptionF(throw_location, "Ljava/lang/IllegalArgumentException;",
384 "timeout arguments out of range: ms=%lld ns=%d", ms, ns);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700385 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700386 return;
387 }
388
Elliott Hughes5f791332011-09-15 17:45:30 -0700389 /*
390 * Add ourselves to the set of threads waiting on this monitor, and
391 * release our hold. We need to let it go even if we're a few levels
392 * deep in a recursive lock, and we need to restore that later.
393 *
394 * We append to the wait set ahead of clearing the count and owner
395 * fields so the subroutine can check that the calling thread owns
396 * the monitor. Aside from that, the order of member updates is
397 * not order sensitive as we hold the pthread mutex.
398 */
399 AppendToWaitSet(self);
Ian Rogers0399dde2012-06-06 17:09:28 -0700400 int prev_lock_count = lock_count_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700401 lock_count_ = 0;
402 owner_ = NULL;
Brian Carlstromea46f952013-07-30 01:26:50 -0700403 const mirror::ArtMethod* saved_method = locking_method_;
jeffhao33dc7712011-11-09 17:54:24 -0800404 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700405 uintptr_t saved_dex_pc = locking_dex_pc_;
406 locking_dex_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700407
408 /*
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800409 * Update thread state. If the GC wakes up, it'll ignore us, knowing
Elliott Hughes5f791332011-09-15 17:45:30 -0700410 * that we won't touch any references in this state, and we'll check
411 * our suspend mode before we transition out.
412 */
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800413 self->TransitionFromRunnableToSuspended(why);
Elliott Hughes5f791332011-09-15 17:45:30 -0700414
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800415 bool was_interrupted = false;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700416 {
417 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
Ian Rogers50b35e22012-10-04 10:09:15 -0700418 MutexLock mu(self, *self->wait_mutex_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700419
420 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
421 // non-NULL a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
422 // up.
423 DCHECK(self->wait_monitor_ == NULL);
424 self->wait_monitor_ = this;
425
426 // Release the monitor lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700427 monitor_contenders_.Signal(self);
428 monitor_lock_.Unlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700429
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800430 // Handle the case where the thread was interrupted before we called wait().
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700431 if (self->interrupted_) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800432 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700433 } else {
434 // Wait for a notification or a timeout to occur.
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800435 if (why == kWaiting) {
Ian Rogersc604d732012-10-14 16:09:54 -0700436 self->wait_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700437 } else {
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800438 DCHECK(why == kTimedWaiting || why == kSleeping) << why;
Ian Rogersc604d732012-10-14 16:09:54 -0700439 self->wait_cond_->TimedWait(self, ms, ns);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700440 }
441 if (self->interrupted_) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800442 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700443 }
444 self->interrupted_ = false;
445 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700446 }
447
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700448 // Set self->status back to kRunnable, and self-suspend if needed.
449 self->TransitionFromSuspendedToRunnable();
Elliott Hughes5f791332011-09-15 17:45:30 -0700450
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800451 {
452 // We reset the thread's wait_monitor_ field after transitioning back to runnable so
453 // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
454 // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
455 // are waiting on "null".)
456 MutexLock mu(self, *self->wait_mutex_);
457 DCHECK(self->wait_monitor_ != NULL);
458 self->wait_monitor_ = NULL;
459 }
460
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700461 // Re-acquire the monitor and lock.
Elliott Hughes5f791332011-09-15 17:45:30 -0700462 Lock(self);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700463 monitor_lock_.Lock(self);
Ian Rogers81d425b2012-09-27 16:03:43 -0700464 self->wait_mutex_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700465
Elliott Hughes5f791332011-09-15 17:45:30 -0700466 /*
467 * We remove our thread from wait set after restoring the count
468 * and owner fields so the subroutine can check that the calling
469 * thread owns the monitor. Aside from that, the order of member
470 * updates is not order sensitive as we hold the pthread mutex.
471 */
472 owner_ = self;
Ian Rogers0399dde2012-06-06 17:09:28 -0700473 lock_count_ = prev_lock_count;
474 locking_method_ = saved_method;
475 locking_dex_pc_ = saved_dex_pc;
Elliott Hughes5f791332011-09-15 17:45:30 -0700476 RemoveFromWaitSet(self);
477
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800478 if (was_interrupted) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700479 /*
480 * We were interrupted while waiting, or somebody interrupted an
481 * un-interruptible thread earlier and we're bailing out immediately.
482 *
483 * The doc sayeth: "The interrupted status of the current thread is
484 * cleared when this exception is thrown."
485 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700486 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700487 MutexLock mu(self, *self->wait_mutex_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700488 self->interrupted_ = false;
489 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700490 if (interruptShouldThrow) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800491 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
492 self->ThrowNewException(throw_location, "Ljava/lang/InterruptedException;", NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700493 }
494 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700495 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700496}
497
498void Monitor::Notify(Thread* self) {
499 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700500 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700501 // Make sure that we hold the lock.
502 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800503 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700504 return;
505 }
506 // Signal the first waiting thread in the wait set.
507 while (wait_set_ != NULL) {
508 Thread* thread = wait_set_;
509 wait_set_ = thread->wait_next_;
510 thread->wait_next_ = NULL;
511
512 // Check to see if the thread is still waiting.
Ian Rogers50b35e22012-10-04 10:09:15 -0700513 MutexLock mu(self, *thread->wait_mutex_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700514 if (thread->wait_monitor_ != NULL) {
Ian Rogersc604d732012-10-14 16:09:54 -0700515 thread->wait_cond_->Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700516 return;
517 }
518 }
519}
520
521void Monitor::NotifyAll(Thread* self) {
522 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700523 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700524 // Make sure that we hold the lock.
525 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800526 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700527 return;
528 }
529 // Signal all threads in the wait set.
530 while (wait_set_ != NULL) {
531 Thread* thread = wait_set_;
532 wait_set_ = thread->wait_next_;
533 thread->wait_next_ = NULL;
534 thread->Notify();
535 }
536}
537
538/*
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700539 * Changes the shape of a monitor from thin to fat, preserving the internal lock state. The calling
540 * thread must own the lock or the owner must be suspended. There's a race with other threads
541 * inflating the lock and so the caller should read the monitor following the call.
Elliott Hughes5f791332011-09-15 17:45:30 -0700542 */
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700543void Monitor::Inflate(Thread* self, Thread* owner, mirror::Object* obj) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700544 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700545 DCHECK(owner != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700546 DCHECK(obj != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700547
548 // Allocate and acquire a new monitor.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700549 UniquePtr<Monitor> m(new Monitor(owner, obj));
550 if (m->Install(self)) {
551 VLOG(monitor) << "monitor: thread " << owner->GetThreadId()
552 << " created monitor " << m.get() << " for object " << obj;
553 Runtime::Current()->GetMonitorList()->Add(m.release());
554 }
555 CHECK_EQ(obj->GetLockWord().GetState(), LockWord::kFatLocked);
Elliott Hughes5f791332011-09-15 17:45:30 -0700556}
557
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800558void Monitor::MonitorEnter(Thread* self, mirror::Object* obj) {
Elliott Hughes4681c802011-09-25 18:04:37 -0700559 DCHECK(self != NULL);
560 DCHECK(obj != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700561 uint32_t thread_id = self->GetThreadId();
562 size_t contention_count = 0;
563
564 while (true) {
565 LockWord lock_word = obj->GetLockWord();
566 switch (lock_word.GetState()) {
567 case LockWord::kUnlocked: {
568 LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0));
569 if (obj->CasLockWord(lock_word, thin_locked)) {
570 return; // Success!
571 }
572 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -0700573 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700574 case LockWord::kThinLocked: {
575 uint32_t owner_thread_id = lock_word.ThinLockOwner();
576 if (owner_thread_id == thread_id) {
577 // We own the lock, increase the recursion count.
578 uint32_t new_count = lock_word.ThinLockCount() + 1;
579 if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
580 LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count));
581 obj->SetLockWord(thin_locked);
582 return; // Success!
Elliott Hughes5f791332011-09-15 17:45:30 -0700583 } else {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700584 // We'd overflow the recursion count, so inflate the monitor.
585 Inflate(self, self, obj);
586 }
587 } else {
588 // Contention.
589 contention_count++;
590 if (contention_count <= Runtime::Current()->GetMaxSpinsBeforeThinkLockInflation()) {
591 NanoSleep(1000); // Sleep for 1us and re-attempt.
592 } else {
593 contention_count = 0;
594 // Suspend the owner, inflate. First change to blocked and give up mutator_lock_.
595 ScopedThreadStateChange tsc(self, kBlocked);
596 bool timed_out;
597 ThreadList* thread_list = Runtime::Current()->GetThreadList();
598 if (lock_word == obj->GetLockWord()) { // If lock word hasn't changed.
599 Thread* owner = thread_list->SuspendThreadByThreadId(lock_word.ThinLockOwner(), false,
600 &timed_out);
601 if (owner != NULL) {
602 // We succeeded in suspending the thread, check the lock's status didn't change.
603 lock_word = obj->GetLockWord();
604 if (lock_word.GetState() == LockWord::kThinLocked &&
605 lock_word.ThinLockOwner() == owner_thread_id) {
606 // Go ahead and inflate the lock.
607 Inflate(self, owner, obj);
608 }
609 thread_list->Resume(owner, false);
Elliott Hughes5f791332011-09-15 17:45:30 -0700610 }
611 }
612 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700613 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700614 continue; // Start from the beginning.
Elliott Hughes5f791332011-09-15 17:45:30 -0700615 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700616 case LockWord::kFatLocked: {
617 Monitor* mon = lock_word.FatLockMonitor();
618 mon->Lock(self);
619 return; // Success!
620 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700621 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700622 }
623}
624
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800625bool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700626 DCHECK(self != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700627 DCHECK(obj != NULL);
628
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700629 LockWord lock_word = obj->GetLockWord();
630 switch (lock_word.GetState()) {
631 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800632 FailedUnlock(obj, self, NULL, NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700633 return false; // Failure.
634 case LockWord::kThinLocked: {
635 uint32_t thread_id = self->GetThreadId();
636 uint32_t owner_thread_id = lock_word.ThinLockOwner();
637 if (owner_thread_id != thread_id) {
638 // TODO: there's a race here with the owner dying while we unlock.
639 Thread* owner =
640 Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
641 FailedUnlock(obj, self, owner, NULL);
642 return false; // Failure.
643 } else {
644 // We own the lock, decrease the recursion count.
645 if (lock_word.ThinLockCount() != 0) {
646 uint32_t new_count = lock_word.ThinLockCount() - 1;
647 LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count));
648 obj->SetLockWord(thin_locked);
649 } else {
650 obj->SetLockWord(LockWord());
651 }
652 return true; // Success!
653 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700654 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700655 case LockWord::kFatLocked: {
656 Monitor* mon = lock_word.FatLockMonitor();
657 return mon->Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700658 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700659 default:
660 LOG(FATAL) << "Unreachable";
661 return false;
Elliott Hughes5f791332011-09-15 17:45:30 -0700662 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700663}
664
665/*
666 * Object.wait(). Also called for class init.
667 */
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800668void Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800669 bool interruptShouldThrow, ThreadState why) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700670 DCHECK(self != NULL);
671 DCHECK(obj != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700672
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700673 LockWord lock_word = obj->GetLockWord();
674 switch (lock_word.GetState()) {
675 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800676 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700677 return; // Failure.
678 case LockWord::kThinLocked: {
679 uint32_t thread_id = self->GetThreadId();
680 uint32_t owner_thread_id = lock_word.ThinLockOwner();
681 if (owner_thread_id != thread_id) {
682 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
683 return; // Failure.
684 } else {
685 // We own the lock, inflate to enqueue ourself on the Monitor.
686 Inflate(self, self, obj);
687 lock_word = obj->GetLockWord();
688 }
689 break;
Elliott Hughes5f791332011-09-15 17:45:30 -0700690 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700691 case LockWord::kFatLocked:
692 break; // Already set for a wait.
Elliott Hughes5f791332011-09-15 17:45:30 -0700693 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700694 Monitor* mon = lock_word.FatLockMonitor();
695 mon->Wait(self, ms, ns, interruptShouldThrow, why);
Elliott Hughes5f791332011-09-15 17:45:30 -0700696}
697
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700698void Monitor::InflateAndNotify(Thread* self, mirror::Object* obj, bool notify_all) {
699 DCHECK(self != NULL);
700 DCHECK(obj != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700701
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700702 LockWord lock_word = obj->GetLockWord();
703 switch (lock_word.GetState()) {
704 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800705 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700706 return; // Failure.
707 case LockWord::kThinLocked: {
708 uint32_t thread_id = self->GetThreadId();
709 uint32_t owner_thread_id = lock_word.ThinLockOwner();
710 if (owner_thread_id != thread_id) {
711 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
712 return; // Failure.
713 } else {
714 // We own the lock but there's no Monitor and therefore no waiters.
715 return; // Success.
716 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700717 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700718 case LockWord::kFatLocked: {
719 Monitor* mon = lock_word.FatLockMonitor();
720 if (notify_all) {
721 mon->NotifyAll(self);
722 } else {
723 mon->Notify(self);
724 }
725 return; // Success.
726 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700727 }
728}
729
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700730uint32_t Monitor::GetLockOwnerThreadId(mirror::Object* obj) {
731 DCHECK(obj != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700732
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700733 LockWord lock_word = obj->GetLockWord();
734 switch (lock_word.GetState()) {
735 case LockWord::kUnlocked:
736 return ThreadList::kInvalidThreadId;
737 case LockWord::kThinLocked:
738 return lock_word.ThinLockOwner();
739 case LockWord::kFatLocked: {
740 Monitor* mon = lock_word.FatLockMonitor();
741 return mon->GetOwnerThreadId();
Elliott Hughes5f791332011-09-15 17:45:30 -0700742 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700743 default:
744 LOG(FATAL) << "Unreachable";
745 return ThreadList::kInvalidThreadId;
Elliott Hughes5f791332011-09-15 17:45:30 -0700746 }
747}
748
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700749void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800750 ThreadState state = thread->GetState();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700751
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700752 int32_t object_identity_hashcode = 0;
753 uint32_t lock_owner = ThreadList::kInvalidThreadId;
754 std::string pretty_type;
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800755 if (state == kWaiting || state == kTimedWaiting || state == kSleeping) {
756 if (state == kSleeping) {
757 os << " - sleeping on ";
758 } else {
759 os << " - waiting on ";
760 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700761 {
Elliott Hughesf9501702013-01-11 11:22:27 -0800762 Thread* self = Thread::Current();
763 MutexLock mu(self, *thread->wait_mutex_);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800764 Monitor* monitor = thread->wait_monitor_;
765 if (monitor != NULL) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700766 mirror::Object* object = monitor->obj_;
767 object_identity_hashcode = object->IdentityHashCode();
768 pretty_type = PrettyTypeOf(object);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800769 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700770 }
Elliott Hughes34e06962012-04-09 13:55:55 -0700771 } else if (state == kBlocked) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700772 os << " - waiting to lock ";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700773 mirror::Object* object = thread->monitor_enter_object_;
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700774 if (object != NULL) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700775 object_identity_hashcode = object->IdentityHashCode();
776 lock_owner = object->GetLockOwnerThreadId();
777 pretty_type = PrettyTypeOf(object);
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700778 }
779 } else {
780 // We're not waiting on anything.
781 return;
782 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700783
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700784 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700785 os << StringPrintf("<0x%08x> (a %s)", object_identity_hashcode, pretty_type.c_str());
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700786
Elliott Hughesc5dc2ff2013-01-09 13:44:30 -0800787 // - waiting to lock <0x613f83d8> (a java.lang.Object) held by thread 5
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700788 if (lock_owner != ThreadList::kInvalidThreadId) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700789 os << " held by thread " << lock_owner;
790 }
791
792 os << "\n";
793}
794
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800795mirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800796 // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
797 // definition of contended that includes a monitor a thread is trying to enter...
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800798 mirror::Object* result = thread->monitor_enter_object_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700799 if (result == NULL) {
800 // ...but also a monitor that the thread is waiting on.
Elliott Hughesf9501702013-01-11 11:22:27 -0800801 MutexLock mu(Thread::Current(), *thread->wait_mutex_);
802 Monitor* monitor = thread->wait_monitor_;
803 if (monitor != NULL) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700804 result = monitor->GetObject();
Elliott Hughesf9501702013-01-11 11:22:27 -0800805 }
806 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700807 return result;
Elliott Hughesf9501702013-01-11 11:22:27 -0800808}
809
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800810void Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
811 void* callback_context) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700812 mirror::ArtMethod* m = stack_visitor->GetMethod();
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700813 CHECK(m != NULL);
814
815 // Native methods are an easy special case.
816 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
817 if (m->IsNative()) {
818 if (m->IsSynchronized()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800819 mirror::Object* jni_this = stack_visitor->GetCurrentSirt()->GetReference(0);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800820 callback(jni_this, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700821 }
822 return;
823 }
824
jeffhao61f916c2012-10-25 17:48:51 -0700825 // Proxy methods should not be synchronized.
826 if (m->IsProxyMethod()) {
827 CHECK(!m->IsSynchronized());
828 return;
829 }
830
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700831 // <clinit> is another special case. The runtime holds the class lock while calling <clinit>.
832 MethodHelper mh(m);
833 if (mh.IsClassInitializer()) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800834 callback(m->GetDeclaringClass(), callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700835 // Fall through because there might be synchronization in the user code too.
836 }
837
838 // Is there any reason to believe there's any synchronization in this method?
839 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -0700840 CHECK(code_item != NULL) << PrettyMethod(m);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700841 if (code_item->tries_size_ == 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700842 return; // No "tries" implies no synchronization, so no held locks to report.
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700843 }
844
Elliott Hughes80537bb2013-01-04 16:37:26 -0800845 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
846 // the locks held in this stack frame.
847 std::vector<uint32_t> monitor_enter_dex_pcs;
848 verifier::MethodVerifier::FindLocksAtDexPc(m, stack_visitor->GetDexPc(), monitor_enter_dex_pcs);
849 if (monitor_enter_dex_pcs.empty()) {
850 return;
851 }
852
Elliott Hughes80537bb2013-01-04 16:37:26 -0800853 for (size_t i = 0; i < monitor_enter_dex_pcs.size(); ++i) {
854 // The verifier works in terms of the dex pcs of the monitor-enter instructions.
855 // We want the registers used by those instructions (so we can read the values out of them).
856 uint32_t dex_pc = monitor_enter_dex_pcs[i];
857 uint16_t monitor_enter_instruction = code_item->insns_[dex_pc];
858
859 // Quick sanity check.
860 if ((monitor_enter_instruction & 0xff) != Instruction::MONITOR_ENTER) {
861 LOG(FATAL) << "expected monitor-enter @" << dex_pc << "; was "
862 << reinterpret_cast<void*>(monitor_enter_instruction);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700863 }
864
Elliott Hughes80537bb2013-01-04 16:37:26 -0800865 uint16_t monitor_register = ((monitor_enter_instruction >> 8) & 0xff);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800866 mirror::Object* o = reinterpret_cast<mirror::Object*>(stack_visitor->GetVReg(m, monitor_register,
867 kReferenceVReg));
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800868 callback(o, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700869 }
870}
871
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700872bool Monitor::IsValidLockWord(LockWord lock_word) {
873 switch (lock_word.GetState()) {
874 case LockWord::kUnlocked:
875 // Nothing to check.
876 return true;
877 case LockWord::kThinLocked:
878 // Basic sanity check of owner.
879 return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
880 case LockWord::kFatLocked: {
881 // Check the monitor appears in the monitor list.
882 Monitor* mon = lock_word.FatLockMonitor();
883 MonitorList* list = Runtime::Current()->GetMonitorList();
884 MutexLock mu(Thread::Current(), list->monitor_list_lock_);
885 for (Monitor* list_mon : list->list_) {
886 if (mon == list_mon) {
887 return true; // Found our monitor.
888 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700889 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700890 return false; // Fail - unowned monitor in an object.
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700891 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700892 default:
893 LOG(FATAL) << "Unreachable";
894 return false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700895 }
896}
897
Brian Carlstromea46f952013-07-30 01:26:50 -0700898void Monitor::TranslateLocation(const mirror::ArtMethod* method, uint32_t dex_pc,
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700899 const char** source_file, uint32_t* line_number) const {
jeffhao33dc7712011-11-09 17:54:24 -0800900 // If method is null, location is unknown
901 if (method == NULL) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700902 *source_file = "";
903 *line_number = 0;
jeffhao33dc7712011-11-09 17:54:24 -0800904 return;
905 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800906 MethodHelper mh(method);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700907 *source_file = mh.GetDeclaringClassSourceFile();
908 if (*source_file == NULL) {
909 *source_file = "";
Elliott Hughes12c51e32012-01-17 20:25:05 -0800910 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700911 *line_number = mh.GetLineNumFromDexPC(dex_pc);
912}
913
914uint32_t Monitor::GetOwnerThreadId() {
915 MutexLock mu(Thread::Current(), monitor_lock_);
916 Thread* owner = owner_;
917 if (owner != NULL) {
918 return owner->GetThreadId();
919 } else {
920 return ThreadList::kInvalidThreadId;
921 }
jeffhao33dc7712011-11-09 17:54:24 -0800922}
923
Mathieu Chartierc11d9b82013-09-19 10:01:59 -0700924MonitorList::MonitorList()
925 : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock"),
926 monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700927}
928
929MonitorList::~MonitorList() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700930 MutexLock mu(Thread::Current(), monitor_list_lock_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700931 STLDeleteElements(&list_);
932}
933
Mathieu Chartierc11d9b82013-09-19 10:01:59 -0700934void MonitorList::DisallowNewMonitors() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700935 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -0700936 allow_new_monitors_ = false;
937}
938
939void MonitorList::AllowNewMonitors() {
940 Thread* self = Thread::Current();
941 MutexLock mu(self, monitor_list_lock_);
942 allow_new_monitors_ = true;
943 monitor_add_condition_.Broadcast(self);
944}
945
946void MonitorList::Add(Monitor* m) {
947 Thread* self = Thread::Current();
948 MutexLock mu(self, monitor_list_lock_);
949 while (UNLIKELY(!allow_new_monitors_)) {
950 monitor_add_condition_.WaitHoldingLocks(self);
951 }
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700952 list_.push_front(m);
953}
954
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700955void MonitorList::SweepMonitorList(RootVisitor visitor, void* arg) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700956 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700957 for (auto it = list_.begin(); it != list_.end(); ) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700958 Monitor* m = *it;
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700959 mirror::Object* obj = m->GetObject();
960 mirror::Object* new_obj = visitor(obj, arg);
961 if (new_obj == nullptr) {
962 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
963 << m->GetObject();
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700964 delete m;
965 it = list_.erase(it);
966 } else {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700967 m->SetObject(new_obj);
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700968 ++it;
969 }
970 }
971}
972
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700973MonitorInfo::MonitorInfo(mirror::Object* obj) : owner_(NULL), entry_count_(0) {
974 DCHECK(obj != NULL);
975
976 LockWord lock_word = obj->GetLockWord();
977 switch (lock_word.GetState()) {
978 case LockWord::kUnlocked:
979 break;
980 case LockWord::kThinLocked:
981 owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
982 entry_count_ = 1 + lock_word.ThinLockCount();
983 // Thin locks have no waiters.
984 break;
985 case LockWord::kFatLocked: {
986 Monitor* mon = lock_word.FatLockMonitor();
987 owner_ = mon->owner_;
988 entry_count_ = 1 + mon->lock_count_;
989 for (Thread* waiter = mon->wait_set_; waiter != NULL; waiter = waiter->wait_next_) {
990 waiters_.push_back(waiter);
991 }
992 break;
Elliott Hughesf327e072013-01-09 16:01:26 -0800993 }
994 }
995}
996
Elliott Hughes5f791332011-09-15 17:45:30 -0700997} // namespace art