blob: 09a952b3cfb9d11ef93f1bf3eab15d3e6ceea4c9 [file] [log] [blame]
Elliott Hughes5f791332011-09-15 17:45:30 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Elliott Hughes54e7df12011-09-16 11:47:04 -070017#include "monitor.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070018
Elliott Hughes08fc03a2012-06-26 17:34:00 -070019#include <vector>
20
Elliott Hughes76b61672012-12-12 17:47:30 -080021#include "base/mutex.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080022#include "base/stl_util.h"
jeffhao33dc7712011-11-09 17:54:24 -080023#include "class_linker.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070024#include "dex_file-inl.h"
Elliott Hughes08fc03a2012-06-26 17:34:00 -070025#include "dex_instruction.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080026#include "mirror/abstract_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
Elliott Hughes5f791332011-09-15 17:45:30 -0700197void Monitor::Lock(Thread* self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700198 if (owner_ == self) {
199 lock_count_++;
200 return;
201 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700202
Ian Rogers81d425b2012-09-27 16:03:43 -0700203 if (!monitor_lock_.TryLock(self)) {
Mathieu Chartier2542d662012-06-21 17:14:11 -0700204 uint64_t waitStart = 0;
205 uint64_t waitEnd = 0;
Elliott Hughesfc861622011-10-17 17:57:47 -0700206 uint32_t wait_threshold = lock_profiling_threshold_;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800207 const mirror::AbstractMethod* current_locking_method = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700208 uint32_t current_locking_dex_pc = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700209 {
Elliott Hughes34e06962012-04-09 13:55:55 -0700210 ScopedThreadStateChange tsc(self, kBlocked);
Elliott Hughesfc861622011-10-17 17:57:47 -0700211 if (wait_threshold != 0) {
212 waitStart = NanoTime() / 1000;
213 }
jeffhao33dc7712011-11-09 17:54:24 -0800214 current_locking_method = locking_method_;
Ian Rogers0399dde2012-06-06 17:09:28 -0700215 current_locking_dex_pc = locking_dex_pc_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700216
Ian Rogers81d425b2012-09-27 16:03:43 -0700217 monitor_lock_.Lock(self);
Elliott Hughesfc861622011-10-17 17:57:47 -0700218 if (wait_threshold != 0) {
219 waitEnd = NanoTime() / 1000;
220 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700221 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700222
223 if (wait_threshold != 0) {
224 uint64_t wait_ms = (waitEnd - waitStart) / 1000;
225 uint32_t sample_percent;
226 if (wait_ms >= wait_threshold) {
227 sample_percent = 100;
228 } else {
229 sample_percent = 100 * wait_ms / wait_threshold;
230 }
231 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
jeffhao33dc7712011-11-09 17:54:24 -0800232 const char* current_locking_filename;
233 uint32_t current_locking_line_number;
Ian Rogers0399dde2012-06-06 17:09:28 -0700234 TranslateLocation(current_locking_method, current_locking_dex_pc,
jeffhao33dc7712011-11-09 17:54:24 -0800235 current_locking_filename, current_locking_line_number);
236 LogContentionEvent(self, wait_ms, sample_percent, current_locking_filename, current_locking_line_number);
Elliott Hughesfc861622011-10-17 17:57:47 -0700237 }
238 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700239 }
240 owner_ = self;
241 DCHECK_EQ(lock_count_, 0);
242
243 // When debugging, save the current monitor holder for future
244 // acquisition failures to use in sampled logging.
Elliott Hughesfc861622011-10-17 17:57:47 -0700245 if (lock_profiling_threshold_ != 0) {
Ian Rogers0399dde2012-06-06 17:09:28 -0700246 locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
Elliott Hughesfc861622011-10-17 17:57:47 -0700247 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700248}
249
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800250static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
251 __attribute__((format(printf, 1, 2)));
252
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700253static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700254 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800255 va_list args;
256 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800257 Thread* self = Thread::Current();
258 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
259 self->ThrowNewExceptionV(throw_location, "Ljava/lang/IllegalMonitorStateException;", fmt, args);
Brian Carlstrom64277f32012-03-26 23:53:34 -0700260 if (!Runtime::Current()->IsStarted()) {
261 std::ostringstream ss;
Ian Rogers62d6c772013-02-27 08:32:07 -0800262 self->Dump(ss);
Brian Carlstrom64277f32012-03-26 23:53:34 -0700263 std::string str(ss.str());
264 LOG(ERROR) << "IllegalMonitorStateException: " << str;
265 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800266 va_end(args);
267}
268
Elliott Hughesd4237412012-02-21 11:24:45 -0800269static std::string ThreadToString(Thread* thread) {
270 if (thread == NULL) {
271 return "NULL";
272 }
273 std::ostringstream oss;
274 // TODO: alternatively, we could just return the thread's name.
275 oss << *thread;
276 return oss.str();
277}
278
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800279void Monitor::FailedUnlock(mirror::Object* o, Thread* expected_owner, Thread* found_owner,
Elliott Hughesffb465f2012-03-01 18:46:05 -0800280 Monitor* monitor) {
281 Thread* current_owner = NULL;
282 std::string current_owner_string;
283 std::string expected_owner_string;
284 std::string found_owner_string;
285 {
286 // TODO: isn't this too late to prevent threads from disappearing?
287 // Acquire thread list lock so threads won't disappear from under us.
Ian Rogers50b35e22012-10-04 10:09:15 -0700288 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Elliott Hughesffb465f2012-03-01 18:46:05 -0800289 // Re-read owner now that we hold lock.
290 current_owner = (monitor != NULL) ? monitor->owner_ : NULL;
291 // Get short descriptions of the threads involved.
292 current_owner_string = ThreadToString(current_owner);
293 expected_owner_string = ThreadToString(expected_owner);
294 found_owner_string = ThreadToString(found_owner);
295 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800296 if (current_owner == NULL) {
297 if (found_owner == NULL) {
298 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
299 " on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800300 PrettyTypeOf(o).c_str(),
301 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800302 } else {
303 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800304 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
305 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800306 found_owner_string.c_str(),
307 PrettyTypeOf(o).c_str(),
308 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800309 }
310 } else {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800311 if (found_owner == NULL) {
312 // Race: originally there was no owner, there is now
313 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
314 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800315 current_owner_string.c_str(),
316 PrettyTypeOf(o).c_str(),
317 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800318 } else {
319 if (found_owner != current_owner) {
320 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800321 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
322 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800323 found_owner_string.c_str(),
324 current_owner_string.c_str(),
325 PrettyTypeOf(o).c_str(),
326 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800327 } else {
328 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
329 " on thread '%s",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800330 current_owner_string.c_str(),
331 PrettyTypeOf(o).c_str(),
332 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800333 }
334 }
335 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700336}
337
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700338bool Monitor::Unlock(Thread* self, bool for_wait) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700339 DCHECK(self != NULL);
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800340 Thread* owner = owner_;
341 if (owner == self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700342 // We own the monitor, so nobody else can be in here.
343 if (lock_count_ == 0) {
344 owner_ = NULL;
jeffhao33dc7712011-11-09 17:54:24 -0800345 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700346 locking_dex_pc_ = 0;
Ian Rogers81d425b2012-09-27 16:03:43 -0700347 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700348 } else {
349 --lock_count_;
350 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700351 } else if (for_wait) {
352 // Wait should have already cleared the fields.
353 DCHECK_EQ(lock_count_, 0);
354 DCHECK(owner == NULL);
355 DCHECK(locking_method_ == NULL);
356 DCHECK_EQ(locking_dex_pc_, 0u);
Ian Rogers81d425b2012-09-27 16:03:43 -0700357 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700358 } else {
359 // We don't own this, so we're not allowed to unlock it.
360 // The JNI spec says that we should throw IllegalMonitorStateException
361 // in this case.
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800362 FailedUnlock(obj_, self, owner, this);
Elliott Hughes5f791332011-09-15 17:45:30 -0700363 return false;
364 }
365 return true;
366}
367
Elliott Hughes5f791332011-09-15 17:45:30 -0700368/*
369 * Wait on a monitor until timeout, interrupt, or notification. Used for
370 * Object.wait() and (somewhat indirectly) Thread.sleep() and Thread.join().
371 *
372 * If another thread calls Thread.interrupt(), we throw InterruptedException
373 * and return immediately if one of the following are true:
374 * - blocked in wait(), wait(long), or wait(long, int) methods of Object
375 * - blocked in join(), join(long), or join(long, int) methods of Thread
376 * - blocked in sleep(long), or sleep(long, int) methods of Thread
377 * Otherwise, we set the "interrupted" flag.
378 *
379 * Checks to make sure that "ns" is in the range 0-999999
380 * (i.e. fractions of a millisecond) and throws the appropriate
381 * exception if it isn't.
382 *
383 * The spec allows "spurious wakeups", and recommends that all code using
384 * Object.wait() do so in a loop. This appears to derive from concerns
385 * about pthread_cond_wait() on multiprocessor systems. Some commentary
386 * on the web casts doubt on whether these can/should occur.
387 *
388 * Since we're allowed to wake up "early", we clamp extremely long durations
389 * to return at the end of the 32-bit time epoch.
390 */
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800391void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
392 bool interruptShouldThrow, ThreadState why) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700393 DCHECK(self != NULL);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800394 DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
Elliott Hughes5f791332011-09-15 17:45:30 -0700395
396 // Make sure that we hold the lock.
397 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800398 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700399 return;
400 }
Ian Rogers50b35e22012-10-04 10:09:15 -0700401 monitor_lock_.AssertHeld(self);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800402
Elliott Hughesdf42c482013-01-09 12:49:02 -0800403 // We need to turn a zero-length timed wait into a regular wait because
404 // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
405 if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
406 why = kWaiting;
407 }
408
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800409 WaitWithLock(self, ms, ns, interruptShouldThrow, why);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700410}
Elliott Hughes5f791332011-09-15 17:45:30 -0700411
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800412void Monitor::WaitWithLock(Thread* self, int64_t ms, int32_t ns,
413 bool interruptShouldThrow, ThreadState why) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700414 // Enforce the timeout range.
415 if (ms < 0 || ns < 0 || ns > 999999) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800416 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
417 self->ThrowNewExceptionF(throw_location, "Ljava/lang/IllegalArgumentException;",
418 "timeout arguments out of range: ms=%lld ns=%d", ms, ns);
Elliott Hughes5f791332011-09-15 17:45:30 -0700419 return;
420 }
421
Elliott Hughes5f791332011-09-15 17:45:30 -0700422 /*
423 * Add ourselves to the set of threads waiting on this monitor, and
424 * release our hold. We need to let it go even if we're a few levels
425 * deep in a recursive lock, and we need to restore that later.
426 *
427 * We append to the wait set ahead of clearing the count and owner
428 * fields so the subroutine can check that the calling thread owns
429 * the monitor. Aside from that, the order of member updates is
430 * not order sensitive as we hold the pthread mutex.
431 */
432 AppendToWaitSet(self);
Ian Rogers0399dde2012-06-06 17:09:28 -0700433 int prev_lock_count = lock_count_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700434 lock_count_ = 0;
435 owner_ = NULL;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800436 const mirror::AbstractMethod* saved_method = locking_method_;
jeffhao33dc7712011-11-09 17:54:24 -0800437 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700438 uintptr_t saved_dex_pc = locking_dex_pc_;
439 locking_dex_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700440
441 /*
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800442 * Update thread state. If the GC wakes up, it'll ignore us, knowing
Elliott Hughes5f791332011-09-15 17:45:30 -0700443 * that we won't touch any references in this state, and we'll check
444 * our suspend mode before we transition out.
445 */
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800446 self->TransitionFromRunnableToSuspended(why);
Elliott Hughes5f791332011-09-15 17:45:30 -0700447
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800448 bool was_interrupted = false;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700449 {
450 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
Ian Rogers50b35e22012-10-04 10:09:15 -0700451 MutexLock mu(self, *self->wait_mutex_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700452
453 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
454 // non-NULL a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
455 // up.
456 DCHECK(self->wait_monitor_ == NULL);
457 self->wait_monitor_ = this;
458
459 // Release the monitor lock.
460 Unlock(self, true);
461
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800462 // Handle the case where the thread was interrupted before we called wait().
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700463 if (self->interrupted_) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800464 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700465 } else {
466 // Wait for a notification or a timeout to occur.
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800467 if (why == kWaiting) {
Ian Rogersc604d732012-10-14 16:09:54 -0700468 self->wait_cond_->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700469 } else {
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800470 DCHECK(why == kTimedWaiting || why == kSleeping) << why;
Ian Rogersc604d732012-10-14 16:09:54 -0700471 self->wait_cond_->TimedWait(self, ms, ns);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700472 }
473 if (self->interrupted_) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800474 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700475 }
476 self->interrupted_ = false;
477 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700478 }
479
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700480 // Set self->status back to kRunnable, and self-suspend if needed.
481 self->TransitionFromSuspendedToRunnable();
Elliott Hughes5f791332011-09-15 17:45:30 -0700482
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800483 {
484 // We reset the thread's wait_monitor_ field after transitioning back to runnable so
485 // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
486 // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
487 // are waiting on "null".)
488 MutexLock mu(self, *self->wait_mutex_);
489 DCHECK(self->wait_monitor_ != NULL);
490 self->wait_monitor_ = NULL;
491 }
492
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700493 // Re-acquire the monitor lock.
Elliott Hughes5f791332011-09-15 17:45:30 -0700494 Lock(self);
495
Ian Rogers81d425b2012-09-27 16:03:43 -0700496 self->wait_mutex_->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700497
Elliott Hughes5f791332011-09-15 17:45:30 -0700498 /*
499 * We remove our thread from wait set after restoring the count
500 * and owner fields so the subroutine can check that the calling
501 * thread owns the monitor. Aside from that, the order of member
502 * updates is not order sensitive as we hold the pthread mutex.
503 */
504 owner_ = self;
Ian Rogers0399dde2012-06-06 17:09:28 -0700505 lock_count_ = prev_lock_count;
506 locking_method_ = saved_method;
507 locking_dex_pc_ = saved_dex_pc;
Elliott Hughes5f791332011-09-15 17:45:30 -0700508 RemoveFromWaitSet(self);
509
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800510 if (was_interrupted) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700511 /*
512 * We were interrupted while waiting, or somebody interrupted an
513 * un-interruptible thread earlier and we're bailing out immediately.
514 *
515 * The doc sayeth: "The interrupted status of the current thread is
516 * cleared when this exception is thrown."
517 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700518 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700519 MutexLock mu(self, *self->wait_mutex_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700520 self->interrupted_ = false;
521 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700522 if (interruptShouldThrow) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800523 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
524 self->ThrowNewException(throw_location, "Ljava/lang/InterruptedException;", NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700525 }
526 }
527}
528
529void Monitor::Notify(Thread* self) {
530 DCHECK(self != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700531 // Make sure that we hold the lock.
532 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800533 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700534 return;
535 }
Ian Rogers50b35e22012-10-04 10:09:15 -0700536 monitor_lock_.AssertHeld(self);
537 NotifyWithLock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700538}
539
Ian Rogers50b35e22012-10-04 10:09:15 -0700540void Monitor::NotifyWithLock(Thread* self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700541 // Signal the first waiting thread in the wait set.
542 while (wait_set_ != NULL) {
543 Thread* thread = wait_set_;
544 wait_set_ = thread->wait_next_;
545 thread->wait_next_ = NULL;
546
547 // Check to see if the thread is still waiting.
Ian Rogers50b35e22012-10-04 10:09:15 -0700548 MutexLock mu(self, *thread->wait_mutex_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700549 if (thread->wait_monitor_ != NULL) {
Ian Rogersc604d732012-10-14 16:09:54 -0700550 thread->wait_cond_->Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700551 return;
552 }
553 }
554}
555
556void Monitor::NotifyAll(Thread* self) {
557 DCHECK(self != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700558 // Make sure that we hold the lock.
559 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800560 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700561 return;
562 }
Ian Rogers50b35e22012-10-04 10:09:15 -0700563 monitor_lock_.AssertHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700564 NotifyAllWithLock();
565}
566
567void Monitor::NotifyAllWithLock() {
Elliott Hughes5f791332011-09-15 17:45:30 -0700568 // Signal all threads in the wait set.
569 while (wait_set_ != NULL) {
570 Thread* thread = wait_set_;
571 wait_set_ = thread->wait_next_;
572 thread->wait_next_ = NULL;
573 thread->Notify();
574 }
575}
576
577/*
578 * Changes the shape of a monitor from thin to fat, preserving the
579 * internal lock state. The calling thread must own the lock.
580 */
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800581void Monitor::Inflate(Thread* self, mirror::Object* obj) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700582 DCHECK(self != NULL);
583 DCHECK(obj != NULL);
584 DCHECK_EQ(LW_SHAPE(*obj->GetRawLockWordAddress()), LW_SHAPE_THIN);
Elliott Hughesf8e01272011-10-17 11:29:05 -0700585 DCHECK_EQ(LW_LOCK_OWNER(*obj->GetRawLockWordAddress()), static_cast<int32_t>(self->GetThinLockId()));
Elliott Hughes5f791332011-09-15 17:45:30 -0700586
587 // Allocate and acquire a new monitor.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700588 Monitor* m = new Monitor(self, obj);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800589 VLOG(monitor) << "monitor: thread " << self->GetThinLockId()
590 << " created monitor " << m << " for object " << obj;
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700591 Runtime::Current()->GetMonitorList()->Add(m);
Elliott Hughes5f791332011-09-15 17:45:30 -0700592}
593
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800594void Monitor::MonitorEnter(Thread* self, mirror::Object* obj) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700595 volatile int32_t* thinp = obj->GetRawLockWordAddress();
Elliott Hughes398f64b2012-03-26 18:05:48 -0700596 uint32_t sleepDelayNs;
597 uint32_t minSleepDelayNs = 1000000; /* 1 millisecond */
598 uint32_t maxSleepDelayNs = 1000000000; /* 1 second */
Elliott Hughesf8e01272011-10-17 11:29:05 -0700599 uint32_t thin, newThin;
Elliott Hughes5f791332011-09-15 17:45:30 -0700600
Elliott Hughes4681c802011-09-25 18:04:37 -0700601 DCHECK(self != NULL);
602 DCHECK(obj != NULL);
Elliott Hughesf8e01272011-10-17 11:29:05 -0700603 uint32_t threadId = self->GetThinLockId();
Elliott Hughesa21039c2012-06-21 12:09:25 -0700604 retry:
Elliott Hughes5f791332011-09-15 17:45:30 -0700605 thin = *thinp;
606 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
607 /*
608 * The lock is a thin lock. The owner field is used to
609 * determine the acquire method, ordered by cost.
610 */
611 if (LW_LOCK_OWNER(thin) == threadId) {
612 /*
613 * The calling thread owns the lock. Increment the
614 * value of the recursion count field.
615 */
616 *thinp += 1 << LW_LOCK_COUNT_SHIFT;
617 if (LW_LOCK_COUNT(*thinp) == LW_LOCK_COUNT_MASK) {
618 /*
619 * The reacquisition limit has been reached. Inflate
620 * the lock so the next acquire will not overflow the
621 * recursion count field.
622 */
623 Inflate(self, obj);
624 }
625 } else if (LW_LOCK_OWNER(thin) == 0) {
Elliott Hughes81ff3182012-03-23 20:35:56 -0700626 // The lock is unowned. Install the thread id of the calling thread into the owner field.
627 // This is the common case: compiled code will have tried this before calling back into
628 // the runtime.
Elliott Hughes5f791332011-09-15 17:45:30 -0700629 newThin = thin | (threadId << LW_LOCK_OWNER_SHIFT);
630 if (android_atomic_acquire_cas(thin, newThin, thinp) != 0) {
631 // The acquire failed. Try again.
632 goto retry;
633 }
634 } else {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800635 VLOG(monitor) << StringPrintf("monitor: thread %d spin on lock %p (a %s) owned by %d",
Elliott Hughes81ff3182012-03-23 20:35:56 -0700636 threadId, thinp, PrettyTypeOf(obj).c_str(), LW_LOCK_OWNER(thin));
637 // The lock is owned by another thread. Notify the runtime that we are about to wait.
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700638 self->monitor_enter_object_ = obj;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700639 self->TransitionFromRunnableToSuspended(kBlocked);
Elliott Hughes5f791332011-09-15 17:45:30 -0700640 // Spin until the thin lock is released or inflated.
641 sleepDelayNs = 0;
642 for (;;) {
643 thin = *thinp;
644 // Check the shape of the lock word. Another thread
645 // may have inflated the lock while we were waiting.
646 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
647 if (LW_LOCK_OWNER(thin) == 0) {
648 // The lock has been released. Install the thread id of the
649 // calling thread into the owner field.
650 newThin = thin | (threadId << LW_LOCK_OWNER_SHIFT);
651 if (android_atomic_acquire_cas(thin, newThin, thinp) == 0) {
652 // The acquire succeed. Break out of the loop and proceed to inflate the lock.
653 break;
654 }
655 } else {
656 // The lock has not been released. Yield so the owning thread can run.
657 if (sleepDelayNs == 0) {
658 sched_yield();
659 sleepDelayNs = minSleepDelayNs;
660 } else {
Ian Rogers56edc432013-01-18 16:51:51 -0800661 NanoSleep(sleepDelayNs);
Elliott Hughes5f791332011-09-15 17:45:30 -0700662 // Prepare the next delay value. Wrap to avoid once a second polls for eternity.
663 if (sleepDelayNs < maxSleepDelayNs / 2) {
664 sleepDelayNs *= 2;
665 } else {
666 sleepDelayNs = minSleepDelayNs;
667 }
668 }
669 }
670 } else {
Elliott Hughes81ff3182012-03-23 20:35:56 -0700671 // The thin lock was inflated by another thread. Let the runtime know we are no longer
Elliott Hughes5f791332011-09-15 17:45:30 -0700672 // waiting and try again.
Elliott Hughes398f64b2012-03-26 18:05:48 -0700673 VLOG(monitor) << StringPrintf("monitor: thread %d found lock %p surprise-fattened by another thread", threadId, thinp);
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700674 self->monitor_enter_object_ = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700675 self->TransitionFromSuspendedToRunnable();
Elliott Hughes5f791332011-09-15 17:45:30 -0700676 goto retry;
677 }
678 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800679 VLOG(monitor) << StringPrintf("monitor: thread %d spin on lock %p done", threadId, thinp);
Elliott Hughes81ff3182012-03-23 20:35:56 -0700680 // We have acquired the thin lock. Let the runtime know that we are no longer waiting.
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700681 self->monitor_enter_object_ = NULL;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700682 self->TransitionFromSuspendedToRunnable();
Elliott Hughes5f791332011-09-15 17:45:30 -0700683 // Fatten the lock.
684 Inflate(self, obj);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800685 VLOG(monitor) << StringPrintf("monitor: thread %d fattened lock %p", threadId, thinp);
Elliott Hughes5f791332011-09-15 17:45:30 -0700686 }
687 } else {
688 // The lock is a fat lock.
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800689 VLOG(monitor) << StringPrintf("monitor: thread %d locking fat lock %p (%p) %p on a %s",
Elliott Hughes398f64b2012-03-26 18:05:48 -0700690 threadId, thinp, LW_MONITOR(*thinp),
691 reinterpret_cast<void*>(*thinp), PrettyTypeOf(obj).c_str());
Elliott Hughes5f791332011-09-15 17:45:30 -0700692 DCHECK(LW_MONITOR(*thinp) != NULL);
693 LW_MONITOR(*thinp)->Lock(self);
694 }
695}
696
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800697bool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700698 volatile int32_t* thinp = obj->GetRawLockWordAddress();
699
700 DCHECK(self != NULL);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700701 // DCHECK_EQ(self->GetState(), kRunnable);
Elliott Hughes5f791332011-09-15 17:45:30 -0700702 DCHECK(obj != NULL);
703
704 /*
705 * Cache the lock word as its value can change while we are
706 * examining its state.
707 */
708 uint32_t thin = *thinp;
709 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
710 /*
711 * The lock is thin. We must ensure that the lock is owned
712 * by the given thread before unlocking it.
713 */
Elliott Hughesf8e01272011-10-17 11:29:05 -0700714 if (LW_LOCK_OWNER(thin) == self->GetThinLockId()) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700715 /*
716 * We are the lock owner. It is safe to update the lock
717 * without CAS as lock ownership guards the lock itself.
718 */
719 if (LW_LOCK_COUNT(thin) == 0) {
720 /*
721 * The lock was not recursively acquired, the common
722 * case. Unlock by clearing all bits except for the
723 * hash state.
724 */
725 thin &= (LW_HASH_STATE_MASK << LW_HASH_STATE_SHIFT);
726 android_atomic_release_store(thin, thinp);
727 } else {
728 /*
729 * The object was recursively acquired. Decrement the
730 * lock recursion count field.
731 */
732 *thinp -= 1 << LW_LOCK_COUNT_SHIFT;
733 }
734 } else {
735 /*
736 * We do not own the lock. The JVM spec requires that we
737 * throw an exception in this case.
738 */
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800739 FailedUnlock(obj, self, NULL, NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700740 return false;
741 }
742 } else {
743 /*
744 * The lock is fat. We must check to see if Unlock has
745 * raised any exceptions before continuing.
746 */
747 DCHECK(LW_MONITOR(*thinp) != NULL);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700748 if (!LW_MONITOR(*thinp)->Unlock(self, false)) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700749 // An exception has been raised. Do not fall through.
750 return false;
751 }
752 }
753 return true;
754}
755
756/*
757 * Object.wait(). Also called for class init.
758 */
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800759void Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800760 bool interruptShouldThrow, ThreadState why) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700761 volatile int32_t* thinp = obj->GetRawLockWordAddress();
762
763 // If the lock is still thin, we need to fatten it.
764 uint32_t thin = *thinp;
765 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
766 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700767 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800768 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700769 return;
770 }
771
772 /* This thread holds the lock. We need to fatten the lock
773 * so 'self' can block on it. Don't update the object lock
774 * field yet, because 'self' needs to acquire the lock before
775 * any other thread gets a chance.
776 */
777 Inflate(self, obj);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800778 VLOG(monitor) << StringPrintf("monitor: thread %d fattened lock %p by wait()", self->GetThinLockId(), thinp);
Elliott Hughes5f791332011-09-15 17:45:30 -0700779 }
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800780 LW_MONITOR(*thinp)->Wait(self, ms, ns, interruptShouldThrow, why);
Elliott Hughes5f791332011-09-15 17:45:30 -0700781}
782
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800783void Monitor::Notify(Thread* self, mirror::Object *obj) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700784 uint32_t thin = *obj->GetRawLockWordAddress();
785
786 // If the lock is still thin, there aren't any waiters;
787 // waiting on an object forces lock fattening.
788 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
789 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700790 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800791 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700792 return;
793 }
794 // no-op; there are no waiters to notify.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700795 Inflate(self, obj);
Elliott Hughes5f791332011-09-15 17:45:30 -0700796 } else {
797 // It's a fat lock.
798 LW_MONITOR(thin)->Notify(self);
799 }
800}
801
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800802void Monitor::NotifyAll(Thread* self, mirror::Object *obj) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700803 uint32_t thin = *obj->GetRawLockWordAddress();
804
805 // If the lock is still thin, there aren't any waiters;
806 // waiting on an object forces lock fattening.
807 if (LW_SHAPE(thin) == LW_SHAPE_THIN) {
808 // Make sure that 'self' holds the lock.
Elliott Hughesf8e01272011-10-17 11:29:05 -0700809 if (LW_LOCK_OWNER(thin) != self->GetThinLockId()) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800810 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700811 return;
812 }
813 // no-op; there are no waiters to notify.
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700814 Inflate(self, obj);
Elliott Hughes5f791332011-09-15 17:45:30 -0700815 } else {
816 // It's a fat lock.
817 LW_MONITOR(thin)->NotifyAll(self);
818 }
819}
820
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -0700821uint32_t Monitor::GetThinLockId(uint32_t raw_lock_word) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700822 if (LW_SHAPE(raw_lock_word) == LW_SHAPE_THIN) {
823 return LW_LOCK_OWNER(raw_lock_word);
824 } else {
825 Thread* owner = LW_MONITOR(raw_lock_word)->owner_;
826 return owner ? owner->GetThinLockId() : 0;
827 }
828}
829
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700830void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800831 ThreadState state = thread->GetState();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700832
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800833 mirror::Object* object = NULL;
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700834 uint32_t lock_owner = ThreadList::kInvalidId;
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800835 if (state == kWaiting || state == kTimedWaiting || state == kSleeping) {
836 if (state == kSleeping) {
837 os << " - sleeping on ";
838 } else {
839 os << " - waiting on ";
840 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700841 {
Elliott Hughesf9501702013-01-11 11:22:27 -0800842 Thread* self = Thread::Current();
843 MutexLock mu(self, *thread->wait_mutex_);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800844 Monitor* monitor = thread->wait_monitor_;
845 if (monitor != NULL) {
846 object = monitor->obj_;
847 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700848 }
Elliott Hughes34e06962012-04-09 13:55:55 -0700849 } else if (state == kBlocked) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700850 os << " - waiting to lock ";
851 object = thread->monitor_enter_object_;
852 if (object != NULL) {
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -0700853 lock_owner = object->GetThinLockId();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700854 }
855 } else {
856 // We're not waiting on anything.
857 return;
858 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700859
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700860 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700861 os << "<" << object << "> (a " << PrettyTypeOf(object) << ")";
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700862
Elliott Hughesc5dc2ff2013-01-09 13:44:30 -0800863 // - waiting to lock <0x613f83d8> (a java.lang.Object) held by thread 5
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700864 if (lock_owner != ThreadList::kInvalidId) {
865 os << " held by thread " << lock_owner;
866 }
867
868 os << "\n";
869}
870
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800871mirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800872 // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
873 // definition of contended that includes a monitor a thread is trying to enter...
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800874 mirror::Object* result = thread->monitor_enter_object_;
Elliott Hughesf9501702013-01-11 11:22:27 -0800875 if (result != NULL) {
876 return result;
877 }
878 // ...but also a monitor that the thread is waiting on.
879 {
880 MutexLock mu(Thread::Current(), *thread->wait_mutex_);
881 Monitor* monitor = thread->wait_monitor_;
882 if (monitor != NULL) {
883 return monitor->obj_;
884 }
885 }
886 return NULL;
887}
888
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800889void Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
890 void* callback_context) {
891 mirror::AbstractMethod* m = stack_visitor->GetMethod();
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700892 CHECK(m != NULL);
893
894 // Native methods are an easy special case.
895 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
896 if (m->IsNative()) {
897 if (m->IsSynchronized()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800898 mirror::Object* jni_this = stack_visitor->GetCurrentSirt()->GetReference(0);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800899 callback(jni_this, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700900 }
901 return;
902 }
903
jeffhao61f916c2012-10-25 17:48:51 -0700904 // Proxy methods should not be synchronized.
905 if (m->IsProxyMethod()) {
906 CHECK(!m->IsSynchronized());
907 return;
908 }
909
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700910 // <clinit> is another special case. The runtime holds the class lock while calling <clinit>.
911 MethodHelper mh(m);
912 if (mh.IsClassInitializer()) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800913 callback(m->GetDeclaringClass(), callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700914 // Fall through because there might be synchronization in the user code too.
915 }
916
917 // Is there any reason to believe there's any synchronization in this method?
918 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -0700919 CHECK(code_item != NULL) << PrettyMethod(m);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700920 if (code_item->tries_size_ == 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700921 return; // No "tries" implies no synchronization, so no held locks to report.
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700922 }
923
Elliott Hughes80537bb2013-01-04 16:37:26 -0800924 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
925 // the locks held in this stack frame.
926 std::vector<uint32_t> monitor_enter_dex_pcs;
927 verifier::MethodVerifier::FindLocksAtDexPc(m, stack_visitor->GetDexPc(), monitor_enter_dex_pcs);
928 if (monitor_enter_dex_pcs.empty()) {
929 return;
930 }
931
Elliott Hughes80537bb2013-01-04 16:37:26 -0800932 for (size_t i = 0; i < monitor_enter_dex_pcs.size(); ++i) {
933 // The verifier works in terms of the dex pcs of the monitor-enter instructions.
934 // We want the registers used by those instructions (so we can read the values out of them).
935 uint32_t dex_pc = monitor_enter_dex_pcs[i];
936 uint16_t monitor_enter_instruction = code_item->insns_[dex_pc];
937
938 // Quick sanity check.
939 if ((monitor_enter_instruction & 0xff) != Instruction::MONITOR_ENTER) {
940 LOG(FATAL) << "expected monitor-enter @" << dex_pc << "; was "
941 << reinterpret_cast<void*>(monitor_enter_instruction);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700942 }
943
Elliott Hughes80537bb2013-01-04 16:37:26 -0800944 uint16_t monitor_register = ((monitor_enter_instruction >> 8) & 0xff);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800945 mirror::Object* o = reinterpret_cast<mirror::Object*>(stack_visitor->GetVReg(m, monitor_register,
946 kReferenceVReg));
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800947 callback(o, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700948 }
949}
950
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800951void Monitor::TranslateLocation(const mirror::AbstractMethod* method, uint32_t dex_pc,
jeffhao33dc7712011-11-09 17:54:24 -0800952 const char*& source_file, uint32_t& line_number) const {
953 // If method is null, location is unknown
954 if (method == NULL) {
Elliott Hughes12c51e32012-01-17 20:25:05 -0800955 source_file = "";
jeffhao33dc7712011-11-09 17:54:24 -0800956 line_number = 0;
957 return;
958 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800959 MethodHelper mh(method);
960 source_file = mh.GetDeclaringClassSourceFile();
Elliott Hughes12c51e32012-01-17 20:25:05 -0800961 if (source_file == NULL) {
962 source_file = "";
963 }
Ian Rogers0399dde2012-06-06 17:09:28 -0700964 line_number = mh.GetLineNumFromDexPC(dex_pc);
jeffhao33dc7712011-11-09 17:54:24 -0800965}
966
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700967MonitorList::MonitorList() : monitor_list_lock_("MonitorList lock") {
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700968}
969
970MonitorList::~MonitorList() {
Ian Rogers50b35e22012-10-04 10:09:15 -0700971 MutexLock mu(Thread::Current(), monitor_list_lock_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700972 STLDeleteElements(&list_);
973}
974
975void MonitorList::Add(Monitor* m) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700976 MutexLock mu(Thread::Current(), monitor_list_lock_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700977 list_.push_front(m);
978}
979
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800980void MonitorList::SweepMonitorList(IsMarkedTester is_marked, void* arg) {
Ian Rogers50b35e22012-10-04 10:09:15 -0700981 MutexLock mu(Thread::Current(), monitor_list_lock_);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700982 typedef std::list<Monitor*>::iterator It; // TODO: C++0x auto
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700983 It it = list_.begin();
984 while (it != list_.end()) {
985 Monitor* m = *it;
986 if (!is_marked(m->GetObject(), arg)) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800987 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object " << m->GetObject();
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700988 delete m;
989 it = list_.erase(it);
990 } else {
991 ++it;
992 }
993 }
994}
995
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800996MonitorInfo::MonitorInfo(mirror::Object* o) : owner(NULL), entry_count(0) {
Elliott Hughesf327e072013-01-09 16:01:26 -0800997 uint32_t lock_word = *o->GetRawLockWordAddress();
998 if (LW_SHAPE(lock_word) == LW_SHAPE_THIN) {
999 uint32_t owner_thin_lock_id = LW_LOCK_OWNER(lock_word);
1000 if (owner_thin_lock_id != 0) {
1001 owner = Runtime::Current()->GetThreadList()->FindThreadByThinLockId(owner_thin_lock_id);
1002 entry_count = 1 + LW_LOCK_COUNT(lock_word);
1003 }
1004 // Thin locks have no waiters.
1005 } else {
1006 CHECK_EQ(LW_SHAPE(lock_word), LW_SHAPE_FAT);
1007 Monitor* monitor = LW_MONITOR(lock_word);
1008 owner = monitor->owner_;
1009 entry_count = 1 + monitor->lock_count_;
1010 for (Thread* waiter = monitor->wait_set_; waiter != NULL; waiter = waiter->wait_next_) {
1011 waiters.push_back(waiter);
1012 }
1013 }
1014}
1015
Elliott Hughes5f791332011-09-15 17:45:30 -07001016} // namespace art