blob: 6b7fbf116af62dacc6fd47c651daeb08920a0a30 [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
19#include <errno.h>
20#include <fcntl.h>
21#include <pthread.h>
22#include <stdlib.h>
23#include <sys/time.h>
24#include <time.h>
25#include <unistd.h>
26
Elliott Hughes08fc03a2012-06-26 17:34:00 -070027#include <vector>
28
jeffhao33dc7712011-11-09 17:54:24 -080029#include "class_linker.h"
Elliott Hughes08fc03a2012-06-26 17:34:00 -070030#include "dex_instruction.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070031#include "mutex.h"
32#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080033#include "object_utils.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070034#include "scoped_thread_state_change.h"
Elliott Hughesc33a32b2011-10-11 18:18:07 -070035#include "stl_util.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070036#include "thread.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070037#include "thread_list.h"
Elliott Hughes08fc03a2012-06-26 17:34:00 -070038#include "verifier/method_verifier.h"
Elliott Hughes044288f2012-06-25 14:46:39 -070039#include "well_known_classes.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070040
41namespace art {
42
43/*
44 * Every Object has a monitor associated with it, but not every Object is
45 * actually locked. Even the ones that are locked do not need a
46 * full-fledged monitor until a) there is actual contention or b) wait()
47 * is called on the Object.
48 *
49 * For Android, we have implemented a scheme similar to the one described
50 * in Bacon et al.'s "Thin locks: featherweight synchronization for Java"
51 * (ACM 1998). Things are even easier for us, though, because we have
52 * a full 32 bits to work with.
53 *
54 * The two states of an Object's lock are referred to as "thin" and
55 * "fat". A lock may transition from the "thin" state to the "fat"
56 * state and this transition is referred to as inflation. Once a lock
57 * has been inflated it remains in the "fat" state indefinitely.
58 *
59 * The lock value itself is stored in Object.lock. The LSB of the
60 * lock encodes its state. When cleared, the lock is in the "thin"
61 * state and its bits are formatted as follows:
62 *
63 * [31 ---- 19] [18 ---- 3] [2 ---- 1] [0]
64 * lock count thread id hash state 0
65 *
66 * When set, the lock is in the "fat" state and its bits are formatted
67 * as follows:
68 *
69 * [31 ---- 3] [2 ---- 1] [0]
70 * pointer hash state 1
71 *
72 * For an in-depth description of the mechanics of thin-vs-fat locking,
73 * read the paper referred to above.
Elliott Hughes54e7df12011-09-16 11:47:04 -070074 *
Elliott Hughes5f791332011-09-15 17:45:30 -070075 * Monitors provide:
76 * - mutually exclusive access to resources
77 * - a way for multiple threads to wait for notification
78 *
79 * In effect, they fill the role of both mutexes and condition variables.
80 *
81 * Only one thread can own the monitor at any time. There may be several
82 * threads waiting on it (the wait call unlocks it). One or more waiting
83 * threads may be getting interrupted or notified at any given time.
84 *
85 * TODO: the various members of monitor are not SMP-safe.
86 */
Elliott Hughes54e7df12011-09-16 11:47:04 -070087
88
89/*
90 * Monitor accessor. Extracts a monitor structure pointer from a fat
91 * lock. Performs no error checking.
92 */
93#define LW_MONITOR(x) \
Elliott Hughes398f64b2012-03-26 18:05:48 -070094 (reinterpret_cast<Monitor*>((x) & ~((LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT) | LW_SHAPE_MASK)))
Elliott Hughes54e7df12011-09-16 11:47:04 -070095
96/*
97 * Lock recursion count field. Contains a count of the number of times
98 * a lock has been recursively acquired.
99 */
100#define LW_LOCK_COUNT_MASK 0x1fff
101#define LW_LOCK_COUNT_SHIFT 19
102#define LW_LOCK_COUNT(x) (((x) >> LW_LOCK_COUNT_SHIFT) & LW_LOCK_COUNT_MASK)
103
Elliott Hughesfc861622011-10-17 17:57:47 -0700104bool (*Monitor::is_sensitive_thread_hook_)() = NULL;
Elliott Hughesfc861622011-10-17 17:57:47 -0700105uint32_t Monitor::lock_profiling_threshold_ = 0;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700106
Elliott Hughesfc861622011-10-17 17:57:47 -0700107bool Monitor::IsSensitiveThread() {
108 if (is_sensitive_thread_hook_ != NULL) {
109 return (*is_sensitive_thread_hook_)();
110 }
111 return false;
112}
113
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800114void Monitor::Init(uint32_t lock_profiling_threshold, bool (*is_sensitive_thread_hook)()) {
Elliott Hughesfc861622011-10-17 17:57:47 -0700115 lock_profiling_threshold_ = lock_profiling_threshold;
116 is_sensitive_thread_hook_ = is_sensitive_thread_hook;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700117}
118
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700119Monitor::Monitor(Thread* owner, Object* obj)
120 : monitor_lock_("a monitor lock", kMonitorLock),
121 owner_(owner),
Elliott Hughes5f791332011-09-15 17:45:30 -0700122 lock_count_(0),
123 obj_(obj),
124 wait_set_(NULL),
jeffhao33dc7712011-11-09 17:54:24 -0800125 locking_method_(NULL),
Ian Rogers0399dde2012-06-06 17:09:28 -0700126 locking_dex_pc_(0) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700127 monitor_lock_.Lock();
128 // Propagate the lock state.
129 uint32_t thin = *obj->GetRawLockWordAddress();
130 lock_count_ = LW_LOCK_COUNT(thin);
131 thin &= LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT;
132 thin |= reinterpret_cast<uint32_t>(this) | LW_SHAPE_FAT;
133 // Publish the updated lock word.
134 android_atomic_release_store(thin, obj->GetRawLockWordAddress());
135 // Lock profiling.
136 if (lock_profiling_threshold_ != 0) {
137 locking_method_ = owner->GetCurrentMethod(&locking_dex_pc_);
138 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700139}
140
141Monitor::~Monitor() {
142 DCHECK(obj_ != NULL);
143 DCHECK_EQ(LW_SHAPE(*obj_->GetRawLockWordAddress()), LW_SHAPE_FAT);
Elliott Hughes5f791332011-09-15 17:45:30 -0700144}
145
146/*
147 * Links a thread into a monitor's wait set. The monitor lock must be
148 * held by the caller of this routine.
149 */
150void Monitor::AppendToWaitSet(Thread* thread) {
151 DCHECK(owner_ == Thread::Current());
152 DCHECK(thread != NULL);
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700153 DCHECK(thread->wait_next_ == NULL) << thread->wait_next_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700154 if (wait_set_ == NULL) {
155 wait_set_ = thread;
156 return;
157 }
158
159 // push_back.
160 Thread* t = wait_set_;
161 while (t->wait_next_ != NULL) {
162 t = t->wait_next_;
163 }
164 t->wait_next_ = thread;
165}
166
167/*
168 * Unlinks a thread from a monitor's wait set. The monitor lock must
169 * be held by the caller of this routine.
170 */
171void Monitor::RemoveFromWaitSet(Thread *thread) {
172 DCHECK(owner_ == Thread::Current());
173 DCHECK(thread != NULL);
174 if (wait_set_ == NULL) {
175 return;
176 }
177 if (wait_set_ == thread) {
178 wait_set_ = thread->wait_next_;
179 thread->wait_next_ = NULL;
180 return;
181 }
182
183 Thread* t = wait_set_;
184 while (t->wait_next_ != NULL) {
185 if (t->wait_next_ == thread) {
186 t->wait_next_ = thread->wait_next_;
187 thread->wait_next_ = NULL;
188 return;
189 }
190 t = t->wait_next_;
191 }
192}
193
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700194Object* Monitor::GetObject() {
195 return obj_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700196}
197
Elliott Hughes5f791332011-09-15 17:45:30 -0700198void Monitor::Lock(Thread* self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700199 if (owner_ == self) {
200 lock_count_++;
201 return;
202 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700203
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700204 if (!monitor_lock_.TryLock()) {
Mathieu Chartier2542d662012-06-21 17:14:11 -0700205 uint64_t waitStart = 0;
206 uint64_t waitEnd = 0;
Elliott Hughesfc861622011-10-17 17:57:47 -0700207 uint32_t wait_threshold = lock_profiling_threshold_;
jeffhao33dc7712011-11-09 17:54:24 -0800208 const Method* current_locking_method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700209 uint32_t current_locking_dex_pc = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700210 {
Elliott Hughes34e06962012-04-09 13:55:55 -0700211 ScopedThreadStateChange tsc(self, kBlocked);
Elliott Hughesfc861622011-10-17 17:57:47 -0700212 if (wait_threshold != 0) {
213 waitStart = NanoTime() / 1000;
214 }
jeffhao33dc7712011-11-09 17:54:24 -0800215 current_locking_method = locking_method_;
Ian Rogers0399dde2012-06-06 17:09:28 -0700216 current_locking_dex_pc = locking_dex_pc_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700217
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700218 monitor_lock_.Lock();
Elliott Hughesfc861622011-10-17 17:57:47 -0700219 if (wait_threshold != 0) {
220 waitEnd = NanoTime() / 1000;
221 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700222 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700223
224 if (wait_threshold != 0) {
225 uint64_t wait_ms = (waitEnd - waitStart) / 1000;
226 uint32_t sample_percent;
227 if (wait_ms >= wait_threshold) {
228 sample_percent = 100;
229 } else {
230 sample_percent = 100 * wait_ms / wait_threshold;
231 }
232 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
jeffhao33dc7712011-11-09 17:54:24 -0800233 const char* current_locking_filename;
234 uint32_t current_locking_line_number;
Ian Rogers0399dde2012-06-06 17:09:28 -0700235 TranslateLocation(current_locking_method, current_locking_dex_pc,
jeffhao33dc7712011-11-09 17:54:24 -0800236 current_locking_filename, current_locking_line_number);
237 LogContentionEvent(self, wait_ms, sample_percent, current_locking_filename, current_locking_line_number);
Elliott Hughesfc861622011-10-17 17:57:47 -0700238 }
239 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700240 }
241 owner_ = self;
242 DCHECK_EQ(lock_count_, 0);
243
244 // When debugging, save the current monitor holder for future
245 // acquisition failures to use in sampled logging.
Elliott Hughesfc861622011-10-17 17:57:47 -0700246 if (lock_profiling_threshold_ != 0) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700247 locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
Elliott Hughesfc861622011-10-17 17:57:47 -0700248 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700249}
250
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800251static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
252 __attribute__((format(printf, 1, 2)));
253
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700254static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700255 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800256 va_list args;
257 va_start(args, fmt);
258 Thread::Current()->ThrowNewExceptionV("Ljava/lang/IllegalMonitorStateException;", fmt, args);
Brian Carlstrom64277f32012-03-26 23:53:34 -0700259 if (!Runtime::Current()->IsStarted()) {
260 std::ostringstream ss;
261 Thread::Current()->Dump(ss);
262 std::string str(ss.str());
263 LOG(ERROR) << "IllegalMonitorStateException: " << str;
264 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800265 va_end(args);
266}
267
Elliott Hughesd4237412012-02-21 11:24:45 -0800268static std::string ThreadToString(Thread* thread) {
269 if (thread == NULL) {
270 return "NULL";
271 }
272 std::ostringstream oss;
273 // TODO: alternatively, we could just return the thread's name.
274 oss << *thread;
275 return oss.str();
276}
277
Elliott Hughesffb465f2012-03-01 18:46:05 -0800278void Monitor::FailedUnlock(Object* o, Thread* expected_owner, Thread* found_owner,
279 Monitor* monitor) {
280 Thread* current_owner = NULL;
281 std::string current_owner_string;
282 std::string expected_owner_string;
283 std::string found_owner_string;
284 {
285 // TODO: isn't this too late to prevent threads from disappearing?
286 // Acquire thread list lock so threads won't disappear from under us.
Ian Rogersb726dcb2012-09-05 08:57:23 -0700287 MutexLock mu(*Locks::thread_list_lock_);
Elliott Hughesffb465f2012-03-01 18:46:05 -0800288 // Re-read owner now that we hold lock.
289 current_owner = (monitor != NULL) ? monitor->owner_ : NULL;
290 // Get short descriptions of the threads involved.
291 current_owner_string = ThreadToString(current_owner);
292 expected_owner_string = ThreadToString(expected_owner);
293 found_owner_string = ThreadToString(found_owner);
294 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800295 if (current_owner == NULL) {
296 if (found_owner == NULL) {
297 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
298 " on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800299 PrettyTypeOf(o).c_str(),
300 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800301 } else {
302 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800303 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
304 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800305 found_owner_string.c_str(),
306 PrettyTypeOf(o).c_str(),
307 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800308 }
309 } else {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800310 if (found_owner == NULL) {
311 // Race: originally there was no owner, there is now
312 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
313 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800314 current_owner_string.c_str(),
315 PrettyTypeOf(o).c_str(),
316 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800317 } else {
318 if (found_owner != current_owner) {
319 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800320 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
321 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800322 found_owner_string.c_str(),
323 current_owner_string.c_str(),
324 PrettyTypeOf(o).c_str(),
325 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800326 } else {
327 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
328 " on thread '%s",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800329 current_owner_string.c_str(),
330 PrettyTypeOf(o).c_str(),
331 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800332 }
333 }
334 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700335}
336
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700337bool Monitor::Unlock(Thread* self, bool for_wait) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700338 DCHECK(self != NULL);
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800339 Thread* owner = owner_;
340 if (owner == self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700341 // We own the monitor, so nobody else can be in here.
342 if (lock_count_ == 0) {
343 owner_ = NULL;
jeffhao33dc7712011-11-09 17:54:24 -0800344 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700345 locking_dex_pc_ = 0;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700346 monitor_lock_.Unlock();
Elliott Hughes5f791332011-09-15 17:45:30 -0700347 } else {
348 --lock_count_;
349 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700350 } else if (for_wait) {
351 // Wait should have already cleared the fields.
352 DCHECK_EQ(lock_count_, 0);
353 DCHECK(owner == NULL);
354 DCHECK(locking_method_ == NULL);
355 DCHECK_EQ(locking_dex_pc_, 0u);
356 monitor_lock_.Unlock();
Elliott Hughes5f791332011-09-15 17:45:30 -0700357 } else {
358 // We don't own this, so we're not allowed to unlock it.
359 // The JNI spec says that we should throw IllegalMonitorStateException
360 // in this case.
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800361 FailedUnlock(obj_, self, owner, this);
Elliott Hughes5f791332011-09-15 17:45:30 -0700362 return false;
363 }
364 return true;
365}
366
Elliott Hughes8f751ab2012-05-15 17:12:40 -0700367// Converts the given waiting time (relative to "now") into an absolute time in 'ts'.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700368static void ToAbsoluteTime(int64_t ms, int32_t ns, timespec* ts)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700369 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700370 int64_t endSec;
371
372#ifdef HAVE_TIMEDWAIT_MONOTONIC
373 clock_gettime(CLOCK_MONOTONIC, ts);
374#else
375 {
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700376 timeval tv;
Elliott Hughes5f791332011-09-15 17:45:30 -0700377 gettimeofday(&tv, NULL);
378 ts->tv_sec = tv.tv_sec;
379 ts->tv_nsec = tv.tv_usec * 1000;
380 }
381#endif
382 endSec = ts->tv_sec + ms / 1000;
383 if (endSec >= 0x7fffffff) {
Elliott Hughes8f751ab2012-05-15 17:12:40 -0700384 std::ostringstream ss;
385 Thread::Current()->Dump(ss);
386 LOG(INFO) << "Note: end time exceeds epoch: " << ss.str();
Elliott Hughes5f791332011-09-15 17:45:30 -0700387 endSec = 0x7ffffffe;
388 }
389 ts->tv_sec = endSec;
390 ts->tv_nsec = (ts->tv_nsec + (ms % 1000) * 1000000) + ns;
391
392 // Catch rollover.
393 if (ts->tv_nsec >= 1000000000L) {
394 ts->tv_sec++;
395 ts->tv_nsec -= 1000000000L;
396 }
397}
398
Elliott Hughes5f791332011-09-15 17:45:30 -0700399/*
400 * Wait on a monitor until timeout, interrupt, or notification. Used for
401 * Object.wait() and (somewhat indirectly) Thread.sleep() and Thread.join().
402 *
403 * If another thread calls Thread.interrupt(), we throw InterruptedException
404 * and return immediately if one of the following are true:
405 * - blocked in wait(), wait(long), or wait(long, int) methods of Object
406 * - blocked in join(), join(long), or join(long, int) methods of Thread
407 * - blocked in sleep(long), or sleep(long, int) methods of Thread
408 * Otherwise, we set the "interrupted" flag.
409 *
410 * Checks to make sure that "ns" is in the range 0-999999
411 * (i.e. fractions of a millisecond) and throws the appropriate
412 * exception if it isn't.
413 *
414 * The spec allows "spurious wakeups", and recommends that all code using
415 * Object.wait() do so in a loop. This appears to derive from concerns
416 * about pthread_cond_wait() on multiprocessor systems. Some commentary
417 * on the web casts doubt on whether these can/should occur.
418 *
419 * Since we're allowed to wake up "early", we clamp extremely long durations
420 * to return at the end of the 32-bit time epoch.
421 */
422void Monitor::Wait(Thread* self, int64_t ms, int32_t ns, bool interruptShouldThrow) {
423 DCHECK(self != NULL);
424
425 // Make sure that we hold the lock.
426 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800427 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700428 return;
429 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700430 monitor_lock_.AssertHeld();
431 WaitWithLock(self, ms, ns, interruptShouldThrow);
432}
Elliott Hughes5f791332011-09-15 17:45:30 -0700433
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700434void Monitor::WaitWithLock(Thread* self, int64_t ms, int32_t ns, bool interruptShouldThrow) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700435 // Enforce the timeout range.
436 if (ms < 0 || ns < 0 || ns > 999999) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700437 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
Elliott Hughes5f791332011-09-15 17:45:30 -0700438 "timeout arguments out of range: ms=%lld ns=%d", ms, ns);
439 return;
440 }
441
442 // Compute absolute wakeup time, if necessary.
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700443 timespec ts;
Elliott Hughes5f791332011-09-15 17:45:30 -0700444 bool timed = false;
445 if (ms != 0 || ns != 0) {
446 ToAbsoluteTime(ms, ns, &ts);
447 timed = true;
448 }
449
450 /*
451 * Add ourselves to the set of threads waiting on this monitor, and
452 * release our hold. We need to let it go even if we're a few levels
453 * deep in a recursive lock, and we need to restore that later.
454 *
455 * We append to the wait set ahead of clearing the count and owner
456 * fields so the subroutine can check that the calling thread owns
457 * the monitor. Aside from that, the order of member updates is
458 * not order sensitive as we hold the pthread mutex.
459 */
460 AppendToWaitSet(self);
Ian Rogers0399dde2012-06-06 17:09:28 -0700461 int prev_lock_count = lock_count_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700462 lock_count_ = 0;
463 owner_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700464 const Method* saved_method = locking_method_;
jeffhao33dc7712011-11-09 17:54:24 -0800465 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700466 uintptr_t saved_dex_pc = locking_dex_pc_;
467 locking_dex_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700468
469 /*
470 * Update thread status. If the GC wakes up, it'll ignore us, knowing
471 * that we won't touch any references in this state, and we'll check
472 * our suspend mode before we transition out.
473 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700474 self->TransitionFromRunnableToSuspended(timed ? kTimedWaiting : kWaiting);
Elliott Hughes5f791332011-09-15 17:45:30 -0700475
Elliott Hughes5f791332011-09-15 17:45:30 -0700476 bool wasInterrupted = false;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700477 {
478 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
479 MutexLock mu(*self->wait_mutex_);
480
481 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
482 // non-NULL a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
483 // up.
484 DCHECK(self->wait_monitor_ == NULL);
485 self->wait_monitor_ = this;
486
487 // Release the monitor lock.
488 Unlock(self, true);
489
490 /*
491 * Handle the case where the thread was interrupted before we called
492 * wait().
493 */
494 if (self->interrupted_) {
495 wasInterrupted = true;
496 } else {
497 // Wait for a notification or a timeout to occur.
498 if (!timed) {
499 self->wait_cond_->Wait(*self->wait_mutex_);
500 } else {
501 self->wait_cond_->TimedWait(*self->wait_mutex_, ts);
502 }
503 if (self->interrupted_) {
504 wasInterrupted = true;
505 }
506 self->interrupted_ = false;
507 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700508 self->wait_monitor_ = NULL;
Elliott Hughes5f791332011-09-15 17:45:30 -0700509 }
510
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700511 // Set self->status back to kRunnable, and self-suspend if needed.
512 self->TransitionFromSuspendedToRunnable();
Elliott Hughes5f791332011-09-15 17:45:30 -0700513
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700514 // Re-acquire the monitor lock.
Elliott Hughes5f791332011-09-15 17:45:30 -0700515 Lock(self);
516
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700517
518 self->wait_mutex_->AssertNotHeld();
519
Elliott Hughes5f791332011-09-15 17:45:30 -0700520 /*
521 * We remove our thread from wait set after restoring the count
522 * and owner fields so the subroutine can check that the calling
523 * thread owns the monitor. Aside from that, the order of member
524 * updates is not order sensitive as we hold the pthread mutex.
525 */
526 owner_ = self;
Ian Rogers0399dde2012-06-06 17:09:28 -0700527 lock_count_ = prev_lock_count;
528 locking_method_ = saved_method;
529 locking_dex_pc_ = saved_dex_pc;
Elliott Hughes5f791332011-09-15 17:45:30 -0700530 RemoveFromWaitSet(self);
531
Elliott Hughes5f791332011-09-15 17:45:30 -0700532 if (wasInterrupted) {
533 /*
534 * We were interrupted while waiting, or somebody interrupted an
535 * un-interruptible thread earlier and we're bailing out immediately.
536 *
537 * The doc sayeth: "The interrupted status of the current thread is
538 * cleared when this exception is thrown."
539 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700540 {
541 MutexLock mu(*self->wait_mutex_);
542 self->interrupted_ = false;
543 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700544 if (interruptShouldThrow) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700545 Thread::Current()->ThrowNewException("Ljava/lang/InterruptedException;", NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700546 }
547 }
548}
549
550void Monitor::Notify(Thread* self) {
551 DCHECK(self != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700552 // Make sure that we hold the lock.
553 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800554 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700555 return;
556 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700557 monitor_lock_.AssertHeld();
558 NotifyWithLock();
559}
560
561void Monitor::NotifyWithLock() {
Elliott Hughes5f791332011-09-15 17:45:30 -0700562 // Signal the first waiting thread in the wait set.
563 while (wait_set_ != NULL) {
564 Thread* thread = wait_set_;
565 wait_set_ = thread->wait_next_;
566 thread->wait_next_ = NULL;
567
568 // Check to see if the thread is still waiting.
Elliott Hughes85d15452011-09-16 17:33:01 -0700569 MutexLock mu(*thread->wait_mutex_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700570 if (thread->wait_monitor_ != NULL) {
Elliott Hughes85d15452011-09-16 17:33:01 -0700571 thread->wait_cond_->Signal();
Elliott Hughes5f791332011-09-15 17:45:30 -0700572 return;
573 }
574 }
575}
576
577void Monitor::NotifyAll(Thread* self) {
578 DCHECK(self != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700579 // Make sure that we hold the lock.
580 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800581 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700582 return;
583 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700584 monitor_lock_.AssertHeld();
585 NotifyAllWithLock();
586}
587
588void Monitor::NotifyAllWithLock() {
Elliott Hughes5f791332011-09-15 17:45:30 -0700589 // Signal all threads in the wait set.
590 while (wait_set_ != NULL) {
591 Thread* thread = wait_set_;
592 wait_set_ = thread->wait_next_;
593 thread->wait_next_ = NULL;
594 thread->Notify();
595 }
596}
597
598/*
599 * Changes the shape of a monitor from thin to fat, preserving the
600 * internal lock state. The calling thread must own the lock.
601 */
602void Monitor::Inflate(Thread* self, Object* obj) {
603 DCHECK(self != NULL);
604 DCHECK(obj != NULL);
605 DCHECK_EQ(LW_SHAPE(*obj->GetRawLockWordAddress()), LW_SHAPE_THIN);
Elliott Hughesf8e01272011-10-17 11:29:05 -0700606 DCHECK_EQ(LW_LOCK_OWNER(*obj->GetRawLockWordAddress()), static_cast<int32_t>(self->GetThinLockId()));
Elliott Hughes5f791332011-09-15 17:45:30 -0700607
608 // Allocate and acquire a new monitor.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700609 Monitor* m = new Monitor(self, obj);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800610 VLOG(monitor) << "monitor: thread " << self->GetThinLockId()
611 << " created monitor " << m << " for object " << obj;
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700612 Runtime::Current()->GetMonitorList()->Add(m);
Elliott Hughes5f791332011-09-15 17:45:30 -0700613}
614
615void Monitor::MonitorEnter(Thread* self, Object* obj) {
616 volatile int32_t* thinp = obj->GetRawLockWordAddress();
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700617 timespec tm;
Elliott Hughes398f64b2012-03-26 18:05:48 -0700618 uint32_t sleepDelayNs;
619 uint32_t minSleepDelayNs = 1000000; /* 1 millisecond */
620 uint32_t maxSleepDelayNs = 1000000000; /* 1 second */
Elliott Hughesf8e01272011-10-17 11:29:05 -0700621 uint32_t thin, newThin;
Elliott Hughes5f791332011-09-15 17:45:30 -0700622
Elliott Hughes4681c802011-09-25 18:04:37 -0700623 DCHECK(self != NULL);
624 DCHECK(obj != NULL);
Elliott Hughesf8e01272011-10-17 11:29:05 -0700625 uint32_t threadId = self->GetThinLockId();
Elliott Hughesa21039c2012-06-21 12:09:25 -0700626 retry:
Elliott Hughes5f791332011-09-15 17:45:30 -0700627 thin = *thinp;
628 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
629 /*
630 * The lock is a thin lock. The owner field is used to
631 * determine the acquire method, ordered by cost.
632 */
633 if (LW_LOCK_OWNER(thin) == threadId) {
634 /*
635 * The calling thread owns the lock. Increment the
636 * value of the recursion count field.
637 */
638 *thinp += 1 << LW_LOCK_COUNT_SHIFT;
639 if (LW_LOCK_COUNT(*thinp) == LW_LOCK_COUNT_MASK) {
640 /*
641 * The reacquisition limit has been reached. Inflate
642 * the lock so the next acquire will not overflow the
643 * recursion count field.
644 */
645 Inflate(self, obj);
646 }
647 } else if (LW_LOCK_OWNER(thin) == 0) {
Elliott Hughes81ff3182012-03-23 20:35:56 -0700648 // The lock is unowned. Install the thread id of the calling thread into the owner field.
649 // This is the common case: compiled code will have tried this before calling back into
650 // the runtime.
Elliott Hughes5f791332011-09-15 17:45:30 -0700651 newThin = thin | (threadId << LW_LOCK_OWNER_SHIFT);
652 if (android_atomic_acquire_cas(thin, newThin, thinp) != 0) {
653 // The acquire failed. Try again.
654 goto retry;
655 }
656 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800657 VLOG(monitor) << StringPrintf("monitor: thread %d spin on lock %p (a %s) owned by %d",
Elliott Hughes81ff3182012-03-23 20:35:56 -0700658 threadId, thinp, PrettyTypeOf(obj).c_str(), LW_LOCK_OWNER(thin));
659 // The lock is owned by another thread. Notify the runtime that we are about to wait.
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700660 self->monitor_enter_object_ = obj;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700661 self->TransitionFromRunnableToSuspended(kBlocked);
Elliott Hughes5f791332011-09-15 17:45:30 -0700662 // Spin until the thin lock is released or inflated.
663 sleepDelayNs = 0;
664 for (;;) {
665 thin = *thinp;
666 // Check the shape of the lock word. Another thread
667 // may have inflated the lock while we were waiting.
668 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
669 if (LW_LOCK_OWNER(thin) == 0) {
670 // The lock has been released. Install the thread id of the
671 // calling thread into the owner field.
672 newThin = thin | (threadId << LW_LOCK_OWNER_SHIFT);
673 if (android_atomic_acquire_cas(thin, newThin, thinp) == 0) {
674 // The acquire succeed. Break out of the loop and proceed to inflate the lock.
675 break;
676 }
677 } else {
678 // The lock has not been released. Yield so the owning thread can run.
679 if (sleepDelayNs == 0) {
680 sched_yield();
681 sleepDelayNs = minSleepDelayNs;
682 } else {
683 tm.tv_sec = 0;
684 tm.tv_nsec = sleepDelayNs;
685 nanosleep(&tm, NULL);
686 // Prepare the next delay value. Wrap to avoid once a second polls for eternity.
687 if (sleepDelayNs < maxSleepDelayNs / 2) {
688 sleepDelayNs *= 2;
689 } else {
690 sleepDelayNs = minSleepDelayNs;
691 }
692 }
693 }
694 } else {
Elliott Hughes81ff3182012-03-23 20:35:56 -0700695 // The thin lock was inflated by another thread. Let the runtime know we are no longer
Elliott Hughes5f791332011-09-15 17:45:30 -0700696 // waiting and try again.
Elliott Hughes398f64b2012-03-26 18:05:48 -0700697 VLOG(monitor) << StringPrintf("monitor: thread %d found lock %p surprise-fattened by another thread", threadId, thinp);
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700698 self->monitor_enter_object_ = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700699 self->TransitionFromSuspendedToRunnable();
Elliott Hughes5f791332011-09-15 17:45:30 -0700700 goto retry;
701 }
702 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800703 VLOG(monitor) << StringPrintf("monitor: thread %d spin on lock %p done", threadId, thinp);
Elliott Hughes81ff3182012-03-23 20:35:56 -0700704 // We have acquired the thin lock. Let the runtime know that we are no longer waiting.
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700705 self->monitor_enter_object_ = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700706 self->TransitionFromSuspendedToRunnable();
Elliott Hughes5f791332011-09-15 17:45:30 -0700707 // Fatten the lock.
708 Inflate(self, obj);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800709 VLOG(monitor) << StringPrintf("monitor: thread %d fattened lock %p", threadId, thinp);
Elliott Hughes5f791332011-09-15 17:45:30 -0700710 }
711 } else {
712 // The lock is a fat lock.
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800713 VLOG(monitor) << StringPrintf("monitor: thread %d locking fat lock %p (%p) %p on a %s",
Elliott Hughes398f64b2012-03-26 18:05:48 -0700714 threadId, thinp, LW_MONITOR(*thinp),
715 reinterpret_cast<void*>(*thinp), PrettyTypeOf(obj).c_str());
Elliott Hughes5f791332011-09-15 17:45:30 -0700716 DCHECK(LW_MONITOR(*thinp) != NULL);
717 LW_MONITOR(*thinp)->Lock(self);
718 }
719}
720
721bool Monitor::MonitorExit(Thread* self, Object* obj) {
722 volatile int32_t* thinp = obj->GetRawLockWordAddress();
723
724 DCHECK(self != NULL);
Elliott Hughes34e06962012-04-09 13:55:55 -0700725 //DCHECK_EQ(self->GetState(), kRunnable);
Elliott Hughes5f791332011-09-15 17:45:30 -0700726 DCHECK(obj != NULL);
727
728 /*
729 * Cache the lock word as its value can change while we are
730 * examining its state.
731 */
732 uint32_t thin = *thinp;
733 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
734 /*
735 * The lock is thin. We must ensure that the lock is owned
736 * by the given thread before unlocking it.
737 */
Elliott Hughesf8e01272011-10-17 11:29:05 -0700738 if (LW_LOCK_OWNER(thin) == self->GetThinLockId()) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700739 /*
740 * We are the lock owner. It is safe to update the lock
741 * without CAS as lock ownership guards the lock itself.
742 */
743 if (LW_LOCK_COUNT(thin) == 0) {
744 /*
745 * The lock was not recursively acquired, the common
746 * case. Unlock by clearing all bits except for the
747 * hash state.
748 */
749 thin &= (LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT);
750 android_atomic_release_store(thin, thinp);
751 } else {
752 /*
753 * The object was recursively acquired. Decrement the
754 * lock recursion count field.
755 */
756 *thinp -= 1 << LW_LOCK_COUNT_SHIFT;
757 }
758 } else {
759 /*
760 * We do not own the lock. The JVM spec requires that we
761 * throw an exception in this case.
762 */
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800763 FailedUnlock(obj, self, NULL, NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700764 return false;
765 }
766 } else {
767 /*
768 * The lock is fat. We must check to see if Unlock has
769 * raised any exceptions before continuing.
770 */
771 DCHECK(LW_MONITOR(*thinp) != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700772 if (!LW_MONITOR(*thinp)->Unlock(self, false)) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700773 // An exception has been raised. Do not fall through.
774 return false;
775 }
776 }
777 return true;
778}
779
780/*
781 * Object.wait(). Also called for class init.
782 */
783void Monitor::Wait(Thread* self, Object *obj, int64_t ms, int32_t ns, bool interruptShouldThrow) {
784 volatile int32_t* thinp = obj->GetRawLockWordAddress();
785
786 // If the lock is still thin, we need to fatten it.
787 uint32_t thin = *thinp;
788 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
789 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700790 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800791 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700792 return;
793 }
794
795 /* This thread holds the lock. We need to fatten the lock
796 * so 'self' can block on it. Don't update the object lock
797 * field yet, because 'self' needs to acquire the lock before
798 * any other thread gets a chance.
799 */
800 Inflate(self, obj);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800801 VLOG(monitor) << StringPrintf("monitor: thread %d fattened lock %p by wait()", self->GetThinLockId(), thinp);
Elliott Hughes5f791332011-09-15 17:45:30 -0700802 }
803 LW_MONITOR(*thinp)->Wait(self, ms, ns, interruptShouldThrow);
804}
805
806void Monitor::Notify(Thread* self, Object *obj) {
807 uint32_t thin = *obj->GetRawLockWordAddress();
808
809 // If the lock is still thin, there aren't any waiters;
810 // waiting on an object forces lock fattening.
811 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
812 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700813 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800814 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700815 return;
816 }
817 // no-op; there are no waiters to notify.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700818 Inflate(self, obj);
Elliott Hughes5f791332011-09-15 17:45:30 -0700819 } else {
820 // It's a fat lock.
821 LW_MONITOR(thin)->Notify(self);
822 }
823}
824
825void Monitor::NotifyAll(Thread* self, Object *obj) {
826 uint32_t thin = *obj->GetRawLockWordAddress();
827
828 // If the lock is still thin, there aren't any waiters;
829 // waiting on an object forces lock fattening.
830 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
831 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700832 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800833 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700834 return;
835 }
836 // no-op; there are no waiters to notify.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700837 Inflate(self, obj);
Elliott Hughes5f791332011-09-15 17:45:30 -0700838 } else {
839 // It's a fat lock.
840 LW_MONITOR(thin)->NotifyAll(self);
841 }
842}
843
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -0700844uint32_t Monitor::GetThinLockId(uint32_t raw_lock_word) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700845 if (LW_SHAPE(raw_lock_word) == LW_SHAPE_THIN) {
846 return LW_LOCK_OWNER(raw_lock_word);
847 } else {
848 Thread* owner = LW_MONITOR(raw_lock_word)->owner_;
849 return owner ? owner->GetThinLockId() : 0;
850 }
851}
852
Elliott Hughes044288f2012-06-25 14:46:39 -0700853static uint32_t LockOwnerFromThreadLock(Object* thread_lock) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700854 ScopedObjectAccess soa(Thread::Current());
Ian Rogers365c1022012-06-22 15:05:28 -0700855 if (thread_lock == NULL ||
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700856 thread_lock->GetClass() != soa.Decode<Class*>(WellKnownClasses::java_lang_ThreadLock)) {
Elliott Hughes044288f2012-06-25 14:46:39 -0700857 return ThreadList::kInvalidId;
858 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700859 Field* thread_field = soa.DecodeField(WellKnownClasses::java_lang_ThreadLock_thread);
Elliott Hughes044288f2012-06-25 14:46:39 -0700860 Object* managed_thread = thread_field->GetObject(thread_lock);
861 if (managed_thread == NULL) {
862 return ThreadList::kInvalidId;
863 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700864 Field* vmData_field = soa.DecodeField(WellKnownClasses::java_lang_Thread_vmData);
Elliott Hughes044288f2012-06-25 14:46:39 -0700865 uintptr_t vmData = static_cast<uintptr_t>(vmData_field->GetInt(managed_thread));
866 Thread* thread = reinterpret_cast<Thread*>(vmData);
867 if (thread == NULL) {
868 return ThreadList::kInvalidId;
869 }
870 return thread->GetThinLockId();
871}
872
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700873void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700874 ThreadState state;
875 {
Ian Rogersb726dcb2012-09-05 08:57:23 -0700876 MutexLock mu(*Locks::thread_suspend_count_lock_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700877 state = thread->GetState();
878 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700879
880 Object* object = NULL;
881 uint32_t lock_owner = ThreadList::kInvalidId;
Elliott Hughes34e06962012-04-09 13:55:55 -0700882 if (state == kWaiting || state == kTimedWaiting) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700883 os << " - waiting on ";
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700884 Monitor* monitor;
885 {
886 MutexLock mu(*thread->wait_mutex_);
887 monitor = thread->wait_monitor_;
888 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700889 if (monitor != NULL) {
890 object = monitor->obj_;
891 }
Elliott Hughes044288f2012-06-25 14:46:39 -0700892 lock_owner = LockOwnerFromThreadLock(object);
Elliott Hughes34e06962012-04-09 13:55:55 -0700893 } else if (state == kBlocked) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700894 os << " - waiting to lock ";
895 object = thread->monitor_enter_object_;
896 if (object != NULL) {
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -0700897 lock_owner = object->GetThinLockId();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700898 }
899 } else {
900 // We're not waiting on anything.
901 return;
902 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700903
904 // - waiting on <0x613f83d8> (a java.lang.ThreadLock) held by thread 5
905 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700906 os << "<" << object << "> (a " << PrettyTypeOf(object) << ")";
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700907
908 if (lock_owner != ThreadList::kInvalidId) {
909 os << " held by thread " << lock_owner;
910 }
911
912 os << "\n";
913}
914
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700915static void DumpLockedObject(std::ostream& os, Object* o)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700916 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700917 os << " - locked <" << o << "> (a " << PrettyTypeOf(o) << ")\n";
918}
919
920void Monitor::DescribeLocks(std::ostream& os, StackVisitor* stack_visitor) {
921 Method* m = stack_visitor->GetMethod();
922 CHECK(m != NULL);
923
924 // Native methods are an easy special case.
925 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
926 if (m->IsNative()) {
927 if (m->IsSynchronized()) {
928 Object* jni_this = stack_visitor->GetCurrentSirt()->GetReference(0);
929 DumpLockedObject(os, jni_this);
930 }
931 return;
932 }
933
934 // <clinit> is another special case. The runtime holds the class lock while calling <clinit>.
935 MethodHelper mh(m);
936 if (mh.IsClassInitializer()) {
937 DumpLockedObject(os, m->GetDeclaringClass());
938 // Fall through because there might be synchronization in the user code too.
939 }
940
941 // Is there any reason to believe there's any synchronization in this method?
942 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -0700943 CHECK(code_item != NULL) << PrettyMethod(m);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700944 if (code_item->tries_size_ == 0) {
945 return; // No "tries" implies no synchronization, so no held locks to report.
946 }
947
Ian Rogers0ec569a2012-07-01 16:43:46 -0700948 // TODO: Enable dex register lock descriptions, disabling as for the portable path GetVReg is
949 // unimplemented. There is also a possible deadlock relating to the verifier calling
950 // ClassLoader.loadClass and reentering managed code whilst the ThreadList lock is held.
951 const bool kEnableDexRegisterLockDescriptions = false;
952 if (kEnableDexRegisterLockDescriptions) {
953 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
954 // the locks held in this stack frame.
955 std::vector<uint32_t> monitor_enter_dex_pcs;
956 verifier::MethodVerifier::FindLocksAtDexPc(m, stack_visitor->GetDexPc(), monitor_enter_dex_pcs);
957 if (monitor_enter_dex_pcs.empty()) {
958 return;
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700959 }
960
Ian Rogers0ec569a2012-07-01 16:43:46 -0700961 // Verification is an iterative process, so it can visit the same monitor-enter instruction
962 // repeatedly with increasingly accurate type information. Our callers don't want to see
963 // duplicates.
964 STLSortAndRemoveDuplicates(&monitor_enter_dex_pcs);
965
966 for (size_t i = 0; i < monitor_enter_dex_pcs.size(); ++i) {
967 // The verifier works in terms of the dex pcs of the monitor-enter instructions.
968 // We want the registers used by those instructions (so we can read the values out of them).
969 uint32_t dex_pc = monitor_enter_dex_pcs[i];
970 uint16_t monitor_enter_instruction = code_item->insns_[dex_pc];
971
972 // Quick sanity check.
973 if ((monitor_enter_instruction & 0xff) != Instruction::MONITOR_ENTER) {
974 LOG(FATAL) << "expected monitor-enter @" << dex_pc << "; was "
975 << reinterpret_cast<void*>(monitor_enter_instruction);
976 }
977
978 uint16_t monitor_register = ((monitor_enter_instruction >> 8) & 0xff);
979 Object* o = reinterpret_cast<Object*>(stack_visitor->GetVReg(m, monitor_register));
980 DumpLockedObject(os, o);
981 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700982 }
983}
984
Ian Rogers0399dde2012-06-06 17:09:28 -0700985void Monitor::TranslateLocation(const Method* method, uint32_t dex_pc,
jeffhao33dc7712011-11-09 17:54:24 -0800986 const char*& source_file, uint32_t& line_number) const {
987 // If method is null, location is unknown
988 if (method == NULL) {
Elliott Hughes12c51e32012-01-17 20:25:05 -0800989 source_file = "";
jeffhao33dc7712011-11-09 17:54:24 -0800990 line_number = 0;
991 return;
992 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800993 MethodHelper mh(method);
994 source_file = mh.GetDeclaringClassSourceFile();
Elliott Hughes12c51e32012-01-17 20:25:05 -0800995 if (source_file == NULL) {
996 source_file = "";
997 }
Ian Rogers0399dde2012-06-06 17:09:28 -0700998 line_number = mh.GetLineNumFromDexPC(dex_pc);
jeffhao33dc7712011-11-09 17:54:24 -0800999}
1000
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001001MonitorList::MonitorList() : monitor_list_lock_("MonitorList lock") {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001002}
1003
1004MonitorList::~MonitorList() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001005 MutexLock mu(monitor_list_lock_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001006 STLDeleteElements(&list_);
1007}
1008
1009void MonitorList::Add(Monitor* m) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001010 MutexLock mu(monitor_list_lock_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001011 list_.push_front(m);
1012}
1013
1014void MonitorList::SweepMonitorList(Heap::IsMarkedTester is_marked, void* arg) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001015 MutexLock mu(monitor_list_lock_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001016 typedef std::list<Monitor*>::iterator It; // TODO: C++0x auto
1017 It it = list_.begin();
1018 while (it != list_.end()) {
1019 Monitor* m = *it;
1020 if (!is_marked(m->GetObject(), arg)) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001021 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object " << m->GetObject();
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001022 delete m;
1023 it = list_.erase(it);
1024 } else {
1025 ++it;
1026 }
1027 }
1028}
1029
Elliott Hughes5f791332011-09-15 17:45:30 -07001030} // namespace art