blob: aa4e5acefea19f9006b461c6147258eb8662f99e [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"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080025#include "mirror/abstract_method-inl.h"
26#include "mirror/object.h"
27#include "mirror/object_array-inl.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080028#include "object_utils.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070029#include "scoped_thread_state_change.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070030#include "thread.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070031#include "thread_list.h"
Elliott Hughes08fc03a2012-06-26 17:34:00 -070032#include "verifier/method_verifier.h"
Elliott Hughes044288f2012-06-25 14:46:39 -070033#include "well_known_classes.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070034
35namespace art {
36
37/*
38 * Every Object has a monitor associated with it, but not every Object is
39 * actually locked. Even the ones that are locked do not need a
40 * full-fledged monitor until a) there is actual contention or b) wait()
41 * is called on the Object.
42 *
43 * For Android, we have implemented a scheme similar to the one described
44 * in Bacon et al.'s "Thin locks: featherweight synchronization for Java"
45 * (ACM 1998). Things are even easier for us, though, because we have
46 * a full 32 bits to work with.
47 *
48 * The two states of an Object's lock are referred to as "thin" and
49 * "fat". A lock may transition from the "thin" state to the "fat"
50 * state and this transition is referred to as inflation. Once a lock
51 * has been inflated it remains in the "fat" state indefinitely.
52 *
53 * The lock value itself is stored in Object.lock. The LSB of the
54 * lock encodes its state. When cleared, the lock is in the "thin"
55 * state and its bits are formatted as follows:
56 *
57 * [31 ---- 19] [18 ---- 3] [2 ---- 1] [0]
58 * lock count thread id hash state 0
59 *
60 * When set, the lock is in the "fat" state and its bits are formatted
61 * as follows:
62 *
63 * [31 ---- 3] [2 ---- 1] [0]
64 * pointer hash state 1
65 *
66 * For an in-depth description of the mechanics of thin-vs-fat locking,
67 * read the paper referred to above.
Elliott Hughes54e7df12011-09-16 11:47:04 -070068 *
Elliott Hughes5f791332011-09-15 17:45:30 -070069 * Monitors provide:
70 * - mutually exclusive access to resources
71 * - a way for multiple threads to wait for notification
72 *
73 * In effect, they fill the role of both mutexes and condition variables.
74 *
75 * Only one thread can own the monitor at any time. There may be several
76 * threads waiting on it (the wait call unlocks it). One or more waiting
77 * threads may be getting interrupted or notified at any given time.
78 *
79 * TODO: the various members of monitor are not SMP-safe.
80 */
Elliott Hughes54e7df12011-09-16 11:47:04 -070081
Elliott Hughesf327e072013-01-09 16:01:26 -080082// The shape is the bottom bit; either LW_SHAPE_THIN or LW_SHAPE_FAT.
83#define LW_SHAPE_MASK 0x1
84#define LW_SHAPE(x) static_cast<int>((x) & LW_SHAPE_MASK)
Elliott Hughes54e7df12011-09-16 11:47:04 -070085
86/*
87 * Monitor accessor. Extracts a monitor structure pointer from a fat
88 * lock. Performs no error checking.
89 */
90#define LW_MONITOR(x) \
Elliott Hughes398f64b2012-03-26 18:05:48 -070091 (reinterpret_cast<Monitor*>((x) & ~((LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT) | LW_SHAPE_MASK)))
Elliott Hughes54e7df12011-09-16 11:47:04 -070092
93/*
94 * Lock recursion count field. Contains a count of the number of times
95 * a lock has been recursively acquired.
96 */
97#define LW_LOCK_COUNT_MASK 0x1fff
98#define LW_LOCK_COUNT_SHIFT 19
99#define LW_LOCK_COUNT(x) (((x) >> LW_LOCK_COUNT_SHIFT) & LW_LOCK_COUNT_MASK)
100
Elliott Hughesfc861622011-10-17 17:57:47 -0700101bool (*Monitor::is_sensitive_thread_hook_)() = NULL;
Elliott Hughesfc861622011-10-17 17:57:47 -0700102uint32_t Monitor::lock_profiling_threshold_ = 0;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700103
Elliott Hughesfc861622011-10-17 17:57:47 -0700104bool Monitor::IsSensitiveThread() {
105 if (is_sensitive_thread_hook_ != NULL) {
106 return (*is_sensitive_thread_hook_)();
107 }
108 return false;
109}
110
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800111void Monitor::Init(uint32_t lock_profiling_threshold, bool (*is_sensitive_thread_hook)()) {
Elliott Hughesfc861622011-10-17 17:57:47 -0700112 lock_profiling_threshold_ = lock_profiling_threshold;
113 is_sensitive_thread_hook_ = is_sensitive_thread_hook;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700114}
115
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800116Monitor::Monitor(Thread* owner, mirror::Object* obj)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700117 : monitor_lock_("a monitor lock", kMonitorLock),
118 owner_(owner),
Elliott Hughes5f791332011-09-15 17:45:30 -0700119 lock_count_(0),
120 obj_(obj),
121 wait_set_(NULL),
jeffhao33dc7712011-11-09 17:54:24 -0800122 locking_method_(NULL),
Ian Rogers0399dde2012-06-06 17:09:28 -0700123 locking_dex_pc_(0) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700124 monitor_lock_.Lock(owner);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700125 // Propagate the lock state.
126 uint32_t thin = *obj->GetRawLockWordAddress();
127 lock_count_ = LW_LOCK_COUNT(thin);
128 thin &= LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT;
129 thin |= reinterpret_cast<uint32_t>(this) | LW_SHAPE_FAT;
130 // Publish the updated lock word.
131 android_atomic_release_store(thin, obj->GetRawLockWordAddress());
132 // Lock profiling.
133 if (lock_profiling_threshold_ != 0) {
134 locking_method_ = owner->GetCurrentMethod(&locking_dex_pc_);
135 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700136}
137
138Monitor::~Monitor() {
139 DCHECK(obj_ != NULL);
140 DCHECK_EQ(LW_SHAPE(*obj_->GetRawLockWordAddress()), LW_SHAPE_FAT);
Elliott Hughes5f791332011-09-15 17:45:30 -0700141}
142
143/*
144 * Links a thread into a monitor's wait set. The monitor lock must be
145 * held by the caller of this routine.
146 */
147void Monitor::AppendToWaitSet(Thread* thread) {
148 DCHECK(owner_ == Thread::Current());
149 DCHECK(thread != NULL);
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700150 DCHECK(thread->wait_next_ == NULL) << thread->wait_next_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700151 if (wait_set_ == NULL) {
152 wait_set_ = thread;
153 return;
154 }
155
156 // push_back.
157 Thread* t = wait_set_;
158 while (t->wait_next_ != NULL) {
159 t = t->wait_next_;
160 }
161 t->wait_next_ = thread;
162}
163
164/*
165 * Unlinks a thread from a monitor's wait set. The monitor lock must
166 * be held by the caller of this routine.
167 */
168void Monitor::RemoveFromWaitSet(Thread *thread) {
169 DCHECK(owner_ == Thread::Current());
170 DCHECK(thread != NULL);
171 if (wait_set_ == NULL) {
172 return;
173 }
174 if (wait_set_ == thread) {
175 wait_set_ = thread->wait_next_;
176 thread->wait_next_ = NULL;
177 return;
178 }
179
180 Thread* t = wait_set_;
181 while (t->wait_next_ != NULL) {
182 if (t->wait_next_ == thread) {
183 t->wait_next_ = thread->wait_next_;
184 thread->wait_next_ = NULL;
185 return;
186 }
187 t = t->wait_next_;
188 }
189}
190
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800191mirror::Object* Monitor::GetObject() {
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700192 return obj_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700193}
194
Elliott Hughes5f791332011-09-15 17:45:30 -0700195void Monitor::Lock(Thread* self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700196 if (owner_ == self) {
197 lock_count_++;
198 return;
199 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700200
Ian Rogers81d425b2012-09-27 16:03:43 -0700201 if (!monitor_lock_.TryLock(self)) {
Mathieu Chartier2542d662012-06-21 17:14:11 -0700202 uint64_t waitStart = 0;
203 uint64_t waitEnd = 0;
Elliott Hughesfc861622011-10-17 17:57:47 -0700204 uint32_t wait_threshold = lock_profiling_threshold_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800205 const mirror::AbstractMethod* current_locking_method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700206 uint32_t current_locking_dex_pc = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700207 {
Elliott Hughes34e06962012-04-09 13:55:55 -0700208 ScopedThreadStateChange tsc(self, kBlocked);
Elliott Hughesfc861622011-10-17 17:57:47 -0700209 if (wait_threshold != 0) {
210 waitStart = NanoTime() / 1000;
211 }
jeffhao33dc7712011-11-09 17:54:24 -0800212 current_locking_method = locking_method_;
Ian Rogers0399dde2012-06-06 17:09:28 -0700213 current_locking_dex_pc = locking_dex_pc_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700214
Ian Rogers81d425b2012-09-27 16:03:43 -0700215 monitor_lock_.Lock(self);
Elliott Hughesfc861622011-10-17 17:57:47 -0700216 if (wait_threshold != 0) {
217 waitEnd = NanoTime() / 1000;
218 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700219 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700220
221 if (wait_threshold != 0) {
222 uint64_t wait_ms = (waitEnd - waitStart) / 1000;
223 uint32_t sample_percent;
224 if (wait_ms >= wait_threshold) {
225 sample_percent = 100;
226 } else {
227 sample_percent = 100 * wait_ms / wait_threshold;
228 }
229 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
jeffhao33dc7712011-11-09 17:54:24 -0800230 const char* current_locking_filename;
231 uint32_t current_locking_line_number;
Ian Rogers0399dde2012-06-06 17:09:28 -0700232 TranslateLocation(current_locking_method, current_locking_dex_pc,
jeffhao33dc7712011-11-09 17:54:24 -0800233 current_locking_filename, current_locking_line_number);
234 LogContentionEvent(self, wait_ms, sample_percent, current_locking_filename, current_locking_line_number);
Elliott Hughesfc861622011-10-17 17:57:47 -0700235 }
236 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700237 }
238 owner_ = self;
239 DCHECK_EQ(lock_count_, 0);
240
241 // When debugging, save the current monitor holder for future
242 // acquisition failures to use in sampled logging.
Elliott Hughesfc861622011-10-17 17:57:47 -0700243 if (lock_profiling_threshold_ != 0) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700244 locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
Elliott Hughesfc861622011-10-17 17:57:47 -0700245 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700246}
247
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800248static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
249 __attribute__((format(printf, 1, 2)));
250
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700251static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700252 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800253 va_list args;
254 va_start(args, fmt);
255 Thread::Current()->ThrowNewExceptionV("Ljava/lang/IllegalMonitorStateException;", fmt, args);
Brian Carlstrom64277f32012-03-26 23:53:34 -0700256 if (!Runtime::Current()->IsStarted()) {
257 std::ostringstream ss;
258 Thread::Current()->Dump(ss);
259 std::string str(ss.str());
260 LOG(ERROR) << "IllegalMonitorStateException: " << str;
261 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800262 va_end(args);
263}
264
Elliott Hughesd4237412012-02-21 11:24:45 -0800265static std::string ThreadToString(Thread* thread) {
266 if (thread == NULL) {
267 return "NULL";
268 }
269 std::ostringstream oss;
270 // TODO: alternatively, we could just return the thread's name.
271 oss << *thread;
272 return oss.str();
273}
274
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800275void Monitor::FailedUnlock(mirror::Object* o, Thread* expected_owner, Thread* found_owner,
Elliott Hughesffb465f2012-03-01 18:46:05 -0800276 Monitor* monitor) {
277 Thread* current_owner = NULL;
278 std::string current_owner_string;
279 std::string expected_owner_string;
280 std::string found_owner_string;
281 {
282 // TODO: isn't this too late to prevent threads from disappearing?
283 // Acquire thread list lock so threads won't disappear from under us.
Ian Rogers50b35e22012-10-04 10:09:15 -0700284 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Elliott Hughesffb465f2012-03-01 18:46:05 -0800285 // Re-read owner now that we hold lock.
286 current_owner = (monitor != NULL) ? monitor->owner_ : NULL;
287 // Get short descriptions of the threads involved.
288 current_owner_string = ThreadToString(current_owner);
289 expected_owner_string = ThreadToString(expected_owner);
290 found_owner_string = ThreadToString(found_owner);
291 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800292 if (current_owner == NULL) {
293 if (found_owner == NULL) {
294 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
295 " on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800296 PrettyTypeOf(o).c_str(),
297 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800298 } else {
299 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800300 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
301 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800302 found_owner_string.c_str(),
303 PrettyTypeOf(o).c_str(),
304 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800305 }
306 } else {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800307 if (found_owner == NULL) {
308 // Race: originally there was no owner, there is now
309 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
310 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800311 current_owner_string.c_str(),
312 PrettyTypeOf(o).c_str(),
313 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800314 } else {
315 if (found_owner != current_owner) {
316 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800317 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
318 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800319 found_owner_string.c_str(),
320 current_owner_string.c_str(),
321 PrettyTypeOf(o).c_str(),
322 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800323 } else {
324 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
325 " on thread '%s",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800326 current_owner_string.c_str(),
327 PrettyTypeOf(o).c_str(),
328 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800329 }
330 }
331 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700332}
333
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700334bool Monitor::Unlock(Thread* self, bool for_wait) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700335 DCHECK(self != NULL);
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800336 Thread* owner = owner_;
337 if (owner == self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700338 // We own the monitor, so nobody else can be in here.
339 if (lock_count_ == 0) {
340 owner_ = NULL;
jeffhao33dc7712011-11-09 17:54:24 -0800341 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700342 locking_dex_pc_ = 0;
Ian Rogers81d425b2012-09-27 16:03:43 -0700343 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700344 } else {
345 --lock_count_;
346 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700347 } else if (for_wait) {
348 // Wait should have already cleared the fields.
349 DCHECK_EQ(lock_count_, 0);
350 DCHECK(owner == NULL);
351 DCHECK(locking_method_ == NULL);
352 DCHECK_EQ(locking_dex_pc_, 0u);
Ian Rogers81d425b2012-09-27 16:03:43 -0700353 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700354 } else {
355 // We don't own this, so we're not allowed to unlock it.
356 // The JNI spec says that we should throw IllegalMonitorStateException
357 // in this case.
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800358 FailedUnlock(obj_, self, owner, this);
Elliott Hughes5f791332011-09-15 17:45:30 -0700359 return false;
360 }
361 return true;
362}
363
Elliott Hughes5f791332011-09-15 17:45:30 -0700364/*
365 * Wait on a monitor until timeout, interrupt, or notification. Used for
366 * Object.wait() and (somewhat indirectly) Thread.sleep() and Thread.join().
367 *
368 * If another thread calls Thread.interrupt(), we throw InterruptedException
369 * and return immediately if one of the following are true:
370 * - blocked in wait(), wait(long), or wait(long, int) methods of Object
371 * - blocked in join(), join(long), or join(long, int) methods of Thread
372 * - blocked in sleep(long), or sleep(long, int) methods of Thread
373 * Otherwise, we set the "interrupted" flag.
374 *
375 * Checks to make sure that "ns" is in the range 0-999999
376 * (i.e. fractions of a millisecond) and throws the appropriate
377 * exception if it isn't.
378 *
379 * The spec allows "spurious wakeups", and recommends that all code using
380 * Object.wait() do so in a loop. This appears to derive from concerns
381 * about pthread_cond_wait() on multiprocessor systems. Some commentary
382 * on the web casts doubt on whether these can/should occur.
383 *
384 * Since we're allowed to wake up "early", we clamp extremely long durations
385 * to return at the end of the 32-bit time epoch.
386 */
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800387void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
388 bool interruptShouldThrow, ThreadState why) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700389 DCHECK(self != NULL);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800390 DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
Elliott Hughes5f791332011-09-15 17:45:30 -0700391
392 // Make sure that we hold the lock.
393 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800394 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700395 return;
396 }
Ian Rogers50b35e22012-10-04 10:09:15 -0700397 monitor_lock_.AssertHeld(self);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800398
Elliott Hughesdf42c482013-01-09 12:49:02 -0800399 // We need to turn a zero-length timed wait into a regular wait because
400 // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
401 if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
402 why = kWaiting;
403 }
404
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800405 WaitWithLock(self, ms, ns, interruptShouldThrow, why);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700406}
Elliott Hughes5f791332011-09-15 17:45:30 -0700407
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800408void Monitor::WaitWithLock(Thread* self, int64_t ms, int32_t ns,
409 bool interruptShouldThrow, ThreadState why) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700410 // Enforce the timeout range.
411 if (ms < 0 || ns < 0 || ns > 999999) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700412 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
Elliott Hughes5f791332011-09-15 17:45:30 -0700413 "timeout arguments out of range: ms=%lld ns=%d", ms, ns);
414 return;
415 }
416
Elliott Hughes5f791332011-09-15 17:45:30 -0700417 /*
418 * Add ourselves to the set of threads waiting on this monitor, and
419 * release our hold. We need to let it go even if we're a few levels
420 * deep in a recursive lock, and we need to restore that later.
421 *
422 * We append to the wait set ahead of clearing the count and owner
423 * fields so the subroutine can check that the calling thread owns
424 * the monitor. Aside from that, the order of member updates is
425 * not order sensitive as we hold the pthread mutex.
426 */
427 AppendToWaitSet(self);
Ian Rogers0399dde2012-06-06 17:09:28 -0700428 int prev_lock_count = lock_count_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700429 lock_count_ = 0;
430 owner_ = NULL;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800431 const mirror::AbstractMethod* saved_method = locking_method_;
jeffhao33dc7712011-11-09 17:54:24 -0800432 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700433 uintptr_t saved_dex_pc = locking_dex_pc_;
434 locking_dex_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700435
436 /*
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800437 * Update thread state. If the GC wakes up, it'll ignore us, knowing
Elliott Hughes5f791332011-09-15 17:45:30 -0700438 * that we won't touch any references in this state, and we'll check
439 * our suspend mode before we transition out.
440 */
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800441 self->TransitionFromRunnableToSuspended(why);
Elliott Hughes5f791332011-09-15 17:45:30 -0700442
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800443 bool was_interrupted = false;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700444 {
445 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
Ian Rogers50b35e22012-10-04 10:09:15 -0700446 MutexLock mu(self, *self->wait_mutex_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700447
448 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
449 // non-NULL a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
450 // up.
451 DCHECK(self->wait_monitor_ == NULL);
452 self->wait_monitor_ = this;
453
454 // Release the monitor lock.
455 Unlock(self, true);
456
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800457 // Handle the case where the thread was interrupted before we called wait().
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700458 if (self->interrupted_) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800459 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700460 } else {
461 // Wait for a notification or a timeout to occur.
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800462 if (why == kWaiting) {
Ian Rogersc604d732012-10-14 16:09:54 -0700463 self->wait_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700464 } else {
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800465 DCHECK(why == kTimedWaiting || why == kSleeping) << why;
Ian Rogersc604d732012-10-14 16:09:54 -0700466 self->wait_cond_->TimedWait(self, ms, ns);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700467 }
468 if (self->interrupted_) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800469 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700470 }
471 self->interrupted_ = false;
472 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700473 }
474
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700475 // Set self->status back to kRunnable, and self-suspend if needed.
476 self->TransitionFromSuspendedToRunnable();
Elliott Hughes5f791332011-09-15 17:45:30 -0700477
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800478 {
479 // We reset the thread's wait_monitor_ field after transitioning back to runnable so
480 // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
481 // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
482 // are waiting on "null".)
483 MutexLock mu(self, *self->wait_mutex_);
484 DCHECK(self->wait_monitor_ != NULL);
485 self->wait_monitor_ = NULL;
486 }
487
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700488 // Re-acquire the monitor lock.
Elliott Hughes5f791332011-09-15 17:45:30 -0700489 Lock(self);
490
Ian Rogers81d425b2012-09-27 16:03:43 -0700491 self->wait_mutex_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700492
Elliott Hughes5f791332011-09-15 17:45:30 -0700493 /*
494 * We remove our thread from wait set after restoring the count
495 * and owner fields so the subroutine can check that the calling
496 * thread owns the monitor. Aside from that, the order of member
497 * updates is not order sensitive as we hold the pthread mutex.
498 */
499 owner_ = self;
Ian Rogers0399dde2012-06-06 17:09:28 -0700500 lock_count_ = prev_lock_count;
501 locking_method_ = saved_method;
502 locking_dex_pc_ = saved_dex_pc;
Elliott Hughes5f791332011-09-15 17:45:30 -0700503 RemoveFromWaitSet(self);
504
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800505 if (was_interrupted) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700506 /*
507 * We were interrupted while waiting, or somebody interrupted an
508 * un-interruptible thread earlier and we're bailing out immediately.
509 *
510 * The doc sayeth: "The interrupted status of the current thread is
511 * cleared when this exception is thrown."
512 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700513 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700514 MutexLock mu(self, *self->wait_mutex_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700515 self->interrupted_ = false;
516 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700517 if (interruptShouldThrow) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700518 Thread::Current()->ThrowNewException("Ljava/lang/InterruptedException;", NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700519 }
520 }
521}
522
523void Monitor::Notify(Thread* self) {
524 DCHECK(self != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700525 // Make sure that we hold the lock.
526 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800527 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700528 return;
529 }
Ian Rogers50b35e22012-10-04 10:09:15 -0700530 monitor_lock_.AssertHeld(self);
531 NotifyWithLock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700532}
533
Ian Rogers50b35e22012-10-04 10:09:15 -0700534void Monitor::NotifyWithLock(Thread* self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700535 // Signal the first waiting thread in the wait set.
536 while (wait_set_ != NULL) {
537 Thread* thread = wait_set_;
538 wait_set_ = thread->wait_next_;
539 thread->wait_next_ = NULL;
540
541 // Check to see if the thread is still waiting.
Ian Rogers50b35e22012-10-04 10:09:15 -0700542 MutexLock mu(self, *thread->wait_mutex_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700543 if (thread->wait_monitor_ != NULL) {
Ian Rogersc604d732012-10-14 16:09:54 -0700544 thread->wait_cond_->Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700545 return;
546 }
547 }
548}
549
550void Monitor::NotifyAll(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 notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700555 return;
556 }
Ian Rogers50b35e22012-10-04 10:09:15 -0700557 monitor_lock_.AssertHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700558 NotifyAllWithLock();
559}
560
561void Monitor::NotifyAllWithLock() {
Elliott Hughes5f791332011-09-15 17:45:30 -0700562 // Signal all threads 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 thread->Notify();
568 }
569}
570
571/*
572 * Changes the shape of a monitor from thin to fat, preserving the
573 * internal lock state. The calling thread must own the lock.
574 */
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800575void Monitor::Inflate(Thread* self, mirror::Object* obj) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700576 DCHECK(self != NULL);
577 DCHECK(obj != NULL);
578 DCHECK_EQ(LW_SHAPE(*obj->GetRawLockWordAddress()), LW_SHAPE_THIN);
Elliott Hughesf8e01272011-10-17 11:29:05 -0700579 DCHECK_EQ(LW_LOCK_OWNER(*obj->GetRawLockWordAddress()), static_cast<int32_t>(self->GetThinLockId()));
Elliott Hughes5f791332011-09-15 17:45:30 -0700580
581 // Allocate and acquire a new monitor.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700582 Monitor* m = new Monitor(self, obj);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800583 VLOG(monitor) << "monitor: thread " << self->GetThinLockId()
584 << " created monitor " << m << " for object " << obj;
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700585 Runtime::Current()->GetMonitorList()->Add(m);
Elliott Hughes5f791332011-09-15 17:45:30 -0700586}
587
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800588void Monitor::MonitorEnter(Thread* self, mirror::Object* obj) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700589 volatile int32_t* thinp = obj->GetRawLockWordAddress();
Elliott Hughes398f64b2012-03-26 18:05:48 -0700590 uint32_t sleepDelayNs;
591 uint32_t minSleepDelayNs = 1000000; /* 1 millisecond */
592 uint32_t maxSleepDelayNs = 1000000000; /* 1 second */
Elliott Hughesf8e01272011-10-17 11:29:05 -0700593 uint32_t thin, newThin;
Elliott Hughes5f791332011-09-15 17:45:30 -0700594
Elliott Hughes4681c802011-09-25 18:04:37 -0700595 DCHECK(self != NULL);
596 DCHECK(obj != NULL);
Elliott Hughesf8e01272011-10-17 11:29:05 -0700597 uint32_t threadId = self->GetThinLockId();
Elliott Hughesa21039c2012-06-21 12:09:25 -0700598 retry:
Elliott Hughes5f791332011-09-15 17:45:30 -0700599 thin = *thinp;
600 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
601 /*
602 * The lock is a thin lock. The owner field is used to
603 * determine the acquire method, ordered by cost.
604 */
605 if (LW_LOCK_OWNER(thin) == threadId) {
606 /*
607 * The calling thread owns the lock. Increment the
608 * value of the recursion count field.
609 */
610 *thinp += 1 << LW_LOCK_COUNT_SHIFT;
611 if (LW_LOCK_COUNT(*thinp) == LW_LOCK_COUNT_MASK) {
612 /*
613 * The reacquisition limit has been reached. Inflate
614 * the lock so the next acquire will not overflow the
615 * recursion count field.
616 */
617 Inflate(self, obj);
618 }
619 } else if (LW_LOCK_OWNER(thin) == 0) {
Elliott Hughes81ff3182012-03-23 20:35:56 -0700620 // The lock is unowned. Install the thread id of the calling thread into the owner field.
621 // This is the common case: compiled code will have tried this before calling back into
622 // the runtime.
Elliott Hughes5f791332011-09-15 17:45:30 -0700623 newThin = thin | (threadId << LW_LOCK_OWNER_SHIFT);
624 if (android_atomic_acquire_cas(thin, newThin, thinp) != 0) {
625 // The acquire failed. Try again.
626 goto retry;
627 }
628 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800629 VLOG(monitor) << StringPrintf("monitor: thread %d spin on lock %p (a %s) owned by %d",
Elliott Hughes81ff3182012-03-23 20:35:56 -0700630 threadId, thinp, PrettyTypeOf(obj).c_str(), LW_LOCK_OWNER(thin));
631 // The lock is owned by another thread. Notify the runtime that we are about to wait.
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700632 self->monitor_enter_object_ = obj;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700633 self->TransitionFromRunnableToSuspended(kBlocked);
Elliott Hughes5f791332011-09-15 17:45:30 -0700634 // Spin until the thin lock is released or inflated.
635 sleepDelayNs = 0;
636 for (;;) {
637 thin = *thinp;
638 // Check the shape of the lock word. Another thread
639 // may have inflated the lock while we were waiting.
640 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
641 if (LW_LOCK_OWNER(thin) == 0) {
642 // The lock has been released. Install the thread id of the
643 // calling thread into the owner field.
644 newThin = thin | (threadId << LW_LOCK_OWNER_SHIFT);
645 if (android_atomic_acquire_cas(thin, newThin, thinp) == 0) {
646 // The acquire succeed. Break out of the loop and proceed to inflate the lock.
647 break;
648 }
649 } else {
650 // The lock has not been released. Yield so the owning thread can run.
651 if (sleepDelayNs == 0) {
652 sched_yield();
653 sleepDelayNs = minSleepDelayNs;
654 } else {
Ian Rogers56edc432013-01-18 16:51:51 -0800655 NanoSleep(sleepDelayNs);
Elliott Hughes5f791332011-09-15 17:45:30 -0700656 // Prepare the next delay value. Wrap to avoid once a second polls for eternity.
657 if (sleepDelayNs < maxSleepDelayNs / 2) {
658 sleepDelayNs *= 2;
659 } else {
660 sleepDelayNs = minSleepDelayNs;
661 }
662 }
663 }
664 } else {
Elliott Hughes81ff3182012-03-23 20:35:56 -0700665 // The thin lock was inflated by another thread. Let the runtime know we are no longer
Elliott Hughes5f791332011-09-15 17:45:30 -0700666 // waiting and try again.
Elliott Hughes398f64b2012-03-26 18:05:48 -0700667 VLOG(monitor) << StringPrintf("monitor: thread %d found lock %p surprise-fattened by another thread", threadId, thinp);
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700668 self->monitor_enter_object_ = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700669 self->TransitionFromSuspendedToRunnable();
Elliott Hughes5f791332011-09-15 17:45:30 -0700670 goto retry;
671 }
672 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800673 VLOG(monitor) << StringPrintf("monitor: thread %d spin on lock %p done", threadId, thinp);
Elliott Hughes81ff3182012-03-23 20:35:56 -0700674 // We have acquired the thin lock. Let the runtime know that we are no longer waiting.
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700675 self->monitor_enter_object_ = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700676 self->TransitionFromSuspendedToRunnable();
Elliott Hughes5f791332011-09-15 17:45:30 -0700677 // Fatten the lock.
678 Inflate(self, obj);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800679 VLOG(monitor) << StringPrintf("monitor: thread %d fattened lock %p", threadId, thinp);
Elliott Hughes5f791332011-09-15 17:45:30 -0700680 }
681 } else {
682 // The lock is a fat lock.
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800683 VLOG(monitor) << StringPrintf("monitor: thread %d locking fat lock %p (%p) %p on a %s",
Elliott Hughes398f64b2012-03-26 18:05:48 -0700684 threadId, thinp, LW_MONITOR(*thinp),
685 reinterpret_cast<void*>(*thinp), PrettyTypeOf(obj).c_str());
Elliott Hughes5f791332011-09-15 17:45:30 -0700686 DCHECK(LW_MONITOR(*thinp) != NULL);
687 LW_MONITOR(*thinp)->Lock(self);
688 }
689}
690
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800691bool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700692 volatile int32_t* thinp = obj->GetRawLockWordAddress();
693
694 DCHECK(self != NULL);
Elliott Hughes34e06962012-04-09 13:55:55 -0700695 //DCHECK_EQ(self->GetState(), kRunnable);
Elliott Hughes5f791332011-09-15 17:45:30 -0700696 DCHECK(obj != NULL);
697
698 /*
699 * Cache the lock word as its value can change while we are
700 * examining its state.
701 */
702 uint32_t thin = *thinp;
703 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
704 /*
705 * The lock is thin. We must ensure that the lock is owned
706 * by the given thread before unlocking it.
707 */
Elliott Hughesf8e01272011-10-17 11:29:05 -0700708 if (LW_LOCK_OWNER(thin) == self->GetThinLockId()) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700709 /*
710 * We are the lock owner. It is safe to update the lock
711 * without CAS as lock ownership guards the lock itself.
712 */
713 if (LW_LOCK_COUNT(thin) == 0) {
714 /*
715 * The lock was not recursively acquired, the common
716 * case. Unlock by clearing all bits except for the
717 * hash state.
718 */
719 thin &= (LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT);
720 android_atomic_release_store(thin, thinp);
721 } else {
722 /*
723 * The object was recursively acquired. Decrement the
724 * lock recursion count field.
725 */
726 *thinp -= 1 << LW_LOCK_COUNT_SHIFT;
727 }
728 } else {
729 /*
730 * We do not own the lock. The JVM spec requires that we
731 * throw an exception in this case.
732 */
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800733 FailedUnlock(obj, self, NULL, NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700734 return false;
735 }
736 } else {
737 /*
738 * The lock is fat. We must check to see if Unlock has
739 * raised any exceptions before continuing.
740 */
741 DCHECK(LW_MONITOR(*thinp) != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700742 if (!LW_MONITOR(*thinp)->Unlock(self, false)) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700743 // An exception has been raised. Do not fall through.
744 return false;
745 }
746 }
747 return true;
748}
749
750/*
751 * Object.wait(). Also called for class init.
752 */
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800753void Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800754 bool interruptShouldThrow, ThreadState why) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700755 volatile int32_t* thinp = obj->GetRawLockWordAddress();
756
757 // If the lock is still thin, we need to fatten it.
758 uint32_t thin = *thinp;
759 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
760 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700761 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800762 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700763 return;
764 }
765
766 /* This thread holds the lock. We need to fatten the lock
767 * so 'self' can block on it. Don't update the object lock
768 * field yet, because 'self' needs to acquire the lock before
769 * any other thread gets a chance.
770 */
771 Inflate(self, obj);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800772 VLOG(monitor) << StringPrintf("monitor: thread %d fattened lock %p by wait()", self->GetThinLockId(), thinp);
Elliott Hughes5f791332011-09-15 17:45:30 -0700773 }
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800774 LW_MONITOR(*thinp)->Wait(self, ms, ns, interruptShouldThrow, why);
Elliott Hughes5f791332011-09-15 17:45:30 -0700775}
776
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800777void Monitor::Notify(Thread* self, mirror::Object *obj) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700778 uint32_t thin = *obj->GetRawLockWordAddress();
779
780 // If the lock is still thin, there aren't any waiters;
781 // waiting on an object forces lock fattening.
782 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
783 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700784 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800785 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700786 return;
787 }
788 // no-op; there are no waiters to notify.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700789 Inflate(self, obj);
Elliott Hughes5f791332011-09-15 17:45:30 -0700790 } else {
791 // It's a fat lock.
792 LW_MONITOR(thin)->Notify(self);
793 }
794}
795
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800796void Monitor::NotifyAll(Thread* self, mirror::Object *obj) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700797 uint32_t thin = *obj->GetRawLockWordAddress();
798
799 // If the lock is still thin, there aren't any waiters;
800 // waiting on an object forces lock fattening.
801 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
802 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700803 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800804 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700805 return;
806 }
807 // no-op; there are no waiters to notify.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700808 Inflate(self, obj);
Elliott Hughes5f791332011-09-15 17:45:30 -0700809 } else {
810 // It's a fat lock.
811 LW_MONITOR(thin)->NotifyAll(self);
812 }
813}
814
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -0700815uint32_t Monitor::GetThinLockId(uint32_t raw_lock_word) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700816 if (LW_SHAPE(raw_lock_word) == LW_SHAPE_THIN) {
817 return LW_LOCK_OWNER(raw_lock_word);
818 } else {
819 Thread* owner = LW_MONITOR(raw_lock_word)->owner_;
820 return owner ? owner->GetThinLockId() : 0;
821 }
822}
823
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700824void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800825 ThreadState state = thread->GetState();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700826
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800827 mirror::Object* object = NULL;
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700828 uint32_t lock_owner = ThreadList::kInvalidId;
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800829 if (state == kWaiting || state == kTimedWaiting || state == kSleeping) {
830 if (state == kSleeping) {
831 os << " - sleeping on ";
832 } else {
833 os << " - waiting on ";
834 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700835 {
Elliott Hughesf9501702013-01-11 11:22:27 -0800836 Thread* self = Thread::Current();
837 MutexLock mu(self, *thread->wait_mutex_);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800838 Monitor* monitor = thread->wait_monitor_;
839 if (monitor != NULL) {
840 object = monitor->obj_;
841 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700842 }
Elliott Hughes34e06962012-04-09 13:55:55 -0700843 } else if (state == kBlocked) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700844 os << " - waiting to lock ";
845 object = thread->monitor_enter_object_;
846 if (object != NULL) {
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -0700847 lock_owner = object->GetThinLockId();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700848 }
849 } else {
850 // We're not waiting on anything.
851 return;
852 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700853
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700854 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700855 os << "<" << object << "> (a " << PrettyTypeOf(object) << ")";
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700856
Elliott Hughesc5dc2ff2013-01-09 13:44:30 -0800857 // - waiting to lock <0x613f83d8> (a java.lang.Object) held by thread 5
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700858 if (lock_owner != ThreadList::kInvalidId) {
859 os << " held by thread " << lock_owner;
860 }
861
862 os << "\n";
863}
864
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800865mirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800866 // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
867 // definition of contended that includes a monitor a thread is trying to enter...
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800868 mirror::Object* result = thread->monitor_enter_object_;
Elliott Hughesf9501702013-01-11 11:22:27 -0800869 if (result != NULL) {
870 return result;
871 }
872 // ...but also a monitor that the thread is waiting on.
873 {
874 MutexLock mu(Thread::Current(), *thread->wait_mutex_);
875 Monitor* monitor = thread->wait_monitor_;
876 if (monitor != NULL) {
877 return monitor->obj_;
878 }
879 }
880 return NULL;
881}
882
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800883void Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
884 void* callback_context) {
885 mirror::AbstractMethod* m = stack_visitor->GetMethod();
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700886 CHECK(m != NULL);
887
888 // Native methods are an easy special case.
889 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
890 if (m->IsNative()) {
891 if (m->IsSynchronized()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800892 mirror::Object* jni_this = stack_visitor->GetCurrentSirt()->GetReference(0);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800893 callback(jni_this, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700894 }
895 return;
896 }
897
jeffhao61f916c2012-10-25 17:48:51 -0700898 // Proxy methods should not be synchronized.
899 if (m->IsProxyMethod()) {
900 CHECK(!m->IsSynchronized());
901 return;
902 }
903
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700904 // <clinit> is another special case. The runtime holds the class lock while calling <clinit>.
905 MethodHelper mh(m);
906 if (mh.IsClassInitializer()) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800907 callback(m->GetDeclaringClass(), callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700908 // Fall through because there might be synchronization in the user code too.
909 }
910
911 // Is there any reason to believe there's any synchronization in this method?
912 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -0700913 CHECK(code_item != NULL) << PrettyMethod(m);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700914 if (code_item->tries_size_ == 0) {
915 return; // No "tries" implies no synchronization, so no held locks to report.
916 }
917
Elliott Hughes80537bb2013-01-04 16:37:26 -0800918 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
919 // the locks held in this stack frame.
920 std::vector<uint32_t> monitor_enter_dex_pcs;
921 verifier::MethodVerifier::FindLocksAtDexPc(m, stack_visitor->GetDexPc(), monitor_enter_dex_pcs);
922 if (monitor_enter_dex_pcs.empty()) {
923 return;
924 }
925
Elliott Hughes80537bb2013-01-04 16:37:26 -0800926 for (size_t i = 0; i < monitor_enter_dex_pcs.size(); ++i) {
927 // The verifier works in terms of the dex pcs of the monitor-enter instructions.
928 // We want the registers used by those instructions (so we can read the values out of them).
929 uint32_t dex_pc = monitor_enter_dex_pcs[i];
930 uint16_t monitor_enter_instruction = code_item->insns_[dex_pc];
931
932 // Quick sanity check.
933 if ((monitor_enter_instruction & 0xff) != Instruction::MONITOR_ENTER) {
934 LOG(FATAL) << "expected monitor-enter @" << dex_pc << "; was "
935 << reinterpret_cast<void*>(monitor_enter_instruction);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700936 }
937
Elliott Hughes80537bb2013-01-04 16:37:26 -0800938 uint16_t monitor_register = ((monitor_enter_instruction >> 8) & 0xff);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800939 mirror::Object* o = reinterpret_cast<mirror::Object*>(stack_visitor->GetVReg(m, monitor_register,
940 kReferenceVReg));
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800941 callback(o, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700942 }
943}
944
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800945void Monitor::TranslateLocation(const mirror::AbstractMethod* method, uint32_t dex_pc,
jeffhao33dc7712011-11-09 17:54:24 -0800946 const char*& source_file, uint32_t& line_number) const {
947 // If method is null, location is unknown
948 if (method == NULL) {
Elliott Hughes12c51e32012-01-17 20:25:05 -0800949 source_file = "";
jeffhao33dc7712011-11-09 17:54:24 -0800950 line_number = 0;
951 return;
952 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800953 MethodHelper mh(method);
954 source_file = mh.GetDeclaringClassSourceFile();
Elliott Hughes12c51e32012-01-17 20:25:05 -0800955 if (source_file == NULL) {
956 source_file = "";
957 }
Ian Rogers0399dde2012-06-06 17:09:28 -0700958 line_number = mh.GetLineNumFromDexPC(dex_pc);
jeffhao33dc7712011-11-09 17:54:24 -0800959}
960
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700961MonitorList::MonitorList() : monitor_list_lock_("MonitorList lock") {
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700962}
963
964MonitorList::~MonitorList() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700965 MutexLock mu(Thread::Current(), monitor_list_lock_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700966 STLDeleteElements(&list_);
967}
968
969void MonitorList::Add(Monitor* m) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700970 MutexLock mu(Thread::Current(), monitor_list_lock_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700971 list_.push_front(m);
972}
973
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800974void MonitorList::SweepMonitorList(IsMarkedTester is_marked, void* arg) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700975 MutexLock mu(Thread::Current(), monitor_list_lock_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700976 typedef std::list<Monitor*>::iterator It; // TODO: C++0x auto
977 It it = list_.begin();
978 while (it != list_.end()) {
979 Monitor* m = *it;
980 if (!is_marked(m->GetObject(), arg)) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800981 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object " << m->GetObject();
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700982 delete m;
983 it = list_.erase(it);
984 } else {
985 ++it;
986 }
987 }
988}
989
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800990MonitorInfo::MonitorInfo(mirror::Object* o) : owner(NULL), entry_count(0) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800991 uint32_t lock_word = *o->GetRawLockWordAddress();
992 if (LW_SHAPE(lock_word) == LW_SHAPE_THIN) {
993 uint32_t owner_thin_lock_id = LW_LOCK_OWNER(lock_word);
994 if (owner_thin_lock_id != 0) {
995 owner = Runtime::Current()->GetThreadList()->FindThreadByThinLockId(owner_thin_lock_id);
996 entry_count = 1 + LW_LOCK_COUNT(lock_word);
997 }
998 // Thin locks have no waiters.
999 } else {
1000 CHECK_EQ(LW_SHAPE(lock_word), LW_SHAPE_FAT);
1001 Monitor* monitor = LW_MONITOR(lock_word);
1002 owner = monitor->owner_;
1003 entry_count = 1 + monitor->lock_count_;
1004 for (Thread* waiter = monitor->wait_set_; waiter != NULL; waiter = waiter->wait_next_) {
1005 waiters.push_back(waiter);
1006 }
1007 }
1008}
1009
Elliott Hughes5f791332011-09-15 17:45:30 -07001010} // namespace art