blob: 570c2bef944c61a80b1fe50fb707914564705b28 [file] [log] [blame]
Elliott Hughes5f791332011-09-15 17:45:30 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Elliott Hughes54e7df12011-09-16 11:47:04 -070017#include "monitor.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070018
Elliott Hughes08fc03a2012-06-26 17:34:00 -070019#include <vector>
20
Elliott Hughes76b61672012-12-12 17:47:30 -080021#include "base/mutex.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080022#include "base/stl_util.h"
jeffhao33dc7712011-11-09 17:54:24 -080023#include "class_linker.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070024#include "dex_file-inl.h"
Elliott Hughes08fc03a2012-06-26 17:34:00 -070025#include "dex_instruction.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070026#include "mirror/art_method-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070027#include "mirror/class-inl.h"
Ian Rogers05f30572013-02-20 12:13:11 -080028#include "mirror/object-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080029#include "mirror/object_array-inl.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080030#include "object_utils.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070031#include "scoped_thread_state_change.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070032#include "thread.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070033#include "thread_list.h"
Elliott Hughes08fc03a2012-06-26 17:34:00 -070034#include "verifier/method_verifier.h"
Elliott Hughes044288f2012-06-25 14:46:39 -070035#include "well_known_classes.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070036
37namespace art {
38
39/*
40 * Every Object has a monitor associated with it, but not every Object is
41 * actually locked. Even the ones that are locked do not need a
42 * full-fledged monitor until a) there is actual contention or b) wait()
43 * is called on the Object.
44 *
45 * For Android, we have implemented a scheme similar to the one described
46 * in Bacon et al.'s "Thin locks: featherweight synchronization for Java"
47 * (ACM 1998). Things are even easier for us, though, because we have
48 * a full 32 bits to work with.
49 *
50 * The two states of an Object's lock are referred to as "thin" and
51 * "fat". A lock may transition from the "thin" state to the "fat"
52 * state and this transition is referred to as inflation. Once a lock
53 * has been inflated it remains in the "fat" state indefinitely.
54 *
55 * The lock value itself is stored in Object.lock. The LSB of the
56 * lock encodes its state. When cleared, the lock is in the "thin"
57 * state and its bits are formatted as follows:
58 *
59 * [31 ---- 19] [18 ---- 3] [2 ---- 1] [0]
60 * lock count thread id hash state 0
61 *
62 * When set, the lock is in the "fat" state and its bits are formatted
63 * as follows:
64 *
65 * [31 ---- 3] [2 ---- 1] [0]
66 * pointer hash state 1
67 *
68 * For an in-depth description of the mechanics of thin-vs-fat locking,
69 * read the paper referred to above.
Elliott Hughes54e7df12011-09-16 11:47:04 -070070 *
Elliott Hughes5f791332011-09-15 17:45:30 -070071 * Monitors provide:
72 * - mutually exclusive access to resources
73 * - a way for multiple threads to wait for notification
74 *
75 * In effect, they fill the role of both mutexes and condition variables.
76 *
77 * Only one thread can own the monitor at any time. There may be several
78 * threads waiting on it (the wait call unlocks it). One or more waiting
79 * threads may be getting interrupted or notified at any given time.
80 *
81 * TODO: the various members of monitor are not SMP-safe.
82 */
Elliott Hughes54e7df12011-09-16 11:47:04 -070083
Elliott Hughesf327e072013-01-09 16:01:26 -080084// The shape is the bottom bit; either LW_SHAPE_THIN or LW_SHAPE_FAT.
85#define LW_SHAPE_MASK 0x1
86#define LW_SHAPE(x) static_cast<int>((x) & LW_SHAPE_MASK)
Elliott Hughes54e7df12011-09-16 11:47:04 -070087
88/*
89 * Monitor accessor. Extracts a monitor structure pointer from a fat
90 * lock. Performs no error checking.
91 */
92#define LW_MONITOR(x) \
Elliott Hughes398f64b2012-03-26 18:05:48 -070093 (reinterpret_cast<Monitor*>((x) & ~((LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT) | LW_SHAPE_MASK)))
Elliott Hughes54e7df12011-09-16 11:47:04 -070094
95/*
96 * Lock recursion count field. Contains a count of the number of times
97 * a lock has been recursively acquired.
98 */
99#define LW_LOCK_COUNT_MASK 0x1fff
100#define LW_LOCK_COUNT_SHIFT 19
101#define LW_LOCK_COUNT(x) (((x) >> LW_LOCK_COUNT_SHIFT) & LW_LOCK_COUNT_MASK)
102
Elliott Hughesfc861622011-10-17 17:57:47 -0700103bool (*Monitor::is_sensitive_thread_hook_)() = NULL;
Elliott Hughesfc861622011-10-17 17:57:47 -0700104uint32_t Monitor::lock_profiling_threshold_ = 0;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700105
Elliott Hughesfc861622011-10-17 17:57:47 -0700106bool Monitor::IsSensitiveThread() {
107 if (is_sensitive_thread_hook_ != NULL) {
108 return (*is_sensitive_thread_hook_)();
109 }
110 return false;
111}
112
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800113void Monitor::Init(uint32_t lock_profiling_threshold, bool (*is_sensitive_thread_hook)()) {
Elliott Hughesfc861622011-10-17 17:57:47 -0700114 lock_profiling_threshold_ = lock_profiling_threshold;
115 is_sensitive_thread_hook_ = is_sensitive_thread_hook;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700116}
117
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800118Monitor::Monitor(Thread* owner, mirror::Object* obj)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700119 : monitor_lock_("a monitor lock", kMonitorLock),
120 owner_(owner),
Elliott Hughes5f791332011-09-15 17:45:30 -0700121 lock_count_(0),
122 obj_(obj),
123 wait_set_(NULL),
jeffhao33dc7712011-11-09 17:54:24 -0800124 locking_method_(NULL),
Ian Rogers0399dde2012-06-06 17:09:28 -0700125 locking_dex_pc_(0) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700126 monitor_lock_.Lock(owner);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700127 // Propagate the lock state.
128 uint32_t thin = *obj->GetRawLockWordAddress();
129 lock_count_ = LW_LOCK_COUNT(thin);
130 thin &= LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT;
131 thin |= reinterpret_cast<uint32_t>(this) | LW_SHAPE_FAT;
132 // Publish the updated lock word.
133 android_atomic_release_store(thin, obj->GetRawLockWordAddress());
134 // Lock profiling.
135 if (lock_profiling_threshold_ != 0) {
136 locking_method_ = owner->GetCurrentMethod(&locking_dex_pc_);
137 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700138}
139
140Monitor::~Monitor() {
141 DCHECK(obj_ != NULL);
142 DCHECK_EQ(LW_SHAPE(*obj_->GetRawLockWordAddress()), LW_SHAPE_FAT);
Elliott Hughes5f791332011-09-15 17:45:30 -0700143}
144
145/*
146 * Links a thread into a monitor's wait set. The monitor lock must be
147 * held by the caller of this routine.
148 */
149void Monitor::AppendToWaitSet(Thread* thread) {
150 DCHECK(owner_ == Thread::Current());
151 DCHECK(thread != NULL);
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700152 DCHECK(thread->wait_next_ == NULL) << thread->wait_next_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700153 if (wait_set_ == NULL) {
154 wait_set_ = thread;
155 return;
156 }
157
158 // push_back.
159 Thread* t = wait_set_;
160 while (t->wait_next_ != NULL) {
161 t = t->wait_next_;
162 }
163 t->wait_next_ = thread;
164}
165
166/*
167 * Unlinks a thread from a monitor's wait set. The monitor lock must
168 * be held by the caller of this routine.
169 */
170void Monitor::RemoveFromWaitSet(Thread *thread) {
171 DCHECK(owner_ == Thread::Current());
172 DCHECK(thread != NULL);
173 if (wait_set_ == NULL) {
174 return;
175 }
176 if (wait_set_ == thread) {
177 wait_set_ = thread->wait_next_;
178 thread->wait_next_ = NULL;
179 return;
180 }
181
182 Thread* t = wait_set_;
183 while (t->wait_next_ != NULL) {
184 if (t->wait_next_ == thread) {
185 t->wait_next_ = thread->wait_next_;
186 thread->wait_next_ = NULL;
187 return;
188 }
189 t = t->wait_next_;
190 }
191}
192
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800193mirror::Object* Monitor::GetObject() {
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700194 return obj_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700195}
196
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700197void Monitor::SetObject(mirror::Object* object) {
198 obj_ = object;
199}
200
Elliott Hughes5f791332011-09-15 17:45:30 -0700201void Monitor::Lock(Thread* self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700202 if (owner_ == self) {
203 lock_count_++;
204 return;
205 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700206
Ian Rogers81d425b2012-09-27 16:03:43 -0700207 if (!monitor_lock_.TryLock(self)) {
Mathieu Chartier2542d662012-06-21 17:14:11 -0700208 uint64_t waitStart = 0;
209 uint64_t waitEnd = 0;
Elliott Hughesfc861622011-10-17 17:57:47 -0700210 uint32_t wait_threshold = lock_profiling_threshold_;
Brian Carlstromea46f952013-07-30 01:26:50 -0700211 const mirror::ArtMethod* current_locking_method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700212 uint32_t current_locking_dex_pc = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700213 {
Elliott Hughes34e06962012-04-09 13:55:55 -0700214 ScopedThreadStateChange tsc(self, kBlocked);
Elliott Hughesfc861622011-10-17 17:57:47 -0700215 if (wait_threshold != 0) {
216 waitStart = NanoTime() / 1000;
217 }
jeffhao33dc7712011-11-09 17:54:24 -0800218 current_locking_method = locking_method_;
Ian Rogers0399dde2012-06-06 17:09:28 -0700219 current_locking_dex_pc = locking_dex_pc_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700220
Ian Rogers81d425b2012-09-27 16:03:43 -0700221 monitor_lock_.Lock(self);
Elliott Hughesfc861622011-10-17 17:57:47 -0700222 if (wait_threshold != 0) {
223 waitEnd = NanoTime() / 1000;
224 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700225 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700226
227 if (wait_threshold != 0) {
228 uint64_t wait_ms = (waitEnd - waitStart) / 1000;
229 uint32_t sample_percent;
230 if (wait_ms >= wait_threshold) {
231 sample_percent = 100;
232 } else {
233 sample_percent = 100 * wait_ms / wait_threshold;
234 }
235 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
jeffhao33dc7712011-11-09 17:54:24 -0800236 const char* current_locking_filename;
237 uint32_t current_locking_line_number;
Ian Rogers0399dde2012-06-06 17:09:28 -0700238 TranslateLocation(current_locking_method, current_locking_dex_pc,
jeffhao33dc7712011-11-09 17:54:24 -0800239 current_locking_filename, current_locking_line_number);
240 LogContentionEvent(self, wait_ms, sample_percent, current_locking_filename, current_locking_line_number);
Elliott Hughesfc861622011-10-17 17:57:47 -0700241 }
242 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700243 }
244 owner_ = self;
245 DCHECK_EQ(lock_count_, 0);
246
247 // When debugging, save the current monitor holder for future
248 // acquisition failures to use in sampled logging.
Elliott Hughesfc861622011-10-17 17:57:47 -0700249 if (lock_profiling_threshold_ != 0) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700250 locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
Elliott Hughesfc861622011-10-17 17:57:47 -0700251 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700252}
253
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800254static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
255 __attribute__((format(printf, 1, 2)));
256
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700257static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700258 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800259 va_list args;
260 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800261 Thread* self = Thread::Current();
262 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
263 self->ThrowNewExceptionV(throw_location, "Ljava/lang/IllegalMonitorStateException;", fmt, args);
Brian Carlstrom64277f32012-03-26 23:53:34 -0700264 if (!Runtime::Current()->IsStarted()) {
265 std::ostringstream ss;
Ian Rogers62d6c772013-02-27 08:32:07 -0800266 self->Dump(ss);
Ian Rogers049e7a32013-09-11 10:35:34 -0700267 LOG(ERROR) << self->GetException(NULL)->Dump() << "\n" << ss.str();
Brian Carlstrom64277f32012-03-26 23:53:34 -0700268 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800269 va_end(args);
270}
271
Elliott Hughesd4237412012-02-21 11:24:45 -0800272static std::string ThreadToString(Thread* thread) {
273 if (thread == NULL) {
274 return "NULL";
275 }
276 std::ostringstream oss;
277 // TODO: alternatively, we could just return the thread's name.
278 oss << *thread;
279 return oss.str();
280}
281
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800282void Monitor::FailedUnlock(mirror::Object* o, Thread* expected_owner, Thread* found_owner,
Elliott Hughesffb465f2012-03-01 18:46:05 -0800283 Monitor* monitor) {
284 Thread* current_owner = NULL;
285 std::string current_owner_string;
286 std::string expected_owner_string;
287 std::string found_owner_string;
288 {
289 // TODO: isn't this too late to prevent threads from disappearing?
290 // Acquire thread list lock so threads won't disappear from under us.
Ian Rogers50b35e22012-10-04 10:09:15 -0700291 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Elliott Hughesffb465f2012-03-01 18:46:05 -0800292 // Re-read owner now that we hold lock.
293 current_owner = (monitor != NULL) ? monitor->owner_ : NULL;
294 // Get short descriptions of the threads involved.
295 current_owner_string = ThreadToString(current_owner);
296 expected_owner_string = ThreadToString(expected_owner);
297 found_owner_string = ThreadToString(found_owner);
298 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800299 if (current_owner == NULL) {
300 if (found_owner == NULL) {
301 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
302 " on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800303 PrettyTypeOf(o).c_str(),
304 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800305 } else {
306 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800307 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
308 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800309 found_owner_string.c_str(),
310 PrettyTypeOf(o).c_str(),
311 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800312 }
313 } else {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800314 if (found_owner == NULL) {
315 // Race: originally there was no owner, there is now
316 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
317 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800318 current_owner_string.c_str(),
319 PrettyTypeOf(o).c_str(),
320 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800321 } else {
322 if (found_owner != current_owner) {
323 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800324 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
325 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800326 found_owner_string.c_str(),
327 current_owner_string.c_str(),
328 PrettyTypeOf(o).c_str(),
329 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800330 } else {
331 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
332 " on thread '%s",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800333 current_owner_string.c_str(),
334 PrettyTypeOf(o).c_str(),
335 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800336 }
337 }
338 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700339}
340
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700341bool Monitor::Unlock(Thread* self, bool for_wait) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700342 DCHECK(self != NULL);
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800343 Thread* owner = owner_;
344 if (owner == self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700345 // We own the monitor, so nobody else can be in here.
346 if (lock_count_ == 0) {
347 owner_ = NULL;
jeffhao33dc7712011-11-09 17:54:24 -0800348 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700349 locking_dex_pc_ = 0;
Ian Rogers81d425b2012-09-27 16:03:43 -0700350 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700351 } else {
352 --lock_count_;
353 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700354 } else if (for_wait) {
355 // Wait should have already cleared the fields.
356 DCHECK_EQ(lock_count_, 0);
357 DCHECK(owner == NULL);
358 DCHECK(locking_method_ == NULL);
359 DCHECK_EQ(locking_dex_pc_, 0u);
Ian Rogers81d425b2012-09-27 16:03:43 -0700360 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700361 } else {
362 // We don't own this, so we're not allowed to unlock it.
363 // The JNI spec says that we should throw IllegalMonitorStateException
364 // in this case.
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800365 FailedUnlock(obj_, self, owner, this);
Elliott Hughes5f791332011-09-15 17:45:30 -0700366 return false;
367 }
368 return true;
369}
370
Elliott Hughes5f791332011-09-15 17:45:30 -0700371/*
372 * Wait on a monitor until timeout, interrupt, or notification. Used for
373 * Object.wait() and (somewhat indirectly) Thread.sleep() and Thread.join().
374 *
375 * If another thread calls Thread.interrupt(), we throw InterruptedException
376 * and return immediately if one of the following are true:
377 * - blocked in wait(), wait(long), or wait(long, int) methods of Object
378 * - blocked in join(), join(long), or join(long, int) methods of Thread
379 * - blocked in sleep(long), or sleep(long, int) methods of Thread
380 * Otherwise, we set the "interrupted" flag.
381 *
382 * Checks to make sure that "ns" is in the range 0-999999
383 * (i.e. fractions of a millisecond) and throws the appropriate
384 * exception if it isn't.
385 *
386 * The spec allows "spurious wakeups", and recommends that all code using
387 * Object.wait() do so in a loop. This appears to derive from concerns
388 * about pthread_cond_wait() on multiprocessor systems. Some commentary
389 * on the web casts doubt on whether these can/should occur.
390 *
391 * Since we're allowed to wake up "early", we clamp extremely long durations
392 * to return at the end of the 32-bit time epoch.
393 */
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800394void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
395 bool interruptShouldThrow, ThreadState why) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700396 DCHECK(self != NULL);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800397 DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
Elliott Hughes5f791332011-09-15 17:45:30 -0700398
399 // Make sure that we hold the lock.
400 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800401 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700402 return;
403 }
Ian Rogers50b35e22012-10-04 10:09:15 -0700404 monitor_lock_.AssertHeld(self);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800405
Elliott Hughesdf42c482013-01-09 12:49:02 -0800406 // We need to turn a zero-length timed wait into a regular wait because
407 // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
408 if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
409 why = kWaiting;
410 }
411
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800412 WaitWithLock(self, ms, ns, interruptShouldThrow, why);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700413}
Elliott Hughes5f791332011-09-15 17:45:30 -0700414
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800415void Monitor::WaitWithLock(Thread* self, int64_t ms, int32_t ns,
416 bool interruptShouldThrow, ThreadState why) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700417 // Enforce the timeout range.
418 if (ms < 0 || ns < 0 || ns > 999999) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800419 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
420 self->ThrowNewExceptionF(throw_location, "Ljava/lang/IllegalArgumentException;",
421 "timeout arguments out of range: ms=%lld ns=%d", ms, ns);
Elliott Hughes5f791332011-09-15 17:45:30 -0700422 return;
423 }
424
Elliott Hughes5f791332011-09-15 17:45:30 -0700425 /*
426 * Add ourselves to the set of threads waiting on this monitor, and
427 * release our hold. We need to let it go even if we're a few levels
428 * deep in a recursive lock, and we need to restore that later.
429 *
430 * We append to the wait set ahead of clearing the count and owner
431 * fields so the subroutine can check that the calling thread owns
432 * the monitor. Aside from that, the order of member updates is
433 * not order sensitive as we hold the pthread mutex.
434 */
435 AppendToWaitSet(self);
Ian Rogers0399dde2012-06-06 17:09:28 -0700436 int prev_lock_count = lock_count_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700437 lock_count_ = 0;
438 owner_ = NULL;
Brian Carlstromea46f952013-07-30 01:26:50 -0700439 const mirror::ArtMethod* saved_method = locking_method_;
jeffhao33dc7712011-11-09 17:54:24 -0800440 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700441 uintptr_t saved_dex_pc = locking_dex_pc_;
442 locking_dex_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700443
444 /*
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800445 * Update thread state. If the GC wakes up, it'll ignore us, knowing
Elliott Hughes5f791332011-09-15 17:45:30 -0700446 * that we won't touch any references in this state, and we'll check
447 * our suspend mode before we transition out.
448 */
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800449 self->TransitionFromRunnableToSuspended(why);
Elliott Hughes5f791332011-09-15 17:45:30 -0700450
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800451 bool was_interrupted = false;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700452 {
453 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
Ian Rogers50b35e22012-10-04 10:09:15 -0700454 MutexLock mu(self, *self->wait_mutex_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700455
456 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
457 // non-NULL a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
458 // up.
459 DCHECK(self->wait_monitor_ == NULL);
460 self->wait_monitor_ = this;
461
462 // Release the monitor lock.
463 Unlock(self, true);
464
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800465 // Handle the case where the thread was interrupted before we called wait().
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700466 if (self->interrupted_) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800467 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700468 } else {
469 // Wait for a notification or a timeout to occur.
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800470 if (why == kWaiting) {
Ian Rogersc604d732012-10-14 16:09:54 -0700471 self->wait_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700472 } else {
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800473 DCHECK(why == kTimedWaiting || why == kSleeping) << why;
Ian Rogersc604d732012-10-14 16:09:54 -0700474 self->wait_cond_->TimedWait(self, ms, ns);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700475 }
476 if (self->interrupted_) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800477 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700478 }
479 self->interrupted_ = false;
480 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700481 }
482
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700483 // Set self->status back to kRunnable, and self-suspend if needed.
484 self->TransitionFromSuspendedToRunnable();
Elliott Hughes5f791332011-09-15 17:45:30 -0700485
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800486 {
487 // We reset the thread's wait_monitor_ field after transitioning back to runnable so
488 // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
489 // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
490 // are waiting on "null".)
491 MutexLock mu(self, *self->wait_mutex_);
492 DCHECK(self->wait_monitor_ != NULL);
493 self->wait_monitor_ = NULL;
494 }
495
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700496 // Re-acquire the monitor lock.
Elliott Hughes5f791332011-09-15 17:45:30 -0700497 Lock(self);
498
Ian Rogers81d425b2012-09-27 16:03:43 -0700499 self->wait_mutex_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700500
Elliott Hughes5f791332011-09-15 17:45:30 -0700501 /*
502 * We remove our thread from wait set after restoring the count
503 * and owner fields so the subroutine can check that the calling
504 * thread owns the monitor. Aside from that, the order of member
505 * updates is not order sensitive as we hold the pthread mutex.
506 */
507 owner_ = self;
Ian Rogers0399dde2012-06-06 17:09:28 -0700508 lock_count_ = prev_lock_count;
509 locking_method_ = saved_method;
510 locking_dex_pc_ = saved_dex_pc;
Elliott Hughes5f791332011-09-15 17:45:30 -0700511 RemoveFromWaitSet(self);
512
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800513 if (was_interrupted) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700514 /*
515 * We were interrupted while waiting, or somebody interrupted an
516 * un-interruptible thread earlier and we're bailing out immediately.
517 *
518 * The doc sayeth: "The interrupted status of the current thread is
519 * cleared when this exception is thrown."
520 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700521 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700522 MutexLock mu(self, *self->wait_mutex_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700523 self->interrupted_ = false;
524 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700525 if (interruptShouldThrow) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800526 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
527 self->ThrowNewException(throw_location, "Ljava/lang/InterruptedException;", NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700528 }
529 }
530}
531
532void Monitor::Notify(Thread* self) {
533 DCHECK(self != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700534 // Make sure that we hold the lock.
535 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800536 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700537 return;
538 }
Ian Rogers50b35e22012-10-04 10:09:15 -0700539 monitor_lock_.AssertHeld(self);
540 NotifyWithLock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700541}
542
Ian Rogers50b35e22012-10-04 10:09:15 -0700543void Monitor::NotifyWithLock(Thread* self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700544 // Signal the first waiting thread in the wait set.
545 while (wait_set_ != NULL) {
546 Thread* thread = wait_set_;
547 wait_set_ = thread->wait_next_;
548 thread->wait_next_ = NULL;
549
550 // Check to see if the thread is still waiting.
Ian Rogers50b35e22012-10-04 10:09:15 -0700551 MutexLock mu(self, *thread->wait_mutex_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700552 if (thread->wait_monitor_ != NULL) {
Ian Rogersc604d732012-10-14 16:09:54 -0700553 thread->wait_cond_->Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700554 return;
555 }
556 }
557}
558
559void Monitor::NotifyAll(Thread* self) {
560 DCHECK(self != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700561 // Make sure that we hold the lock.
562 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800563 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700564 return;
565 }
Ian Rogers50b35e22012-10-04 10:09:15 -0700566 monitor_lock_.AssertHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700567 NotifyAllWithLock();
568}
569
570void Monitor::NotifyAllWithLock() {
Elliott Hughes5f791332011-09-15 17:45:30 -0700571 // Signal all threads in the wait set.
572 while (wait_set_ != NULL) {
573 Thread* thread = wait_set_;
574 wait_set_ = thread->wait_next_;
575 thread->wait_next_ = NULL;
576 thread->Notify();
577 }
578}
579
580/*
581 * Changes the shape of a monitor from thin to fat, preserving the
582 * internal lock state. The calling thread must own the lock.
583 */
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800584void Monitor::Inflate(Thread* self, mirror::Object* obj) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700585 DCHECK(self != NULL);
586 DCHECK(obj != NULL);
587 DCHECK_EQ(LW_SHAPE(*obj->GetRawLockWordAddress()), LW_SHAPE_THIN);
Elliott Hughesf8e01272011-10-17 11:29:05 -0700588 DCHECK_EQ(LW_LOCK_OWNER(*obj->GetRawLockWordAddress()), static_cast<int32_t>(self->GetThinLockId()));
Elliott Hughes5f791332011-09-15 17:45:30 -0700589
590 // Allocate and acquire a new monitor.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700591 Monitor* m = new Monitor(self, obj);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800592 VLOG(monitor) << "monitor: thread " << self->GetThinLockId()
593 << " created monitor " << m << " for object " << obj;
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700594 Runtime::Current()->GetMonitorList()->Add(m);
Elliott Hughes5f791332011-09-15 17:45:30 -0700595}
596
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800597void Monitor::MonitorEnter(Thread* self, mirror::Object* obj) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700598 volatile int32_t* thinp = obj->GetRawLockWordAddress();
Elliott Hughes398f64b2012-03-26 18:05:48 -0700599 uint32_t sleepDelayNs;
600 uint32_t minSleepDelayNs = 1000000; /* 1 millisecond */
601 uint32_t maxSleepDelayNs = 1000000000; /* 1 second */
Elliott Hughesf8e01272011-10-17 11:29:05 -0700602 uint32_t thin, newThin;
Elliott Hughes5f791332011-09-15 17:45:30 -0700603
Elliott Hughes4681c802011-09-25 18:04:37 -0700604 DCHECK(self != NULL);
605 DCHECK(obj != NULL);
Elliott Hughesf8e01272011-10-17 11:29:05 -0700606 uint32_t threadId = self->GetThinLockId();
Elliott Hughesa21039c2012-06-21 12:09:25 -0700607 retry:
Elliott Hughes5f791332011-09-15 17:45:30 -0700608 thin = *thinp;
609 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
610 /*
611 * The lock is a thin lock. The owner field is used to
612 * determine the acquire method, ordered by cost.
613 */
614 if (LW_LOCK_OWNER(thin) == threadId) {
615 /*
616 * The calling thread owns the lock. Increment the
617 * value of the recursion count field.
618 */
619 *thinp += 1 << LW_LOCK_COUNT_SHIFT;
620 if (LW_LOCK_COUNT(*thinp) == LW_LOCK_COUNT_MASK) {
621 /*
622 * The reacquisition limit has been reached. Inflate
623 * the lock so the next acquire will not overflow the
624 * recursion count field.
625 */
626 Inflate(self, obj);
627 }
628 } else if (LW_LOCK_OWNER(thin) == 0) {
Elliott Hughes81ff3182012-03-23 20:35:56 -0700629 // The lock is unowned. Install the thread id of the calling thread into the owner field.
630 // This is the common case: compiled code will have tried this before calling back into
631 // the runtime.
Elliott Hughes5f791332011-09-15 17:45:30 -0700632 newThin = thin | (threadId << LW_LOCK_OWNER_SHIFT);
633 if (android_atomic_acquire_cas(thin, newThin, thinp) != 0) {
634 // The acquire failed. Try again.
635 goto retry;
636 }
637 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800638 VLOG(monitor) << StringPrintf("monitor: thread %d spin on lock %p (a %s) owned by %d",
Elliott Hughes81ff3182012-03-23 20:35:56 -0700639 threadId, thinp, PrettyTypeOf(obj).c_str(), LW_LOCK_OWNER(thin));
640 // The lock is owned by another thread. Notify the runtime that we are about to wait.
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700641 self->monitor_enter_object_ = obj;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700642 self->TransitionFromRunnableToSuspended(kBlocked);
Elliott Hughes5f791332011-09-15 17:45:30 -0700643 // Spin until the thin lock is released or inflated.
644 sleepDelayNs = 0;
645 for (;;) {
646 thin = *thinp;
647 // Check the shape of the lock word. Another thread
648 // may have inflated the lock while we were waiting.
649 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
650 if (LW_LOCK_OWNER(thin) == 0) {
651 // The lock has been released. Install the thread id of the
652 // calling thread into the owner field.
653 newThin = thin | (threadId << LW_LOCK_OWNER_SHIFT);
654 if (android_atomic_acquire_cas(thin, newThin, thinp) == 0) {
655 // The acquire succeed. Break out of the loop and proceed to inflate the lock.
656 break;
657 }
658 } else {
659 // The lock has not been released. Yield so the owning thread can run.
660 if (sleepDelayNs == 0) {
661 sched_yield();
662 sleepDelayNs = minSleepDelayNs;
663 } else {
Ian Rogers56edc432013-01-18 16:51:51 -0800664 NanoSleep(sleepDelayNs);
Elliott Hughes5f791332011-09-15 17:45:30 -0700665 // Prepare the next delay value. Wrap to avoid once a second polls for eternity.
666 if (sleepDelayNs < maxSleepDelayNs / 2) {
667 sleepDelayNs *= 2;
668 } else {
669 sleepDelayNs = minSleepDelayNs;
670 }
671 }
672 }
673 } else {
Elliott Hughes81ff3182012-03-23 20:35:56 -0700674 // The thin lock was inflated by another thread. Let the runtime know we are no longer
Elliott Hughes5f791332011-09-15 17:45:30 -0700675 // waiting and try again.
Elliott Hughes398f64b2012-03-26 18:05:48 -0700676 VLOG(monitor) << StringPrintf("monitor: thread %d found lock %p surprise-fattened by another thread", threadId, thinp);
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700677 self->monitor_enter_object_ = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700678 self->TransitionFromSuspendedToRunnable();
Elliott Hughes5f791332011-09-15 17:45:30 -0700679 goto retry;
680 }
681 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800682 VLOG(monitor) << StringPrintf("monitor: thread %d spin on lock %p done", threadId, thinp);
Elliott Hughes81ff3182012-03-23 20:35:56 -0700683 // We have acquired the thin lock. Let the runtime know that we are no longer waiting.
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700684 self->monitor_enter_object_ = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700685 self->TransitionFromSuspendedToRunnable();
Elliott Hughes5f791332011-09-15 17:45:30 -0700686 // Fatten the lock.
687 Inflate(self, obj);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800688 VLOG(monitor) << StringPrintf("monitor: thread %d fattened lock %p", threadId, thinp);
Elliott Hughes5f791332011-09-15 17:45:30 -0700689 }
690 } else {
691 // The lock is a fat lock.
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800692 VLOG(monitor) << StringPrintf("monitor: thread %d locking fat lock %p (%p) %p on a %s",
Elliott Hughes398f64b2012-03-26 18:05:48 -0700693 threadId, thinp, LW_MONITOR(*thinp),
694 reinterpret_cast<void*>(*thinp), PrettyTypeOf(obj).c_str());
Elliott Hughes5f791332011-09-15 17:45:30 -0700695 DCHECK(LW_MONITOR(*thinp) != NULL);
696 LW_MONITOR(*thinp)->Lock(self);
697 }
698}
699
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800700bool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700701 volatile int32_t* thinp = obj->GetRawLockWordAddress();
702
703 DCHECK(self != NULL);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700704 // DCHECK_EQ(self->GetState(), kRunnable);
Elliott Hughes5f791332011-09-15 17:45:30 -0700705 DCHECK(obj != NULL);
706
707 /*
708 * Cache the lock word as its value can change while we are
709 * examining its state.
710 */
711 uint32_t thin = *thinp;
712 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
713 /*
714 * The lock is thin. We must ensure that the lock is owned
715 * by the given thread before unlocking it.
716 */
Elliott Hughesf8e01272011-10-17 11:29:05 -0700717 if (LW_LOCK_OWNER(thin) == self->GetThinLockId()) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700718 /*
719 * We are the lock owner. It is safe to update the lock
720 * without CAS as lock ownership guards the lock itself.
721 */
722 if (LW_LOCK_COUNT(thin) == 0) {
723 /*
724 * The lock was not recursively acquired, the common
725 * case. Unlock by clearing all bits except for the
726 * hash state.
727 */
728 thin &= (LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT);
729 android_atomic_release_store(thin, thinp);
730 } else {
731 /*
732 * The object was recursively acquired. Decrement the
733 * lock recursion count field.
734 */
735 *thinp -= 1 << LW_LOCK_COUNT_SHIFT;
736 }
737 } else {
738 /*
739 * We do not own the lock. The JVM spec requires that we
740 * throw an exception in this case.
741 */
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800742 FailedUnlock(obj, self, NULL, NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700743 return false;
744 }
745 } else {
746 /*
747 * The lock is fat. We must check to see if Unlock has
748 * raised any exceptions before continuing.
749 */
750 DCHECK(LW_MONITOR(*thinp) != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700751 if (!LW_MONITOR(*thinp)->Unlock(self, false)) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700752 // An exception has been raised. Do not fall through.
753 return false;
754 }
755 }
756 return true;
757}
758
759/*
760 * Object.wait(). Also called for class init.
761 */
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800762void Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800763 bool interruptShouldThrow, ThreadState why) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700764 volatile int32_t* thinp = obj->GetRawLockWordAddress();
765
766 // If the lock is still thin, we need to fatten it.
767 uint32_t thin = *thinp;
768 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
769 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700770 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800771 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700772 return;
773 }
774
775 /* This thread holds the lock. We need to fatten the lock
776 * so 'self' can block on it. Don't update the object lock
777 * field yet, because 'self' needs to acquire the lock before
778 * any other thread gets a chance.
779 */
780 Inflate(self, obj);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800781 VLOG(monitor) << StringPrintf("monitor: thread %d fattened lock %p by wait()", self->GetThinLockId(), thinp);
Elliott Hughes5f791332011-09-15 17:45:30 -0700782 }
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800783 LW_MONITOR(*thinp)->Wait(self, ms, ns, interruptShouldThrow, why);
Elliott Hughes5f791332011-09-15 17:45:30 -0700784}
785
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800786void Monitor::Notify(Thread* self, mirror::Object *obj) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700787 uint32_t thin = *obj->GetRawLockWordAddress();
788
789 // If the lock is still thin, there aren't any waiters;
790 // waiting on an object forces lock fattening.
791 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
792 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700793 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800794 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700795 return;
796 }
797 // no-op; there are no waiters to notify.
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700798 // We inflate here in case the Notify is in a tight loop. Without inflation here the waiter
799 // will struggle to get in. Bug 6961405.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700800 Inflate(self, obj);
Elliott Hughes5f791332011-09-15 17:45:30 -0700801 } else {
802 // It's a fat lock.
803 LW_MONITOR(thin)->Notify(self);
804 }
805}
806
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800807void Monitor::NotifyAll(Thread* self, mirror::Object *obj) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700808 uint32_t thin = *obj->GetRawLockWordAddress();
809
810 // If the lock is still thin, there aren't any waiters;
811 // waiting on an object forces lock fattening.
812 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
813 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700814 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800815 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700816 return;
817 }
818 // no-op; there are no waiters to notify.
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700819 // We inflate here in case the NotifyAll is in a tight loop. Without inflation here the waiter
820 // will struggle to get in. Bug 6961405.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700821 Inflate(self, obj);
Elliott Hughes5f791332011-09-15 17:45:30 -0700822 } else {
823 // It's a fat lock.
824 LW_MONITOR(thin)->NotifyAll(self);
825 }
826}
827
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -0700828uint32_t Monitor::GetThinLockId(uint32_t raw_lock_word) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700829 if (LW_SHAPE(raw_lock_word) == LW_SHAPE_THIN) {
830 return LW_LOCK_OWNER(raw_lock_word);
831 } else {
832 Thread* owner = LW_MONITOR(raw_lock_word)->owner_;
833 return owner ? owner->GetThinLockId() : 0;
834 }
835}
836
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700837void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800838 ThreadState state = thread->GetState();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700839
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800840 mirror::Object* object = NULL;
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700841 uint32_t lock_owner = ThreadList::kInvalidId;
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800842 if (state == kWaiting || state == kTimedWaiting || state == kSleeping) {
843 if (state == kSleeping) {
844 os << " - sleeping on ";
845 } else {
846 os << " - waiting on ";
847 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700848 {
Elliott Hughesf9501702013-01-11 11:22:27 -0800849 Thread* self = Thread::Current();
850 MutexLock mu(self, *thread->wait_mutex_);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800851 Monitor* monitor = thread->wait_monitor_;
852 if (monitor != NULL) {
853 object = monitor->obj_;
854 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700855 }
Elliott Hughes34e06962012-04-09 13:55:55 -0700856 } else if (state == kBlocked) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700857 os << " - waiting to lock ";
858 object = thread->monitor_enter_object_;
859 if (object != NULL) {
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -0700860 lock_owner = object->GetThinLockId();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700861 }
862 } else {
863 // We're not waiting on anything.
864 return;
865 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700866
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700867 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700868 os << "<" << object << "> (a " << PrettyTypeOf(object) << ")";
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700869
Elliott Hughesc5dc2ff2013-01-09 13:44:30 -0800870 // - waiting to lock <0x613f83d8> (a java.lang.Object) held by thread 5
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700871 if (lock_owner != ThreadList::kInvalidId) {
872 os << " held by thread " << lock_owner;
873 }
874
875 os << "\n";
876}
877
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800878mirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800879 // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
880 // definition of contended that includes a monitor a thread is trying to enter...
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800881 mirror::Object* result = thread->monitor_enter_object_;
Elliott Hughesf9501702013-01-11 11:22:27 -0800882 if (result != NULL) {
883 return result;
884 }
885 // ...but also a monitor that the thread is waiting on.
886 {
887 MutexLock mu(Thread::Current(), *thread->wait_mutex_);
888 Monitor* monitor = thread->wait_monitor_;
889 if (monitor != NULL) {
890 return monitor->obj_;
891 }
892 }
893 return NULL;
894}
895
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800896void Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
897 void* callback_context) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700898 mirror::ArtMethod* m = stack_visitor->GetMethod();
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700899 CHECK(m != NULL);
900
901 // Native methods are an easy special case.
902 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
903 if (m->IsNative()) {
904 if (m->IsSynchronized()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800905 mirror::Object* jni_this = stack_visitor->GetCurrentSirt()->GetReference(0);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800906 callback(jni_this, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700907 }
908 return;
909 }
910
jeffhao61f916c2012-10-25 17:48:51 -0700911 // Proxy methods should not be synchronized.
912 if (m->IsProxyMethod()) {
913 CHECK(!m->IsSynchronized());
914 return;
915 }
916
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700917 // <clinit> is another special case. The runtime holds the class lock while calling <clinit>.
918 MethodHelper mh(m);
919 if (mh.IsClassInitializer()) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800920 callback(m->GetDeclaringClass(), callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700921 // Fall through because there might be synchronization in the user code too.
922 }
923
924 // Is there any reason to believe there's any synchronization in this method?
925 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -0700926 CHECK(code_item != NULL) << PrettyMethod(m);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700927 if (code_item->tries_size_ == 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700928 return; // No "tries" implies no synchronization, so no held locks to report.
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700929 }
930
Elliott Hughes80537bb2013-01-04 16:37:26 -0800931 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
932 // the locks held in this stack frame.
933 std::vector<uint32_t> monitor_enter_dex_pcs;
934 verifier::MethodVerifier::FindLocksAtDexPc(m, stack_visitor->GetDexPc(), monitor_enter_dex_pcs);
935 if (monitor_enter_dex_pcs.empty()) {
936 return;
937 }
938
Elliott Hughes80537bb2013-01-04 16:37:26 -0800939 for (size_t i = 0; i < monitor_enter_dex_pcs.size(); ++i) {
940 // The verifier works in terms of the dex pcs of the monitor-enter instructions.
941 // We want the registers used by those instructions (so we can read the values out of them).
942 uint32_t dex_pc = monitor_enter_dex_pcs[i];
943 uint16_t monitor_enter_instruction = code_item->insns_[dex_pc];
944
945 // Quick sanity check.
946 if ((monitor_enter_instruction & 0xff) != Instruction::MONITOR_ENTER) {
947 LOG(FATAL) << "expected monitor-enter @" << dex_pc << "; was "
948 << reinterpret_cast<void*>(monitor_enter_instruction);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700949 }
950
Elliott Hughes80537bb2013-01-04 16:37:26 -0800951 uint16_t monitor_register = ((monitor_enter_instruction >> 8) & 0xff);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800952 mirror::Object* o = reinterpret_cast<mirror::Object*>(stack_visitor->GetVReg(m, monitor_register,
953 kReferenceVReg));
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800954 callback(o, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700955 }
956}
957
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700958bool Monitor::IsValidLockWord(int32_t lock_word) {
959 if (lock_word == 0) {
960 return true;
961 } else if (LW_SHAPE(lock_word) == LW_SHAPE_FAT) {
962 Monitor* mon = LW_MONITOR(lock_word);
963 MonitorList* list = Runtime::Current()->GetMonitorList();
964 MutexLock mu(Thread::Current(), list->monitor_list_lock_);
965 bool found = false;
966 for (Monitor* list_mon : list->list_) {
967 if (mon == list_mon) {
968 found = true;
969 break;
970 }
971 }
972 return found;
973 } else {
974 // TODO: thin lock validity checking.
975 return LW_SHAPE(lock_word) == LW_SHAPE_THIN;
976 }
977}
978
Brian Carlstromea46f952013-07-30 01:26:50 -0700979void Monitor::TranslateLocation(const mirror::ArtMethod* method, uint32_t dex_pc,
jeffhao33dc7712011-11-09 17:54:24 -0800980 const char*& source_file, uint32_t& line_number) const {
981 // If method is null, location is unknown
982 if (method == NULL) {
Elliott Hughes12c51e32012-01-17 20:25:05 -0800983 source_file = "";
jeffhao33dc7712011-11-09 17:54:24 -0800984 line_number = 0;
985 return;
986 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800987 MethodHelper mh(method);
988 source_file = mh.GetDeclaringClassSourceFile();
Elliott Hughes12c51e32012-01-17 20:25:05 -0800989 if (source_file == NULL) {
990 source_file = "";
991 }
Ian Rogers0399dde2012-06-06 17:09:28 -0700992 line_number = mh.GetLineNumFromDexPC(dex_pc);
jeffhao33dc7712011-11-09 17:54:24 -0800993}
994
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700995MonitorList::MonitorList() : monitor_list_lock_("MonitorList lock") {
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700996}
997
998MonitorList::~MonitorList() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700999 MutexLock mu(Thread::Current(), monitor_list_lock_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001000 STLDeleteElements(&list_);
1001}
1002
1003void MonitorList::Add(Monitor* m) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001004 MutexLock mu(Thread::Current(), monitor_list_lock_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001005 list_.push_front(m);
1006}
1007
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001008void MonitorList::SweepMonitorList(RootVisitor visitor, void* arg) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001009 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001010 for (auto it = list_.begin(); it != list_.end(); ) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001011 Monitor* m = *it;
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001012 mirror::Object* obj = m->GetObject();
1013 mirror::Object* new_obj = visitor(obj, arg);
1014 if (new_obj == nullptr) {
1015 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
1016 << m->GetObject();
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001017 delete m;
1018 it = list_.erase(it);
1019 } else {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001020 m->SetObject(new_obj);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001021 ++it;
1022 }
1023 }
1024}
1025
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001026MonitorInfo::MonitorInfo(mirror::Object* o) : owner(NULL), entry_count(0) {
Elliott Hughesf327e072013-01-09 16:01:26 -08001027 uint32_t lock_word = *o->GetRawLockWordAddress();
1028 if (LW_SHAPE(lock_word) == LW_SHAPE_THIN) {
1029 uint32_t owner_thin_lock_id = LW_LOCK_OWNER(lock_word);
1030 if (owner_thin_lock_id != 0) {
1031 owner = Runtime::Current()->GetThreadList()->FindThreadByThinLockId(owner_thin_lock_id);
1032 entry_count = 1 + LW_LOCK_COUNT(lock_word);
1033 }
1034 // Thin locks have no waiters.
1035 } else {
1036 CHECK_EQ(LW_SHAPE(lock_word), LW_SHAPE_FAT);
1037 Monitor* monitor = LW_MONITOR(lock_word);
1038 owner = monitor->owner_;
1039 entry_count = 1 + monitor->lock_count_;
1040 for (Thread* waiter = monitor->wait_set_; waiter != NULL; waiter = waiter->wait_next_) {
1041 waiters.push_back(waiter);
1042 }
1043 }
1044}
1045
Elliott Hughes5f791332011-09-15 17:45:30 -07001046} // namespace art