blob: 7cdccac095c1730b249b95a0984e1e156eca66e5 [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"
Elliott Hughes08fc03a2012-06-26 17:34:00 -070024#include "dex_instruction.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070025#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080026#include "object_utils.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070027#include "scoped_thread_state_change.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070028#include "thread.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070029#include "thread_list.h"
Elliott Hughes08fc03a2012-06-26 17:34:00 -070030#include "verifier/method_verifier.h"
Elliott Hughes044288f2012-06-25 14:46:39 -070031#include "well_known_classes.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070032
33namespace art {
34
35/*
36 * Every Object has a monitor associated with it, but not every Object is
37 * actually locked. Even the ones that are locked do not need a
38 * full-fledged monitor until a) there is actual contention or b) wait()
39 * is called on the Object.
40 *
41 * For Android, we have implemented a scheme similar to the one described
42 * in Bacon et al.'s "Thin locks: featherweight synchronization for Java"
43 * (ACM 1998). Things are even easier for us, though, because we have
44 * a full 32 bits to work with.
45 *
46 * The two states of an Object's lock are referred to as "thin" and
47 * "fat". A lock may transition from the "thin" state to the "fat"
48 * state and this transition is referred to as inflation. Once a lock
49 * has been inflated it remains in the "fat" state indefinitely.
50 *
51 * The lock value itself is stored in Object.lock. The LSB of the
52 * lock encodes its state. When cleared, the lock is in the "thin"
53 * state and its bits are formatted as follows:
54 *
55 * [31 ---- 19] [18 ---- 3] [2 ---- 1] [0]
56 * lock count thread id hash state 0
57 *
58 * When set, the lock is in the "fat" state and its bits are formatted
59 * as follows:
60 *
61 * [31 ---- 3] [2 ---- 1] [0]
62 * pointer hash state 1
63 *
64 * For an in-depth description of the mechanics of thin-vs-fat locking,
65 * read the paper referred to above.
Elliott Hughes54e7df12011-09-16 11:47:04 -070066 *
Elliott Hughes5f791332011-09-15 17:45:30 -070067 * Monitors provide:
68 * - mutually exclusive access to resources
69 * - a way for multiple threads to wait for notification
70 *
71 * In effect, they fill the role of both mutexes and condition variables.
72 *
73 * Only one thread can own the monitor at any time. There may be several
74 * threads waiting on it (the wait call unlocks it). One or more waiting
75 * threads may be getting interrupted or notified at any given time.
76 *
77 * TODO: the various members of monitor are not SMP-safe.
78 */
Elliott Hughes54e7df12011-09-16 11:47:04 -070079
80
81/*
82 * Monitor accessor. Extracts a monitor structure pointer from a fat
83 * lock. Performs no error checking.
84 */
85#define LW_MONITOR(x) \
Elliott Hughes398f64b2012-03-26 18:05:48 -070086 (reinterpret_cast<Monitor*>((x) & ~((LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT) | LW_SHAPE_MASK)))
Elliott Hughes54e7df12011-09-16 11:47:04 -070087
88/*
89 * Lock recursion count field. Contains a count of the number of times
90 * a lock has been recursively acquired.
91 */
92#define LW_LOCK_COUNT_MASK 0x1fff
93#define LW_LOCK_COUNT_SHIFT 19
94#define LW_LOCK_COUNT(x) (((x) >> LW_LOCK_COUNT_SHIFT) & LW_LOCK_COUNT_MASK)
95
Elliott Hughesfc861622011-10-17 17:57:47 -070096bool (*Monitor::is_sensitive_thread_hook_)() = NULL;
Elliott Hughesfc861622011-10-17 17:57:47 -070097uint32_t Monitor::lock_profiling_threshold_ = 0;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070098
Elliott Hughesfc861622011-10-17 17:57:47 -070099bool Monitor::IsSensitiveThread() {
100 if (is_sensitive_thread_hook_ != NULL) {
101 return (*is_sensitive_thread_hook_)();
102 }
103 return false;
104}
105
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800106void Monitor::Init(uint32_t lock_profiling_threshold, bool (*is_sensitive_thread_hook)()) {
Elliott Hughesfc861622011-10-17 17:57:47 -0700107 lock_profiling_threshold_ = lock_profiling_threshold;
108 is_sensitive_thread_hook_ = is_sensitive_thread_hook;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700109}
110
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700111Monitor::Monitor(Thread* owner, Object* obj)
112 : monitor_lock_("a monitor lock", kMonitorLock),
113 owner_(owner),
Elliott Hughes5f791332011-09-15 17:45:30 -0700114 lock_count_(0),
115 obj_(obj),
116 wait_set_(NULL),
jeffhao33dc7712011-11-09 17:54:24 -0800117 locking_method_(NULL),
Ian Rogers0399dde2012-06-06 17:09:28 -0700118 locking_dex_pc_(0) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700119 monitor_lock_.Lock(owner);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700120 // Propagate the lock state.
121 uint32_t thin = *obj->GetRawLockWordAddress();
122 lock_count_ = LW_LOCK_COUNT(thin);
123 thin &= LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT;
124 thin |= reinterpret_cast<uint32_t>(this) | LW_SHAPE_FAT;
125 // Publish the updated lock word.
126 android_atomic_release_store(thin, obj->GetRawLockWordAddress());
127 // Lock profiling.
128 if (lock_profiling_threshold_ != 0) {
129 locking_method_ = owner->GetCurrentMethod(&locking_dex_pc_);
130 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700131}
132
133Monitor::~Monitor() {
134 DCHECK(obj_ != NULL);
135 DCHECK_EQ(LW_SHAPE(*obj_->GetRawLockWordAddress()), LW_SHAPE_FAT);
Elliott Hughes5f791332011-09-15 17:45:30 -0700136}
137
138/*
139 * Links a thread into a monitor's wait set. The monitor lock must be
140 * held by the caller of this routine.
141 */
142void Monitor::AppendToWaitSet(Thread* thread) {
143 DCHECK(owner_ == Thread::Current());
144 DCHECK(thread != NULL);
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700145 DCHECK(thread->wait_next_ == NULL) << thread->wait_next_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700146 if (wait_set_ == NULL) {
147 wait_set_ = thread;
148 return;
149 }
150
151 // push_back.
152 Thread* t = wait_set_;
153 while (t->wait_next_ != NULL) {
154 t = t->wait_next_;
155 }
156 t->wait_next_ = thread;
157}
158
159/*
160 * Unlinks a thread from a monitor's wait set. The monitor lock must
161 * be held by the caller of this routine.
162 */
163void Monitor::RemoveFromWaitSet(Thread *thread) {
164 DCHECK(owner_ == Thread::Current());
165 DCHECK(thread != NULL);
166 if (wait_set_ == NULL) {
167 return;
168 }
169 if (wait_set_ == thread) {
170 wait_set_ = thread->wait_next_;
171 thread->wait_next_ = NULL;
172 return;
173 }
174
175 Thread* t = wait_set_;
176 while (t->wait_next_ != NULL) {
177 if (t->wait_next_ == thread) {
178 t->wait_next_ = thread->wait_next_;
179 thread->wait_next_ = NULL;
180 return;
181 }
182 t = t->wait_next_;
183 }
184}
185
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700186Object* Monitor::GetObject() {
187 return obj_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700188}
189
Elliott Hughes5f791332011-09-15 17:45:30 -0700190void Monitor::Lock(Thread* self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700191 if (owner_ == self) {
192 lock_count_++;
193 return;
194 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700195
Ian Rogers81d425b2012-09-27 16:03:43 -0700196 if (!monitor_lock_.TryLock(self)) {
Mathieu Chartier2542d662012-06-21 17:14:11 -0700197 uint64_t waitStart = 0;
198 uint64_t waitEnd = 0;
Elliott Hughesfc861622011-10-17 17:57:47 -0700199 uint32_t wait_threshold = lock_profiling_threshold_;
Mathieu Chartier66f19252012-09-18 08:57:04 -0700200 const AbstractMethod* current_locking_method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700201 uint32_t current_locking_dex_pc = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700202 {
Elliott Hughes34e06962012-04-09 13:55:55 -0700203 ScopedThreadStateChange tsc(self, kBlocked);
Elliott Hughesfc861622011-10-17 17:57:47 -0700204 if (wait_threshold != 0) {
205 waitStart = NanoTime() / 1000;
206 }
jeffhao33dc7712011-11-09 17:54:24 -0800207 current_locking_method = locking_method_;
Ian Rogers0399dde2012-06-06 17:09:28 -0700208 current_locking_dex_pc = locking_dex_pc_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700209
Ian Rogers81d425b2012-09-27 16:03:43 -0700210 monitor_lock_.Lock(self);
Elliott Hughesfc861622011-10-17 17:57:47 -0700211 if (wait_threshold != 0) {
212 waitEnd = NanoTime() / 1000;
213 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700214 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700215
216 if (wait_threshold != 0) {
217 uint64_t wait_ms = (waitEnd - waitStart) / 1000;
218 uint32_t sample_percent;
219 if (wait_ms >= wait_threshold) {
220 sample_percent = 100;
221 } else {
222 sample_percent = 100 * wait_ms / wait_threshold;
223 }
224 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
jeffhao33dc7712011-11-09 17:54:24 -0800225 const char* current_locking_filename;
226 uint32_t current_locking_line_number;
Ian Rogers0399dde2012-06-06 17:09:28 -0700227 TranslateLocation(current_locking_method, current_locking_dex_pc,
jeffhao33dc7712011-11-09 17:54:24 -0800228 current_locking_filename, current_locking_line_number);
229 LogContentionEvent(self, wait_ms, sample_percent, current_locking_filename, current_locking_line_number);
Elliott Hughesfc861622011-10-17 17:57:47 -0700230 }
231 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700232 }
233 owner_ = self;
234 DCHECK_EQ(lock_count_, 0);
235
236 // When debugging, save the current monitor holder for future
237 // acquisition failures to use in sampled logging.
Elliott Hughesfc861622011-10-17 17:57:47 -0700238 if (lock_profiling_threshold_ != 0) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700239 locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
Elliott Hughesfc861622011-10-17 17:57:47 -0700240 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700241}
242
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800243static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
244 __attribute__((format(printf, 1, 2)));
245
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700246static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700247 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800248 va_list args;
249 va_start(args, fmt);
250 Thread::Current()->ThrowNewExceptionV("Ljava/lang/IllegalMonitorStateException;", fmt, args);
Brian Carlstrom64277f32012-03-26 23:53:34 -0700251 if (!Runtime::Current()->IsStarted()) {
252 std::ostringstream ss;
253 Thread::Current()->Dump(ss);
254 std::string str(ss.str());
255 LOG(ERROR) << "IllegalMonitorStateException: " << str;
256 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800257 va_end(args);
258}
259
Elliott Hughesd4237412012-02-21 11:24:45 -0800260static std::string ThreadToString(Thread* thread) {
261 if (thread == NULL) {
262 return "NULL";
263 }
264 std::ostringstream oss;
265 // TODO: alternatively, we could just return the thread's name.
266 oss << *thread;
267 return oss.str();
268}
269
Elliott Hughesffb465f2012-03-01 18:46:05 -0800270void Monitor::FailedUnlock(Object* o, Thread* expected_owner, Thread* found_owner,
271 Monitor* monitor) {
272 Thread* current_owner = NULL;
273 std::string current_owner_string;
274 std::string expected_owner_string;
275 std::string found_owner_string;
276 {
277 // TODO: isn't this too late to prevent threads from disappearing?
278 // Acquire thread list lock so threads won't disappear from under us.
Ian Rogers50b35e22012-10-04 10:09:15 -0700279 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Elliott Hughesffb465f2012-03-01 18:46:05 -0800280 // Re-read owner now that we hold lock.
281 current_owner = (monitor != NULL) ? monitor->owner_ : NULL;
282 // Get short descriptions of the threads involved.
283 current_owner_string = ThreadToString(current_owner);
284 expected_owner_string = ThreadToString(expected_owner);
285 found_owner_string = ThreadToString(found_owner);
286 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800287 if (current_owner == NULL) {
288 if (found_owner == NULL) {
289 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
290 " on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800291 PrettyTypeOf(o).c_str(),
292 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800293 } else {
294 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800295 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
296 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800297 found_owner_string.c_str(),
298 PrettyTypeOf(o).c_str(),
299 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800300 }
301 } else {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800302 if (found_owner == NULL) {
303 // Race: originally there was no owner, there is now
304 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
305 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800306 current_owner_string.c_str(),
307 PrettyTypeOf(o).c_str(),
308 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800309 } else {
310 if (found_owner != current_owner) {
311 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800312 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
313 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800314 found_owner_string.c_str(),
315 current_owner_string.c_str(),
316 PrettyTypeOf(o).c_str(),
317 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800318 } else {
319 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
320 " on thread '%s",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800321 current_owner_string.c_str(),
322 PrettyTypeOf(o).c_str(),
323 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800324 }
325 }
326 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700327}
328
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700329bool Monitor::Unlock(Thread* self, bool for_wait) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700330 DCHECK(self != NULL);
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800331 Thread* owner = owner_;
332 if (owner == self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700333 // We own the monitor, so nobody else can be in here.
334 if (lock_count_ == 0) {
335 owner_ = NULL;
jeffhao33dc7712011-11-09 17:54:24 -0800336 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700337 locking_dex_pc_ = 0;
Ian Rogers81d425b2012-09-27 16:03:43 -0700338 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700339 } else {
340 --lock_count_;
341 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700342 } else if (for_wait) {
343 // Wait should have already cleared the fields.
344 DCHECK_EQ(lock_count_, 0);
345 DCHECK(owner == NULL);
346 DCHECK(locking_method_ == NULL);
347 DCHECK_EQ(locking_dex_pc_, 0u);
Ian Rogers81d425b2012-09-27 16:03:43 -0700348 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700349 } else {
350 // We don't own this, so we're not allowed to unlock it.
351 // The JNI spec says that we should throw IllegalMonitorStateException
352 // in this case.
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800353 FailedUnlock(obj_, self, owner, this);
Elliott Hughes5f791332011-09-15 17:45:30 -0700354 return false;
355 }
356 return true;
357}
358
Elliott Hughes5f791332011-09-15 17:45:30 -0700359/*
360 * Wait on a monitor until timeout, interrupt, or notification. Used for
361 * Object.wait() and (somewhat indirectly) Thread.sleep() and Thread.join().
362 *
363 * If another thread calls Thread.interrupt(), we throw InterruptedException
364 * and return immediately if one of the following are true:
365 * - blocked in wait(), wait(long), or wait(long, int) methods of Object
366 * - blocked in join(), join(long), or join(long, int) methods of Thread
367 * - blocked in sleep(long), or sleep(long, int) methods of Thread
368 * Otherwise, we set the "interrupted" flag.
369 *
370 * Checks to make sure that "ns" is in the range 0-999999
371 * (i.e. fractions of a millisecond) and throws the appropriate
372 * exception if it isn't.
373 *
374 * The spec allows "spurious wakeups", and recommends that all code using
375 * Object.wait() do so in a loop. This appears to derive from concerns
376 * about pthread_cond_wait() on multiprocessor systems. Some commentary
377 * on the web casts doubt on whether these can/should occur.
378 *
379 * Since we're allowed to wake up "early", we clamp extremely long durations
380 * to return at the end of the 32-bit time epoch.
381 */
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800382void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
383 bool interruptShouldThrow, ThreadState why) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700384 DCHECK(self != NULL);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800385 DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
386 DCHECK(why != kWaiting || (ms == 0 && ns == 0));
Elliott Hughes5f791332011-09-15 17:45:30 -0700387
388 // Make sure that we hold the lock.
389 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800390 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700391 return;
392 }
Ian Rogers50b35e22012-10-04 10:09:15 -0700393 monitor_lock_.AssertHeld(self);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800394
395 WaitWithLock(self, ms, ns, interruptShouldThrow, why);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700396}
Elliott Hughes5f791332011-09-15 17:45:30 -0700397
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800398void Monitor::WaitWithLock(Thread* self, int64_t ms, int32_t ns,
399 bool interruptShouldThrow, ThreadState why) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700400 // Enforce the timeout range.
401 if (ms < 0 || ns < 0 || ns > 999999) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700402 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
Elliott Hughes5f791332011-09-15 17:45:30 -0700403 "timeout arguments out of range: ms=%lld ns=%d", ms, ns);
404 return;
405 }
406
Elliott Hughes5f791332011-09-15 17:45:30 -0700407 /*
408 * Add ourselves to the set of threads waiting on this monitor, and
409 * release our hold. We need to let it go even if we're a few levels
410 * deep in a recursive lock, and we need to restore that later.
411 *
412 * We append to the wait set ahead of clearing the count and owner
413 * fields so the subroutine can check that the calling thread owns
414 * the monitor. Aside from that, the order of member updates is
415 * not order sensitive as we hold the pthread mutex.
416 */
417 AppendToWaitSet(self);
Ian Rogers0399dde2012-06-06 17:09:28 -0700418 int prev_lock_count = lock_count_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700419 lock_count_ = 0;
420 owner_ = NULL;
Mathieu Chartier66f19252012-09-18 08:57:04 -0700421 const AbstractMethod* saved_method = locking_method_;
jeffhao33dc7712011-11-09 17:54:24 -0800422 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700423 uintptr_t saved_dex_pc = locking_dex_pc_;
424 locking_dex_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700425
426 /*
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800427 * Update thread state. If the GC wakes up, it'll ignore us, knowing
Elliott Hughes5f791332011-09-15 17:45:30 -0700428 * that we won't touch any references in this state, and we'll check
429 * our suspend mode before we transition out.
430 */
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800431 self->TransitionFromRunnableToSuspended(why);
Elliott Hughes5f791332011-09-15 17:45:30 -0700432
Elliott Hughes5f791332011-09-15 17:45:30 -0700433 bool wasInterrupted = false;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700434 {
435 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
Ian Rogers50b35e22012-10-04 10:09:15 -0700436 MutexLock mu(self, *self->wait_mutex_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700437
438 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
439 // non-NULL a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
440 // up.
441 DCHECK(self->wait_monitor_ == NULL);
442 self->wait_monitor_ = this;
443
444 // Release the monitor lock.
445 Unlock(self, true);
446
447 /*
448 * Handle the case where the thread was interrupted before we called
449 * wait().
450 */
451 if (self->interrupted_) {
452 wasInterrupted = true;
453 } else {
454 // Wait for a notification or a timeout to occur.
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800455 if (why == kWaiting) {
Ian Rogersc604d732012-10-14 16:09:54 -0700456 self->wait_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700457 } else {
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800458 DCHECK(why == kTimedWaiting || why == kSleeping) << why;
Ian Rogersc604d732012-10-14 16:09:54 -0700459 self->wait_cond_->TimedWait(self, ms, ns);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700460 }
461 if (self->interrupted_) {
462 wasInterrupted = true;
463 }
464 self->interrupted_ = false;
465 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700466 self->wait_monitor_ = NULL;
Elliott Hughes5f791332011-09-15 17:45:30 -0700467 }
468
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700469 // Set self->status back to kRunnable, and self-suspend if needed.
470 self->TransitionFromSuspendedToRunnable();
Elliott Hughes5f791332011-09-15 17:45:30 -0700471
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700472 // Re-acquire the monitor lock.
Elliott Hughes5f791332011-09-15 17:45:30 -0700473 Lock(self);
474
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700475
Ian Rogers81d425b2012-09-27 16:03:43 -0700476 self->wait_mutex_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700477
Elliott Hughes5f791332011-09-15 17:45:30 -0700478 /*
479 * We remove our thread from wait set after restoring the count
480 * and owner fields so the subroutine can check that the calling
481 * thread owns the monitor. Aside from that, the order of member
482 * updates is not order sensitive as we hold the pthread mutex.
483 */
484 owner_ = self;
Ian Rogers0399dde2012-06-06 17:09:28 -0700485 lock_count_ = prev_lock_count;
486 locking_method_ = saved_method;
487 locking_dex_pc_ = saved_dex_pc;
Elliott Hughes5f791332011-09-15 17:45:30 -0700488 RemoveFromWaitSet(self);
489
Elliott Hughes5f791332011-09-15 17:45:30 -0700490 if (wasInterrupted) {
491 /*
492 * We were interrupted while waiting, or somebody interrupted an
493 * un-interruptible thread earlier and we're bailing out immediately.
494 *
495 * The doc sayeth: "The interrupted status of the current thread is
496 * cleared when this exception is thrown."
497 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700498 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700499 MutexLock mu(self, *self->wait_mutex_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700500 self->interrupted_ = false;
501 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700502 if (interruptShouldThrow) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700503 Thread::Current()->ThrowNewException("Ljava/lang/InterruptedException;", NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700504 }
505 }
506}
507
508void Monitor::Notify(Thread* self) {
509 DCHECK(self != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700510 // Make sure that we hold the lock.
511 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800512 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700513 return;
514 }
Ian Rogers50b35e22012-10-04 10:09:15 -0700515 monitor_lock_.AssertHeld(self);
516 NotifyWithLock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700517}
518
Ian Rogers50b35e22012-10-04 10:09:15 -0700519void Monitor::NotifyWithLock(Thread* self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700520 // Signal the first waiting thread in the wait set.
521 while (wait_set_ != NULL) {
522 Thread* thread = wait_set_;
523 wait_set_ = thread->wait_next_;
524 thread->wait_next_ = NULL;
525
526 // Check to see if the thread is still waiting.
Ian Rogers50b35e22012-10-04 10:09:15 -0700527 MutexLock mu(self, *thread->wait_mutex_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700528 if (thread->wait_monitor_ != NULL) {
Ian Rogersc604d732012-10-14 16:09:54 -0700529 thread->wait_cond_->Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700530 return;
531 }
532 }
533}
534
535void Monitor::NotifyAll(Thread* self) {
536 DCHECK(self != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700537 // Make sure that we hold the lock.
538 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800539 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700540 return;
541 }
Ian Rogers50b35e22012-10-04 10:09:15 -0700542 monitor_lock_.AssertHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700543 NotifyAllWithLock();
544}
545
546void Monitor::NotifyAllWithLock() {
Elliott Hughes5f791332011-09-15 17:45:30 -0700547 // Signal all threads in the wait set.
548 while (wait_set_ != NULL) {
549 Thread* thread = wait_set_;
550 wait_set_ = thread->wait_next_;
551 thread->wait_next_ = NULL;
552 thread->Notify();
553 }
554}
555
556/*
557 * Changes the shape of a monitor from thin to fat, preserving the
558 * internal lock state. The calling thread must own the lock.
559 */
560void Monitor::Inflate(Thread* self, Object* obj) {
561 DCHECK(self != NULL);
562 DCHECK(obj != NULL);
563 DCHECK_EQ(LW_SHAPE(*obj->GetRawLockWordAddress()), LW_SHAPE_THIN);
Elliott Hughesf8e01272011-10-17 11:29:05 -0700564 DCHECK_EQ(LW_LOCK_OWNER(*obj->GetRawLockWordAddress()), static_cast<int32_t>(self->GetThinLockId()));
Elliott Hughes5f791332011-09-15 17:45:30 -0700565
566 // Allocate and acquire a new monitor.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700567 Monitor* m = new Monitor(self, obj);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800568 VLOG(monitor) << "monitor: thread " << self->GetThinLockId()
569 << " created monitor " << m << " for object " << obj;
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700570 Runtime::Current()->GetMonitorList()->Add(m);
Elliott Hughes5f791332011-09-15 17:45:30 -0700571}
572
573void Monitor::MonitorEnter(Thread* self, Object* obj) {
574 volatile int32_t* thinp = obj->GetRawLockWordAddress();
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700575 timespec tm;
Elliott Hughes398f64b2012-03-26 18:05:48 -0700576 uint32_t sleepDelayNs;
577 uint32_t minSleepDelayNs = 1000000; /* 1 millisecond */
578 uint32_t maxSleepDelayNs = 1000000000; /* 1 second */
Elliott Hughesf8e01272011-10-17 11:29:05 -0700579 uint32_t thin, newThin;
Elliott Hughes5f791332011-09-15 17:45:30 -0700580
Elliott Hughes4681c802011-09-25 18:04:37 -0700581 DCHECK(self != NULL);
582 DCHECK(obj != NULL);
Elliott Hughesf8e01272011-10-17 11:29:05 -0700583 uint32_t threadId = self->GetThinLockId();
Elliott Hughesa21039c2012-06-21 12:09:25 -0700584 retry:
Elliott Hughes5f791332011-09-15 17:45:30 -0700585 thin = *thinp;
586 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
587 /*
588 * The lock is a thin lock. The owner field is used to
589 * determine the acquire method, ordered by cost.
590 */
591 if (LW_LOCK_OWNER(thin) == threadId) {
592 /*
593 * The calling thread owns the lock. Increment the
594 * value of the recursion count field.
595 */
596 *thinp += 1 << LW_LOCK_COUNT_SHIFT;
597 if (LW_LOCK_COUNT(*thinp) == LW_LOCK_COUNT_MASK) {
598 /*
599 * The reacquisition limit has been reached. Inflate
600 * the lock so the next acquire will not overflow the
601 * recursion count field.
602 */
603 Inflate(self, obj);
604 }
605 } else if (LW_LOCK_OWNER(thin) == 0) {
Elliott Hughes81ff3182012-03-23 20:35:56 -0700606 // The lock is unowned. Install the thread id of the calling thread into the owner field.
607 // This is the common case: compiled code will have tried this before calling back into
608 // the runtime.
Elliott Hughes5f791332011-09-15 17:45:30 -0700609 newThin = thin | (threadId << LW_LOCK_OWNER_SHIFT);
610 if (android_atomic_acquire_cas(thin, newThin, thinp) != 0) {
611 // The acquire failed. Try again.
612 goto retry;
613 }
614 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800615 VLOG(monitor) << StringPrintf("monitor: thread %d spin on lock %p (a %s) owned by %d",
Elliott Hughes81ff3182012-03-23 20:35:56 -0700616 threadId, thinp, PrettyTypeOf(obj).c_str(), LW_LOCK_OWNER(thin));
617 // The lock is owned by another thread. Notify the runtime that we are about to wait.
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700618 self->monitor_enter_object_ = obj;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700619 self->TransitionFromRunnableToSuspended(kBlocked);
Elliott Hughes5f791332011-09-15 17:45:30 -0700620 // Spin until the thin lock is released or inflated.
621 sleepDelayNs = 0;
622 for (;;) {
623 thin = *thinp;
624 // Check the shape of the lock word. Another thread
625 // may have inflated the lock while we were waiting.
626 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
627 if (LW_LOCK_OWNER(thin) == 0) {
628 // The lock has been released. Install the thread id of the
629 // calling thread into the owner field.
630 newThin = thin | (threadId << LW_LOCK_OWNER_SHIFT);
631 if (android_atomic_acquire_cas(thin, newThin, thinp) == 0) {
632 // The acquire succeed. Break out of the loop and proceed to inflate the lock.
633 break;
634 }
635 } else {
636 // The lock has not been released. Yield so the owning thread can run.
637 if (sleepDelayNs == 0) {
638 sched_yield();
639 sleepDelayNs = minSleepDelayNs;
640 } else {
641 tm.tv_sec = 0;
642 tm.tv_nsec = sleepDelayNs;
643 nanosleep(&tm, NULL);
644 // Prepare the next delay value. Wrap to avoid once a second polls for eternity.
645 if (sleepDelayNs < maxSleepDelayNs / 2) {
646 sleepDelayNs *= 2;
647 } else {
648 sleepDelayNs = minSleepDelayNs;
649 }
650 }
651 }
652 } else {
Elliott Hughes81ff3182012-03-23 20:35:56 -0700653 // The thin lock was inflated by another thread. Let the runtime know we are no longer
Elliott Hughes5f791332011-09-15 17:45:30 -0700654 // waiting and try again.
Elliott Hughes398f64b2012-03-26 18:05:48 -0700655 VLOG(monitor) << StringPrintf("monitor: thread %d found lock %p surprise-fattened by another thread", threadId, thinp);
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700656 self->monitor_enter_object_ = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700657 self->TransitionFromSuspendedToRunnable();
Elliott Hughes5f791332011-09-15 17:45:30 -0700658 goto retry;
659 }
660 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800661 VLOG(monitor) << StringPrintf("monitor: thread %d spin on lock %p done", threadId, thinp);
Elliott Hughes81ff3182012-03-23 20:35:56 -0700662 // We have acquired the thin lock. Let the runtime know that we are no longer waiting.
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700663 self->monitor_enter_object_ = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700664 self->TransitionFromSuspendedToRunnable();
Elliott Hughes5f791332011-09-15 17:45:30 -0700665 // Fatten the lock.
666 Inflate(self, obj);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800667 VLOG(monitor) << StringPrintf("monitor: thread %d fattened lock %p", threadId, thinp);
Elliott Hughes5f791332011-09-15 17:45:30 -0700668 }
669 } else {
670 // The lock is a fat lock.
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800671 VLOG(monitor) << StringPrintf("monitor: thread %d locking fat lock %p (%p) %p on a %s",
Elliott Hughes398f64b2012-03-26 18:05:48 -0700672 threadId, thinp, LW_MONITOR(*thinp),
673 reinterpret_cast<void*>(*thinp), PrettyTypeOf(obj).c_str());
Elliott Hughes5f791332011-09-15 17:45:30 -0700674 DCHECK(LW_MONITOR(*thinp) != NULL);
675 LW_MONITOR(*thinp)->Lock(self);
676 }
677}
678
679bool Monitor::MonitorExit(Thread* self, Object* obj) {
680 volatile int32_t* thinp = obj->GetRawLockWordAddress();
681
682 DCHECK(self != NULL);
Elliott Hughes34e06962012-04-09 13:55:55 -0700683 //DCHECK_EQ(self->GetState(), kRunnable);
Elliott Hughes5f791332011-09-15 17:45:30 -0700684 DCHECK(obj != NULL);
685
686 /*
687 * Cache the lock word as its value can change while we are
688 * examining its state.
689 */
690 uint32_t thin = *thinp;
691 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
692 /*
693 * The lock is thin. We must ensure that the lock is owned
694 * by the given thread before unlocking it.
695 */
Elliott Hughesf8e01272011-10-17 11:29:05 -0700696 if (LW_LOCK_OWNER(thin) == self->GetThinLockId()) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700697 /*
698 * We are the lock owner. It is safe to update the lock
699 * without CAS as lock ownership guards the lock itself.
700 */
701 if (LW_LOCK_COUNT(thin) == 0) {
702 /*
703 * The lock was not recursively acquired, the common
704 * case. Unlock by clearing all bits except for the
705 * hash state.
706 */
707 thin &= (LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT);
708 android_atomic_release_store(thin, thinp);
709 } else {
710 /*
711 * The object was recursively acquired. Decrement the
712 * lock recursion count field.
713 */
714 *thinp -= 1 << LW_LOCK_COUNT_SHIFT;
715 }
716 } else {
717 /*
718 * We do not own the lock. The JVM spec requires that we
719 * throw an exception in this case.
720 */
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800721 FailedUnlock(obj, self, NULL, NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700722 return false;
723 }
724 } else {
725 /*
726 * The lock is fat. We must check to see if Unlock has
727 * raised any exceptions before continuing.
728 */
729 DCHECK(LW_MONITOR(*thinp) != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700730 if (!LW_MONITOR(*thinp)->Unlock(self, false)) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700731 // An exception has been raised. Do not fall through.
732 return false;
733 }
734 }
735 return true;
736}
737
738/*
739 * Object.wait(). Also called for class init.
740 */
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800741void Monitor::Wait(Thread* self, Object *obj, int64_t ms, int32_t ns,
742 bool interruptShouldThrow, ThreadState why) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700743 volatile int32_t* thinp = obj->GetRawLockWordAddress();
744
745 // If the lock is still thin, we need to fatten it.
746 uint32_t thin = *thinp;
747 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
748 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700749 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800750 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700751 return;
752 }
753
754 /* This thread holds the lock. We need to fatten the lock
755 * so 'self' can block on it. Don't update the object lock
756 * field yet, because 'self' needs to acquire the lock before
757 * any other thread gets a chance.
758 */
759 Inflate(self, obj);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800760 VLOG(monitor) << StringPrintf("monitor: thread %d fattened lock %p by wait()", self->GetThinLockId(), thinp);
Elliott Hughes5f791332011-09-15 17:45:30 -0700761 }
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800762 LW_MONITOR(*thinp)->Wait(self, ms, ns, interruptShouldThrow, why);
Elliott Hughes5f791332011-09-15 17:45:30 -0700763}
764
765void Monitor::Notify(Thread* self, Object *obj) {
766 uint32_t thin = *obj->GetRawLockWordAddress();
767
768 // If the lock is still thin, there aren't any waiters;
769 // waiting on an object forces lock fattening.
770 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
771 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700772 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800773 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700774 return;
775 }
776 // no-op; there are no waiters to notify.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700777 Inflate(self, obj);
Elliott Hughes5f791332011-09-15 17:45:30 -0700778 } else {
779 // It's a fat lock.
780 LW_MONITOR(thin)->Notify(self);
781 }
782}
783
784void Monitor::NotifyAll(Thread* self, Object *obj) {
785 uint32_t thin = *obj->GetRawLockWordAddress();
786
787 // If the lock is still thin, there aren't any waiters;
788 // waiting on an object forces lock fattening.
789 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
790 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700791 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800792 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700793 return;
794 }
795 // no-op; there are no waiters to notify.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700796 Inflate(self, obj);
Elliott Hughes5f791332011-09-15 17:45:30 -0700797 } else {
798 // It's a fat lock.
799 LW_MONITOR(thin)->NotifyAll(self);
800 }
801}
802
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -0700803uint32_t Monitor::GetThinLockId(uint32_t raw_lock_word) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700804 if (LW_SHAPE(raw_lock_word) == LW_SHAPE_THIN) {
805 return LW_LOCK_OWNER(raw_lock_word);
806 } else {
807 Thread* owner = LW_MONITOR(raw_lock_word)->owner_;
808 return owner ? owner->GetThinLockId() : 0;
809 }
810}
811
Elliott Hughes044288f2012-06-25 14:46:39 -0700812static uint32_t LockOwnerFromThreadLock(Object* thread_lock) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700813 ScopedObjectAccess soa(Thread::Current());
Ian Rogers365c1022012-06-22 15:05:28 -0700814 if (thread_lock == NULL ||
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700815 thread_lock->GetClass() != soa.Decode<Class*>(WellKnownClasses::java_lang_ThreadLock)) {
Elliott Hughes044288f2012-06-25 14:46:39 -0700816 return ThreadList::kInvalidId;
817 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700818 Field* thread_field = soa.DecodeField(WellKnownClasses::java_lang_ThreadLock_thread);
Elliott Hughes044288f2012-06-25 14:46:39 -0700819 Object* managed_thread = thread_field->GetObject(thread_lock);
820 if (managed_thread == NULL) {
821 return ThreadList::kInvalidId;
822 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700823 Field* vmData_field = soa.DecodeField(WellKnownClasses::java_lang_Thread_vmData);
Elliott Hughes044288f2012-06-25 14:46:39 -0700824 uintptr_t vmData = static_cast<uintptr_t>(vmData_field->GetInt(managed_thread));
825 Thread* thread = reinterpret_cast<Thread*>(vmData);
826 if (thread == NULL) {
827 return ThreadList::kInvalidId;
828 }
829 return thread->GetThinLockId();
830}
831
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700832void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700833 ThreadState state;
Ian Rogers50b35e22012-10-04 10:09:15 -0700834 state = thread->GetState();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700835
836 Object* object = NULL;
837 uint32_t lock_owner = ThreadList::kInvalidId;
Elliott Hughes34e06962012-04-09 13:55:55 -0700838 if (state == kWaiting || state == kTimedWaiting) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700839 os << " - waiting on ";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700840 Monitor* monitor;
841 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700842 MutexLock mu(Thread::Current(), *thread->wait_mutex_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700843 monitor = thread->wait_monitor_;
844 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700845 if (monitor != NULL) {
846 object = monitor->obj_;
847 }
Elliott Hughes044288f2012-06-25 14:46:39 -0700848 lock_owner = LockOwnerFromThreadLock(object);
Elliott Hughes34e06962012-04-09 13:55:55 -0700849 } else if (state == kBlocked) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700850 os << " - waiting to lock ";
851 object = thread->monitor_enter_object_;
852 if (object != NULL) {
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -0700853 lock_owner = object->GetThinLockId();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700854 }
855 } else {
856 // We're not waiting on anything.
857 return;
858 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700859
860 // - waiting on <0x613f83d8> (a java.lang.ThreadLock) held by thread 5
861 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700862 os << "<" << object << "> (a " << PrettyTypeOf(object) << ")";
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700863
864 if (lock_owner != ThreadList::kInvalidId) {
865 os << " held by thread " << lock_owner;
866 }
867
868 os << "\n";
869}
870
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700871static void DumpLockedObject(std::ostream& os, Object* o)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700872 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700873 os << " - locked <" << o << "> (a " << PrettyTypeOf(o) << ")\n";
874}
875
876void Monitor::DescribeLocks(std::ostream& os, StackVisitor* stack_visitor) {
Mathieu Chartier66f19252012-09-18 08:57:04 -0700877 AbstractMethod* m = stack_visitor->GetMethod();
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700878 CHECK(m != NULL);
879
880 // Native methods are an easy special case.
881 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
882 if (m->IsNative()) {
883 if (m->IsSynchronized()) {
884 Object* jni_this = stack_visitor->GetCurrentSirt()->GetReference(0);
885 DumpLockedObject(os, jni_this);
886 }
887 return;
888 }
889
jeffhao61f916c2012-10-25 17:48:51 -0700890 // Proxy methods should not be synchronized.
891 if (m->IsProxyMethod()) {
892 CHECK(!m->IsSynchronized());
893 return;
894 }
895
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700896 // <clinit> is another special case. The runtime holds the class lock while calling <clinit>.
897 MethodHelper mh(m);
898 if (mh.IsClassInitializer()) {
899 DumpLockedObject(os, m->GetDeclaringClass());
900 // Fall through because there might be synchronization in the user code too.
901 }
902
903 // Is there any reason to believe there's any synchronization in this method?
904 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -0700905 CHECK(code_item != NULL) << PrettyMethod(m);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700906 if (code_item->tries_size_ == 0) {
907 return; // No "tries" implies no synchronization, so no held locks to report.
908 }
909
Elliott Hughes80537bb2013-01-04 16:37:26 -0800910 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
911 // the locks held in this stack frame.
912 std::vector<uint32_t> monitor_enter_dex_pcs;
913 verifier::MethodVerifier::FindLocksAtDexPc(m, stack_visitor->GetDexPc(), monitor_enter_dex_pcs);
914 if (monitor_enter_dex_pcs.empty()) {
915 return;
916 }
917
918 // Verification is an iterative process, so it can visit the same monitor-enter instruction
919 // repeatedly with increasingly accurate type information. We don't want duplicates.
920 // TODO: is this fixed if we share the other std::vector-returning verifier code?
921 STLSortAndRemoveDuplicates(&monitor_enter_dex_pcs);
922
923 for (size_t i = 0; i < monitor_enter_dex_pcs.size(); ++i) {
924 // The verifier works in terms of the dex pcs of the monitor-enter instructions.
925 // We want the registers used by those instructions (so we can read the values out of them).
926 uint32_t dex_pc = monitor_enter_dex_pcs[i];
927 uint16_t monitor_enter_instruction = code_item->insns_[dex_pc];
928
929 // Quick sanity check.
930 if ((monitor_enter_instruction & 0xff) != Instruction::MONITOR_ENTER) {
931 LOG(FATAL) << "expected monitor-enter @" << dex_pc << "; was "
932 << reinterpret_cast<void*>(monitor_enter_instruction);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700933 }
934
Elliott Hughes80537bb2013-01-04 16:37:26 -0800935 uint16_t monitor_register = ((monitor_enter_instruction >> 8) & 0xff);
936 Object* o = reinterpret_cast<Object*>(stack_visitor->GetVReg(m, monitor_register,
937 kReferenceVReg));
938 DumpLockedObject(os, o);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700939 }
940}
941
Mathieu Chartier66f19252012-09-18 08:57:04 -0700942void Monitor::TranslateLocation(const AbstractMethod* method, uint32_t dex_pc,
jeffhao33dc7712011-11-09 17:54:24 -0800943 const char*& source_file, uint32_t& line_number) const {
944 // If method is null, location is unknown
945 if (method == NULL) {
Elliott Hughes12c51e32012-01-17 20:25:05 -0800946 source_file = "";
jeffhao33dc7712011-11-09 17:54:24 -0800947 line_number = 0;
948 return;
949 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800950 MethodHelper mh(method);
951 source_file = mh.GetDeclaringClassSourceFile();
Elliott Hughes12c51e32012-01-17 20:25:05 -0800952 if (source_file == NULL) {
953 source_file = "";
954 }
Ian Rogers0399dde2012-06-06 17:09:28 -0700955 line_number = mh.GetLineNumFromDexPC(dex_pc);
jeffhao33dc7712011-11-09 17:54:24 -0800956}
957
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700958MonitorList::MonitorList() : monitor_list_lock_("MonitorList lock") {
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700959}
960
961MonitorList::~MonitorList() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700962 MutexLock mu(Thread::Current(), monitor_list_lock_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700963 STLDeleteElements(&list_);
964}
965
966void MonitorList::Add(Monitor* m) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700967 MutexLock mu(Thread::Current(), monitor_list_lock_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700968 list_.push_front(m);
969}
970
971void MonitorList::SweepMonitorList(Heap::IsMarkedTester is_marked, void* arg) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700972 MutexLock mu(Thread::Current(), monitor_list_lock_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700973 typedef std::list<Monitor*>::iterator It; // TODO: C++0x auto
974 It it = list_.begin();
975 while (it != list_.end()) {
976 Monitor* m = *it;
977 if (!is_marked(m->GetObject(), arg)) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800978 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object " << m->GetObject();
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700979 delete m;
980 it = list_.erase(it);
981 } else {
982 ++it;
983 }
984 }
985}
986
Elliott Hughes5f791332011-09-15 17:45:30 -0700987} // namespace art