blob: 85f3a091cba8d346b4c7225c23354b6f65508ee5 [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 Rogersd9c4fc92013-10-01 19:45:43 -070026#include "lock_word-inl.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070027#include "mirror/art_method-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070028#include "mirror/class-inl.h"
Ian Rogers05f30572013-02-20 12:13:11 -080029#include "mirror/object-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080030#include "mirror/object_array-inl.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080031#include "object_utils.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070032#include "scoped_thread_state_change.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070033#include "thread.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070034#include "thread_list.h"
Elliott Hughes08fc03a2012-06-26 17:34:00 -070035#include "verifier/method_verifier.h"
Elliott Hughes044288f2012-06-25 14:46:39 -070036#include "well_known_classes.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070037
38namespace art {
39
40/*
Ian Rogersd9c4fc92013-10-01 19:45:43 -070041 * Every Object has a monitor associated with it, but not every Object is actually locked. Even
42 * the ones that are locked do not need a full-fledged monitor until a) there is actual contention
43 * or b) wait() is called on the Object.
Elliott Hughes5f791332011-09-15 17:45:30 -070044 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070045 * For Android, we have implemented a scheme similar to the one described in Bacon et al.'s
46 * "Thin locks: featherweight synchronization for Java" (ACM 1998). Things are even easier for us,
47 * though, because we have a full 32 bits to work with.
Elliott Hughes5f791332011-09-15 17:45:30 -070048 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070049 * The two states of an Object's lock are referred to as "thin" and "fat". A lock may transition
50 * from the "thin" state to the "fat" state and this transition is referred to as inflation. Once
51 * a lock has been inflated it remains in the "fat" state indefinitely.
Elliott Hughes5f791332011-09-15 17:45:30 -070052 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070053 * The lock value itself is stored in mirror::Object::monitor_ and the representation is described
54 * in the LockWord value type.
Elliott Hughes54e7df12011-09-16 11:47:04 -070055 *
Elliott Hughes5f791332011-09-15 17:45:30 -070056 * Monitors provide:
57 * - mutually exclusive access to resources
58 * - a way for multiple threads to wait for notification
59 *
60 * In effect, they fill the role of both mutexes and condition variables.
61 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070062 * Only one thread can own the monitor at any time. There may be several threads waiting on it
63 * (the wait call unlocks it). One or more waiting threads may be getting interrupted or notified
64 * at any given time.
Elliott Hughes5f791332011-09-15 17:45:30 -070065 */
Elliott Hughes54e7df12011-09-16 11:47:04 -070066
Elliott Hughesfc861622011-10-17 17:57:47 -070067bool (*Monitor::is_sensitive_thread_hook_)() = NULL;
Elliott Hughesfc861622011-10-17 17:57:47 -070068uint32_t Monitor::lock_profiling_threshold_ = 0;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070069
Elliott Hughesfc861622011-10-17 17:57:47 -070070bool Monitor::IsSensitiveThread() {
71 if (is_sensitive_thread_hook_ != NULL) {
72 return (*is_sensitive_thread_hook_)();
73 }
74 return false;
75}
76
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -080077void Monitor::Init(uint32_t lock_profiling_threshold, bool (*is_sensitive_thread_hook)()) {
Elliott Hughesfc861622011-10-17 17:57:47 -070078 lock_profiling_threshold_ = lock_profiling_threshold;
79 is_sensitive_thread_hook_ = is_sensitive_thread_hook;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070080}
81
Ian Rogersef7d42f2014-01-06 12:55:46 -080082Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code)
Ian Rogers00f7d0e2012-07-19 15:28:27 -070083 : monitor_lock_("a monitor lock", kMonitorLock),
Ian Rogersd9c4fc92013-10-01 19:45:43 -070084 monitor_contenders_("monitor contenders", monitor_lock_),
Mathieu Chartier46bc7782013-11-12 17:03:02 -080085 num_waiters_(0),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070086 owner_(owner),
Elliott Hughes5f791332011-09-15 17:45:30 -070087 lock_count_(0),
88 obj_(obj),
89 wait_set_(NULL),
Mathieu Chartierad2541a2013-10-25 10:05:23 -070090 hash_code_(hash_code),
jeffhao33dc7712011-11-09 17:54:24 -080091 locking_method_(NULL),
Ian Rogersef7d42f2014-01-06 12:55:46 -080092 locking_dex_pc_(0),
93 monitor_id_(MonitorPool::CreateMonitorId(self, this)) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -070094 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
95 // with the owner unlocking the thin-lock.
Ian Rogersef7d42f2014-01-06 12:55:46 -080096 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
Mathieu Chartierad2541a2013-10-25 10:05:23 -070097 // The identity hash code is set for the life time of the monitor.
Ian Rogersd9c4fc92013-10-01 19:45:43 -070098}
99
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700100int32_t Monitor::GetHashCode() {
101 while (!HasHashCode()) {
Ian Rogersb122a4b2013-11-19 18:00:50 -0800102 if (hash_code_.CompareAndSwap(0, mirror::Object::GenerateIdentityHashCode())) {
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700103 break;
104 }
105 }
106 DCHECK(HasHashCode());
Ian Rogersb122a4b2013-11-19 18:00:50 -0800107 return hash_code_.Load();
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700108}
109
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700110bool Monitor::Install(Thread* self) {
111 MutexLock mu(self, monitor_lock_); // Uncontended mutex acquisition as monitor isn't yet public.
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700112 CHECK(owner_ == nullptr || owner_ == self || owner_->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700113 // Propagate the lock state.
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700114 LockWord lw(obj_->GetLockWord());
115 switch (lw.GetState()) {
116 case LockWord::kThinLocked: {
117 CHECK_EQ(owner_->GetThreadId(), lw.ThinLockOwner());
118 lock_count_ = lw.ThinLockCount();
119 break;
120 }
121 case LockWord::kHashCode: {
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700122 CHECK_EQ(hash_code_, static_cast<int32_t>(lw.GetHashCode()));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700123 break;
124 }
125 case LockWord::kFatLocked: {
126 // The owner_ is suspended but another thread beat us to install a monitor.
127 return false;
128 }
129 case LockWord::kUnlocked: {
130 LOG(FATAL) << "Inflating unlocked lock word";
131 break;
132 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700133 default: {
134 LOG(FATAL) << "Invalid monitor state " << lw.GetState();
135 return false;
136 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700137 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700138 LockWord fat(this);
139 // Publish the updated lock word, which may race with other threads.
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700140 bool success = obj_->CasLockWord(lw, fat);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700141 // Lock profiling.
Mathieu Chartier9728f912013-10-30 09:45:13 -0700142 if (success && owner_ != nullptr && lock_profiling_threshold_ != 0) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700143 locking_method_ = owner_->GetCurrentMethod(&locking_dex_pc_);
144 }
145 return success;
Elliott Hughes5f791332011-09-15 17:45:30 -0700146}
147
148Monitor::~Monitor() {
Ian Rogersef7d42f2014-01-06 12:55:46 -0800149 MonitorPool::ReleaseMonitorId(monitor_id_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700150 // Deflated monitors have a null object.
Elliott Hughes5f791332011-09-15 17:45:30 -0700151}
152
153/*
154 * Links a thread into a monitor's wait set. The monitor lock must be
155 * held by the caller of this routine.
156 */
157void Monitor::AppendToWaitSet(Thread* thread) {
158 DCHECK(owner_ == Thread::Current());
159 DCHECK(thread != NULL);
Elliott Hughesdc33ad52011-09-16 19:46:51 -0700160 DCHECK(thread->wait_next_ == NULL) << thread->wait_next_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700161 if (wait_set_ == NULL) {
162 wait_set_ = thread;
163 return;
164 }
165
166 // push_back.
167 Thread* t = wait_set_;
168 while (t->wait_next_ != NULL) {
169 t = t->wait_next_;
170 }
171 t->wait_next_ = thread;
172}
173
174/*
175 * Unlinks a thread from a monitor's wait set. The monitor lock must
176 * be held by the caller of this routine.
177 */
178void Monitor::RemoveFromWaitSet(Thread *thread) {
179 DCHECK(owner_ == Thread::Current());
180 DCHECK(thread != NULL);
181 if (wait_set_ == NULL) {
182 return;
183 }
184 if (wait_set_ == thread) {
185 wait_set_ = thread->wait_next_;
186 thread->wait_next_ = NULL;
187 return;
188 }
189
190 Thread* t = wait_set_;
191 while (t->wait_next_ != NULL) {
192 if (t->wait_next_ == thread) {
193 t->wait_next_ = thread->wait_next_;
194 thread->wait_next_ = NULL;
195 return;
196 }
197 t = t->wait_next_;
198 }
199}
200
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700201void Monitor::SetObject(mirror::Object* object) {
202 obj_ = object;
203}
204
Elliott Hughes5f791332011-09-15 17:45:30 -0700205void Monitor::Lock(Thread* self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700206 MutexLock mu(self, monitor_lock_);
207 while (true) {
208 if (owner_ == NULL) { // Unowned.
209 owner_ = self;
210 CHECK_EQ(lock_count_, 0);
211 // When debugging, save the current monitor holder for future
212 // acquisition failures to use in sampled logging.
213 if (lock_profiling_threshold_ != 0) {
214 locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
215 }
216 return;
217 } else if (owner_ == self) { // Recursive.
218 lock_count_++;
219 return;
220 }
221 // Contended.
222 const bool log_contention = (lock_profiling_threshold_ != 0);
223 uint64_t wait_start_ms = log_contention ? 0 : MilliTime();
Ian Rogersef7d42f2014-01-06 12:55:46 -0800224 mirror::ArtMethod* owners_method = locking_method_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700225 uint32_t owners_dex_pc = locking_dex_pc_;
226 monitor_lock_.Unlock(self); // Let go of locks in order.
Elliott Hughes5f791332011-09-15 17:45:30 -0700227 {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700228 ScopedThreadStateChange tsc(self, kBlocked); // Change to blocked and give up mutator_lock_.
229 MutexLock mu2(self, monitor_lock_); // Reacquire monitor_lock_ without mutator_lock_ for Wait.
230 if (owner_ != NULL) { // Did the owner_ give the lock up?
Mathieu Chartier46bc7782013-11-12 17:03:02 -0800231 ++num_waiters_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700232 monitor_contenders_.Wait(self); // Still contended so wait.
Mathieu Chartier46bc7782013-11-12 17:03:02 -0800233 --num_waiters_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700234 // Woken from contention.
235 if (log_contention) {
236 uint64_t wait_ms = MilliTime() - wait_start_ms;
237 uint32_t sample_percent;
238 if (wait_ms >= lock_profiling_threshold_) {
239 sample_percent = 100;
240 } else {
241 sample_percent = 100 * wait_ms / lock_profiling_threshold_;
242 }
243 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
244 const char* owners_filename;
245 uint32_t owners_line_number;
246 TranslateLocation(owners_method, owners_dex_pc, &owners_filename, &owners_line_number);
247 LogContentionEvent(self, wait_ms, sample_percent, owners_filename, owners_line_number);
248 }
249 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700250 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700251 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700252 monitor_lock_.Lock(self); // Reacquire locks in order.
Elliott Hughesfc861622011-10-17 17:57:47 -0700253 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700254}
255
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800256static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
257 __attribute__((format(printf, 1, 2)));
258
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700259static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700260 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800261 va_list args;
262 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800263 Thread* self = Thread::Current();
264 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
265 self->ThrowNewExceptionV(throw_location, "Ljava/lang/IllegalMonitorStateException;", fmt, args);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700266 if (!Runtime::Current()->IsStarted() || VLOG_IS_ON(monitor)) {
Brian Carlstrom64277f32012-03-26 23:53:34 -0700267 std::ostringstream ss;
Ian Rogers62d6c772013-02-27 08:32:07 -0800268 self->Dump(ss);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700269 LOG(Runtime::Current()->IsStarted() ? INFO : ERROR)
270 << self->GetException(NULL)->Dump() << "\n" << ss.str();
Brian Carlstrom64277f32012-03-26 23:53:34 -0700271 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800272 va_end(args);
273}
274
Elliott Hughesd4237412012-02-21 11:24:45 -0800275static std::string ThreadToString(Thread* thread) {
276 if (thread == NULL) {
277 return "NULL";
278 }
279 std::ostringstream oss;
280 // TODO: alternatively, we could just return the thread's name.
281 oss << *thread;
282 return oss.str();
283}
284
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800285void Monitor::FailedUnlock(mirror::Object* o, Thread* expected_owner, Thread* found_owner,
Elliott Hughesffb465f2012-03-01 18:46:05 -0800286 Monitor* monitor) {
287 Thread* current_owner = NULL;
288 std::string current_owner_string;
289 std::string expected_owner_string;
290 std::string found_owner_string;
291 {
292 // TODO: isn't this too late to prevent threads from disappearing?
293 // Acquire thread list lock so threads won't disappear from under us.
Ian Rogers50b35e22012-10-04 10:09:15 -0700294 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Elliott Hughesffb465f2012-03-01 18:46:05 -0800295 // Re-read owner now that we hold lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700296 current_owner = (monitor != NULL) ? monitor->GetOwner() : NULL;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800297 // Get short descriptions of the threads involved.
298 current_owner_string = ThreadToString(current_owner);
299 expected_owner_string = ThreadToString(expected_owner);
300 found_owner_string = ThreadToString(found_owner);
301 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800302 if (current_owner == NULL) {
303 if (found_owner == NULL) {
304 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
305 " on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800306 PrettyTypeOf(o).c_str(),
307 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800308 } else {
309 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800310 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
311 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800312 found_owner_string.c_str(),
313 PrettyTypeOf(o).c_str(),
314 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800315 }
316 } else {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800317 if (found_owner == NULL) {
318 // Race: originally there was no owner, there is now
319 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
320 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800321 current_owner_string.c_str(),
322 PrettyTypeOf(o).c_str(),
323 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800324 } else {
325 if (found_owner != current_owner) {
326 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800327 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
328 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800329 found_owner_string.c_str(),
330 current_owner_string.c_str(),
331 PrettyTypeOf(o).c_str(),
332 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800333 } else {
334 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
335 " on thread '%s",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800336 current_owner_string.c_str(),
337 PrettyTypeOf(o).c_str(),
338 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800339 }
340 }
341 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700342}
343
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700344bool Monitor::Unlock(Thread* self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700345 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700346 MutexLock mu(self, monitor_lock_);
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800347 Thread* owner = owner_;
348 if (owner == self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700349 // We own the monitor, so nobody else can be in here.
350 if (lock_count_ == 0) {
351 owner_ = NULL;
jeffhao33dc7712011-11-09 17:54:24 -0800352 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700353 locking_dex_pc_ = 0;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700354 // Wake a contender.
355 monitor_contenders_.Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700356 } else {
357 --lock_count_;
358 }
359 } else {
360 // We don't own this, so we're not allowed to unlock it.
361 // The JNI spec says that we should throw IllegalMonitorStateException
362 // in this case.
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800363 FailedUnlock(obj_, self, owner, this);
Elliott Hughes5f791332011-09-15 17:45:30 -0700364 return false;
365 }
366 return true;
367}
368
Elliott Hughes5f791332011-09-15 17:45:30 -0700369/*
370 * Wait on a monitor until timeout, interrupt, or notification. Used for
371 * Object.wait() and (somewhat indirectly) Thread.sleep() and Thread.join().
372 *
373 * If another thread calls Thread.interrupt(), we throw InterruptedException
374 * and return immediately if one of the following are true:
375 * - blocked in wait(), wait(long), or wait(long, int) methods of Object
376 * - blocked in join(), join(long), or join(long, int) methods of Thread
377 * - blocked in sleep(long), or sleep(long, int) methods of Thread
378 * Otherwise, we set the "interrupted" flag.
379 *
380 * Checks to make sure that "ns" is in the range 0-999999
381 * (i.e. fractions of a millisecond) and throws the appropriate
382 * exception if it isn't.
383 *
384 * The spec allows "spurious wakeups", and recommends that all code using
385 * Object.wait() do so in a loop. This appears to derive from concerns
386 * about pthread_cond_wait() on multiprocessor systems. Some commentary
387 * on the web casts doubt on whether these can/should occur.
388 *
389 * Since we're allowed to wake up "early", we clamp extremely long durations
390 * to return at the end of the 32-bit time epoch.
391 */
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800392void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
393 bool interruptShouldThrow, ThreadState why) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700394 DCHECK(self != NULL);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800395 DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
Elliott Hughes5f791332011-09-15 17:45:30 -0700396
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700397 monitor_lock_.Lock(self);
398
Elliott Hughes5f791332011-09-15 17:45:30 -0700399 // 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()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700402 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700403 return;
404 }
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 Hughes5f791332011-09-15 17:45:30 -0700412 // Enforce the timeout range.
413 if (ms < 0 || ns < 0 || ns > 999999) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800414 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
415 self->ThrowNewExceptionF(throw_location, "Ljava/lang/IllegalArgumentException;",
Ian Rogersef7d42f2014-01-06 12:55:46 -0800416 "timeout arguments out of range: ms=%" PRId64 " ns=%d", ms, ns);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700417 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700418 return;
419 }
420
Elliott Hughes5f791332011-09-15 17:45:30 -0700421 /*
422 * Add ourselves to the set of threads waiting on this monitor, and
423 * release our hold. We need to let it go even if we're a few levels
424 * deep in a recursive lock, and we need to restore that later.
425 *
426 * We append to the wait set ahead of clearing the count and owner
427 * fields so the subroutine can check that the calling thread owns
428 * the monitor. Aside from that, the order of member updates is
429 * not order sensitive as we hold the pthread mutex.
430 */
431 AppendToWaitSet(self);
Ian Rogers0399dde2012-06-06 17:09:28 -0700432 int prev_lock_count = lock_count_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700433 lock_count_ = 0;
434 owner_ = NULL;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800435 mirror::ArtMethod* saved_method = locking_method_;
jeffhao33dc7712011-11-09 17:54:24 -0800436 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700437 uintptr_t saved_dex_pc = locking_dex_pc_;
438 locking_dex_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700439
440 /*
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800441 * Update thread state. If the GC wakes up, it'll ignore us, knowing
Elliott Hughes5f791332011-09-15 17:45:30 -0700442 * that we won't touch any references in this state, and we'll check
443 * our suspend mode before we transition out.
444 */
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800445 self->TransitionFromRunnableToSuspended(why);
Elliott Hughes5f791332011-09-15 17:45:30 -0700446
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800447 bool was_interrupted = false;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700448 {
449 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
Ian Rogers50b35e22012-10-04 10:09:15 -0700450 MutexLock mu(self, *self->wait_mutex_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700451
452 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
453 // non-NULL a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
454 // up.
455 DCHECK(self->wait_monitor_ == NULL);
456 self->wait_monitor_ = this;
457
458 // Release the monitor lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700459 monitor_contenders_.Signal(self);
460 monitor_lock_.Unlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700461
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 Rogersd9c4fc92013-10-01 19:45:43 -0700493 // Re-acquire the monitor and lock.
Elliott Hughes5f791332011-09-15 17:45:30 -0700494 Lock(self);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700495 monitor_lock_.Lock(self);
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 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700527 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700528}
529
530void Monitor::Notify(Thread* self) {
531 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700532 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700533 // Make sure that we hold the lock.
534 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800535 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700536 return;
537 }
538 // Signal the first waiting thread in the wait set.
539 while (wait_set_ != NULL) {
540 Thread* thread = wait_set_;
541 wait_set_ = thread->wait_next_;
542 thread->wait_next_ = NULL;
543
544 // Check to see if the thread is still waiting.
Ian Rogers50b35e22012-10-04 10:09:15 -0700545 MutexLock mu(self, *thread->wait_mutex_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700546 if (thread->wait_monitor_ != NULL) {
Ian Rogersc604d732012-10-14 16:09:54 -0700547 thread->wait_cond_->Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700548 return;
549 }
550 }
551}
552
553void Monitor::NotifyAll(Thread* self) {
554 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700555 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700556 // Make sure that we hold the lock.
557 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800558 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700559 return;
560 }
561 // Signal all threads in the wait set.
562 while (wait_set_ != NULL) {
563 Thread* thread = wait_set_;
564 wait_set_ = thread->wait_next_;
565 thread->wait_next_ = NULL;
566 thread->Notify();
567 }
568}
569
Mathieu Chartier590fee92013-09-13 13:46:47 -0700570bool Monitor::Deflate(Thread* self, mirror::Object* obj) {
571 DCHECK(obj != nullptr);
572 LockWord lw(obj->GetLockWord());
573 // If the lock isn't an inflated monitor, then we don't need to deflate anything.
574 if (lw.GetState() == LockWord::kFatLocked) {
575 Monitor* monitor = lw.FatLockMonitor();
576 CHECK(monitor != nullptr);
577 MutexLock mu(self, monitor->monitor_lock_);
578 Thread* owner = monitor->owner_;
579 if (owner != nullptr) {
580 // Can't deflate if we are locked and have a hash code.
581 if (monitor->HasHashCode()) {
582 return false;
583 }
584 // Can't deflate if our lock count is too high.
585 if (monitor->lock_count_ > LockWord::kThinLockMaxCount) {
586 return false;
587 }
588 // Can't deflate if we have anybody waiting on the CV.
Mathieu Chartier46bc7782013-11-12 17:03:02 -0800589 if (monitor->num_waiters_ > 0) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700590 return false;
591 }
592 // Deflate to a thin lock.
593 obj->SetLockWord(LockWord::FromThinLockId(owner->GetTid(), monitor->lock_count_));
594 } else if (monitor->HasHashCode()) {
595 obj->SetLockWord(LockWord::FromHashCode(monitor->GetHashCode()));
596 } else {
597 // No lock and no hash, just put an empty lock word inside the object.
598 obj->SetLockWord(LockWord());
599 }
600 // The monitor is deflated, mark the object as nullptr so that we know to delete it during the
601 // next GC.
602 monitor->obj_ = nullptr;
603 }
604 return true;
605}
606
Elliott Hughes5f791332011-09-15 17:45:30 -0700607/*
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700608 * Changes the shape of a monitor from thin to fat, preserving the internal lock state. The calling
609 * thread must own the lock or the owner must be suspended. There's a race with other threads
610 * inflating the lock and so the caller should read the monitor following the call.
Elliott Hughes5f791332011-09-15 17:45:30 -0700611 */
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700612void Monitor::Inflate(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700613 DCHECK(self != NULL);
614 DCHECK(obj != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700615 // Allocate and acquire a new monitor.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800616 UniquePtr<Monitor> m(new Monitor(self, owner, obj, hash_code));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700617 if (m->Install(self)) {
618 VLOG(monitor) << "monitor: thread " << owner->GetThreadId()
619 << " created monitor " << m.get() << " for object " << obj;
620 Runtime::Current()->GetMonitorList()->Add(m.release());
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700621 CHECK_EQ(obj->GetLockWord().GetState(), LockWord::kFatLocked);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700622 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700623}
624
Mathieu Chartier590fee92013-09-13 13:46:47 -0700625void Monitor::InflateThinLocked(Thread* self, SirtRef<mirror::Object>& obj, LockWord lock_word,
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700626 uint32_t hash_code) {
627 DCHECK_EQ(lock_word.GetState(), LockWord::kThinLocked);
628 uint32_t owner_thread_id = lock_word.ThinLockOwner();
629 if (owner_thread_id == self->GetThreadId()) {
630 // We own the monitor, we can easily inflate it.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700631 Inflate(self, self, obj.get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700632 } else {
633 ThreadList* thread_list = Runtime::Current()->GetThreadList();
634 // Suspend the owner, inflate. First change to blocked and give up mutator_lock_.
635 ScopedThreadStateChange tsc(self, kBlocked);
636 if (lock_word == obj->GetLockWord()) { // If lock word hasn't changed.
637 bool timed_out;
Mathieu Chartier5f51d4b2013-12-03 14:24:05 -0800638 Thread* owner = thread_list->SuspendThreadByThreadId(owner_thread_id, false, &timed_out);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700639 if (owner != nullptr) {
640 // We succeeded in suspending the thread, check the lock's status didn't change.
641 lock_word = obj->GetLockWord();
642 if (lock_word.GetState() == LockWord::kThinLocked &&
643 lock_word.ThinLockOwner() == owner_thread_id) {
644 // Go ahead and inflate the lock.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700645 Inflate(self, owner, obj.get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700646 }
647 thread_list->Resume(owner, false);
648 }
649 }
650 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700651}
652
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800653void Monitor::MonitorEnter(Thread* self, mirror::Object* obj) {
Elliott Hughes4681c802011-09-25 18:04:37 -0700654 DCHECK(self != NULL);
655 DCHECK(obj != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700656 uint32_t thread_id = self->GetThreadId();
657 size_t contention_count = 0;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700658 SirtRef<mirror::Object> sirt_obj(self, obj);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700659 while (true) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700660 LockWord lock_word = sirt_obj->GetLockWord();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700661 switch (lock_word.GetState()) {
662 case LockWord::kUnlocked: {
663 LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700664 if (sirt_obj->CasLockWord(lock_word, thin_locked)) {
Ian Rogersb122a4b2013-11-19 18:00:50 -0800665 QuasiAtomic::MembarLoadLoad();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700666 return; // Success!
667 }
668 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -0700669 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700670 case LockWord::kThinLocked: {
671 uint32_t owner_thread_id = lock_word.ThinLockOwner();
672 if (owner_thread_id == thread_id) {
673 // We own the lock, increase the recursion count.
674 uint32_t new_count = lock_word.ThinLockCount() + 1;
675 if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
676 LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700677 sirt_obj->SetLockWord(thin_locked);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700678 return; // Success!
Elliott Hughes5f791332011-09-15 17:45:30 -0700679 } else {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700680 // We'd overflow the recursion count, so inflate the monitor.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700681 InflateThinLocked(self, sirt_obj, lock_word, 0);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700682 }
683 } else {
684 // Contention.
685 contention_count++;
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700686 Runtime* runtime = Runtime::Current();
687 if (contention_count <= runtime->GetMaxSpinsBeforeThinkLockInflation()) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700688 NanoSleep(1000); // Sleep for 1us and re-attempt.
689 } else {
690 contention_count = 0;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700691 InflateThinLocked(self, sirt_obj, lock_word, 0);
Elliott Hughes5f791332011-09-15 17:45:30 -0700692 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700693 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700694 continue; // Start from the beginning.
Elliott Hughes5f791332011-09-15 17:45:30 -0700695 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700696 case LockWord::kFatLocked: {
697 Monitor* mon = lock_word.FatLockMonitor();
698 mon->Lock(self);
699 return; // Success!
700 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700701 case LockWord::kHashCode: {
702 // Inflate with the existing hashcode.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700703 Inflate(self, nullptr, sirt_obj.get(), lock_word.GetHashCode());
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700704 break;
705 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700706 default: {
707 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
708 return;
709 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700710 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700711 }
712}
713
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800714bool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700715 DCHECK(self != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700716 DCHECK(obj != NULL);
717
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700718 LockWord lock_word = obj->GetLockWord();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700719 SirtRef<mirror::Object> sirt_obj(self, obj);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700720 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700721 case LockWord::kHashCode:
722 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700723 case LockWord::kUnlocked:
Mathieu Chartier590fee92013-09-13 13:46:47 -0700724 FailedUnlock(sirt_obj.get(), self, NULL, NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700725 return false; // Failure.
726 case LockWord::kThinLocked: {
727 uint32_t thread_id = self->GetThreadId();
728 uint32_t owner_thread_id = lock_word.ThinLockOwner();
729 if (owner_thread_id != thread_id) {
730 // TODO: there's a race here with the owner dying while we unlock.
731 Thread* owner =
732 Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700733 FailedUnlock(sirt_obj.get(), self, owner, NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700734 return false; // Failure.
735 } else {
736 // We own the lock, decrease the recursion count.
737 if (lock_word.ThinLockCount() != 0) {
738 uint32_t new_count = lock_word.ThinLockCount() - 1;
739 LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700740 sirt_obj->SetLockWord(thin_locked);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700741 } else {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700742 sirt_obj->SetLockWord(LockWord());
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700743 }
744 return true; // Success!
745 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700746 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700747 case LockWord::kFatLocked: {
748 Monitor* mon = lock_word.FatLockMonitor();
749 return mon->Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700750 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700751 default: {
752 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700753 return false;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700754 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700755 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700756}
757
758/*
759 * Object.wait(). Also called for class init.
760 */
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800761void Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800762 bool interruptShouldThrow, ThreadState why) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700763 DCHECK(self != NULL);
764 DCHECK(obj != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700765
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700766 LockWord lock_word = obj->GetLockWord();
767 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700768 case LockWord::kHashCode:
769 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700770 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800771 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700772 return; // Failure.
773 case LockWord::kThinLocked: {
774 uint32_t thread_id = self->GetThreadId();
775 uint32_t owner_thread_id = lock_word.ThinLockOwner();
776 if (owner_thread_id != thread_id) {
777 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
778 return; // Failure.
779 } else {
780 // We own the lock, inflate to enqueue ourself on the Monitor.
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700781 Inflate(self, self, obj, 0);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700782 lock_word = obj->GetLockWord();
783 }
784 break;
Elliott Hughes5f791332011-09-15 17:45:30 -0700785 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700786 case LockWord::kFatLocked:
787 break; // Already set for a wait.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700788 default: {
789 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
790 return;
791 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700792 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700793 Monitor* mon = lock_word.FatLockMonitor();
794 mon->Wait(self, ms, ns, interruptShouldThrow, why);
Elliott Hughes5f791332011-09-15 17:45:30 -0700795}
796
Ian Rogers13c479e2013-10-11 07:59:01 -0700797void Monitor::DoNotify(Thread* self, mirror::Object* obj, bool notify_all) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700798 DCHECK(self != NULL);
799 DCHECK(obj != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700800
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700801 LockWord lock_word = obj->GetLockWord();
802 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700803 case LockWord::kHashCode:
804 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700805 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800806 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700807 return; // Failure.
808 case LockWord::kThinLocked: {
809 uint32_t thread_id = self->GetThreadId();
810 uint32_t owner_thread_id = lock_word.ThinLockOwner();
811 if (owner_thread_id != thread_id) {
812 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
813 return; // Failure.
814 } else {
815 // We own the lock but there's no Monitor and therefore no waiters.
816 return; // Success.
817 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700818 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700819 case LockWord::kFatLocked: {
820 Monitor* mon = lock_word.FatLockMonitor();
821 if (notify_all) {
822 mon->NotifyAll(self);
823 } else {
824 mon->Notify(self);
825 }
826 return; // Success.
827 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700828 default: {
829 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
830 return;
831 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700832 }
833}
834
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700835uint32_t Monitor::GetLockOwnerThreadId(mirror::Object* obj) {
836 DCHECK(obj != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700837
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700838 LockWord lock_word = obj->GetLockWord();
839 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700840 case LockWord::kHashCode:
841 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700842 case LockWord::kUnlocked:
843 return ThreadList::kInvalidThreadId;
844 case LockWord::kThinLocked:
845 return lock_word.ThinLockOwner();
846 case LockWord::kFatLocked: {
847 Monitor* mon = lock_word.FatLockMonitor();
848 return mon->GetOwnerThreadId();
Elliott Hughes5f791332011-09-15 17:45:30 -0700849 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700850 default: {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700851 LOG(FATAL) << "Unreachable";
852 return ThreadList::kInvalidThreadId;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700853 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700854 }
855}
856
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700857void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800858 ThreadState state = thread->GetState();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700859
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700860 int32_t object_identity_hashcode = 0;
861 uint32_t lock_owner = ThreadList::kInvalidThreadId;
862 std::string pretty_type;
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800863 if (state == kWaiting || state == kTimedWaiting || state == kSleeping) {
864 if (state == kSleeping) {
865 os << " - sleeping on ";
866 } else {
867 os << " - waiting on ";
868 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700869 {
Elliott Hughesf9501702013-01-11 11:22:27 -0800870 Thread* self = Thread::Current();
871 MutexLock mu(self, *thread->wait_mutex_);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800872 Monitor* monitor = thread->wait_monitor_;
873 if (monitor != NULL) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700874 mirror::Object* object = monitor->obj_;
875 object_identity_hashcode = object->IdentityHashCode();
876 pretty_type = PrettyTypeOf(object);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800877 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700878 }
Elliott Hughes34e06962012-04-09 13:55:55 -0700879 } else if (state == kBlocked) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700880 os << " - waiting to lock ";
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700881 mirror::Object* object = thread->monitor_enter_object_;
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700882 if (object != NULL) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700883 object_identity_hashcode = object->IdentityHashCode();
884 lock_owner = object->GetLockOwnerThreadId();
885 pretty_type = PrettyTypeOf(object);
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700886 }
887 } else {
888 // We're not waiting on anything.
889 return;
890 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700891
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700892 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700893 os << StringPrintf("<0x%08x> (a %s)", object_identity_hashcode, pretty_type.c_str());
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700894
Elliott Hughesc5dc2ff2013-01-09 13:44:30 -0800895 // - waiting to lock <0x613f83d8> (a java.lang.Object) held by thread 5
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700896 if (lock_owner != ThreadList::kInvalidThreadId) {
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700897 os << " held by thread " << lock_owner;
898 }
899
900 os << "\n";
901}
902
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800903mirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800904 // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
905 // definition of contended that includes a monitor a thread is trying to enter...
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800906 mirror::Object* result = thread->monitor_enter_object_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700907 if (result == NULL) {
908 // ...but also a monitor that the thread is waiting on.
Elliott Hughesf9501702013-01-11 11:22:27 -0800909 MutexLock mu(Thread::Current(), *thread->wait_mutex_);
910 Monitor* monitor = thread->wait_monitor_;
911 if (monitor != NULL) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700912 result = monitor->GetObject();
Elliott Hughesf9501702013-01-11 11:22:27 -0800913 }
914 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700915 return result;
Elliott Hughesf9501702013-01-11 11:22:27 -0800916}
917
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800918void Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
919 void* callback_context) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700920 mirror::ArtMethod* m = stack_visitor->GetMethod();
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700921 CHECK(m != NULL);
922
923 // Native methods are an easy special case.
924 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
925 if (m->IsNative()) {
926 if (m->IsSynchronized()) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800927 mirror::Object* jni_this = stack_visitor->GetCurrentSirt()->GetReference(0);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800928 callback(jni_this, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700929 }
930 return;
931 }
932
jeffhao61f916c2012-10-25 17:48:51 -0700933 // Proxy methods should not be synchronized.
934 if (m->IsProxyMethod()) {
935 CHECK(!m->IsSynchronized());
936 return;
937 }
938
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700939 // <clinit> is another special case. The runtime holds the class lock while calling <clinit>.
940 MethodHelper mh(m);
941 if (mh.IsClassInitializer()) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800942 callback(m->GetDeclaringClass(), callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700943 // Fall through because there might be synchronization in the user code too.
944 }
945
946 // Is there any reason to believe there's any synchronization in this method?
947 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -0700948 CHECK(code_item != NULL) << PrettyMethod(m);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700949 if (code_item->tries_size_ == 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700950 return; // No "tries" implies no synchronization, so no held locks to report.
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700951 }
952
Elliott Hughes80537bb2013-01-04 16:37:26 -0800953 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
954 // the locks held in this stack frame.
955 std::vector<uint32_t> monitor_enter_dex_pcs;
956 verifier::MethodVerifier::FindLocksAtDexPc(m, stack_visitor->GetDexPc(), monitor_enter_dex_pcs);
957 if (monitor_enter_dex_pcs.empty()) {
958 return;
959 }
960
Elliott Hughes80537bb2013-01-04 16:37:26 -0800961 for (size_t i = 0; i < monitor_enter_dex_pcs.size(); ++i) {
962 // The verifier works in terms of the dex pcs of the monitor-enter instructions.
963 // We want the registers used by those instructions (so we can read the values out of them).
964 uint32_t dex_pc = monitor_enter_dex_pcs[i];
965 uint16_t monitor_enter_instruction = code_item->insns_[dex_pc];
966
967 // Quick sanity check.
968 if ((monitor_enter_instruction & 0xff) != Instruction::MONITOR_ENTER) {
969 LOG(FATAL) << "expected monitor-enter @" << dex_pc << "; was "
970 << reinterpret_cast<void*>(monitor_enter_instruction);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700971 }
972
Elliott Hughes80537bb2013-01-04 16:37:26 -0800973 uint16_t monitor_register = ((monitor_enter_instruction >> 8) & 0xff);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800974 mirror::Object* o = reinterpret_cast<mirror::Object*>(stack_visitor->GetVReg(m, monitor_register,
975 kReferenceVReg));
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800976 callback(o, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700977 }
978}
979
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700980bool Monitor::IsValidLockWord(LockWord lock_word) {
981 switch (lock_word.GetState()) {
982 case LockWord::kUnlocked:
983 // Nothing to check.
984 return true;
985 case LockWord::kThinLocked:
986 // Basic sanity check of owner.
987 return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
988 case LockWord::kFatLocked: {
989 // Check the monitor appears in the monitor list.
990 Monitor* mon = lock_word.FatLockMonitor();
991 MonitorList* list = Runtime::Current()->GetMonitorList();
992 MutexLock mu(Thread::Current(), list->monitor_list_lock_);
993 for (Monitor* list_mon : list->list_) {
994 if (mon == list_mon) {
995 return true; // Found our monitor.
996 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700997 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700998 return false; // Fail - unowned monitor in an object.
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700999 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001000 case LockWord::kHashCode:
1001 return true;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001002 default:
1003 LOG(FATAL) << "Unreachable";
1004 return false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001005 }
1006}
1007
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001008bool Monitor::IsLocked() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1009 MutexLock mu(Thread::Current(), monitor_lock_);
1010 return owner_ != nullptr;
1011}
1012
Ian Rogersef7d42f2014-01-06 12:55:46 -08001013void Monitor::TranslateLocation(mirror::ArtMethod* method, uint32_t dex_pc,
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001014 const char** source_file, uint32_t* line_number) const {
jeffhao33dc7712011-11-09 17:54:24 -08001015 // If method is null, location is unknown
1016 if (method == NULL) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001017 *source_file = "";
1018 *line_number = 0;
jeffhao33dc7712011-11-09 17:54:24 -08001019 return;
1020 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001021 MethodHelper mh(method);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001022 *source_file = mh.GetDeclaringClassSourceFile();
1023 if (*source_file == NULL) {
1024 *source_file = "";
Elliott Hughes12c51e32012-01-17 20:25:05 -08001025 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001026 *line_number = mh.GetLineNumFromDexPC(dex_pc);
1027}
1028
1029uint32_t Monitor::GetOwnerThreadId() {
1030 MutexLock mu(Thread::Current(), monitor_lock_);
1031 Thread* owner = owner_;
1032 if (owner != NULL) {
1033 return owner->GetThreadId();
1034 } else {
1035 return ThreadList::kInvalidThreadId;
1036 }
jeffhao33dc7712011-11-09 17:54:24 -08001037}
1038
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001039MonitorList::MonitorList()
1040 : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock"),
1041 monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001042}
1043
1044MonitorList::~MonitorList() {
Ian Rogers50b35e22012-10-04 10:09:15 -07001045 MutexLock mu(Thread::Current(), monitor_list_lock_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001046 STLDeleteElements(&list_);
1047}
1048
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001049void MonitorList::DisallowNewMonitors() {
Ian Rogers50b35e22012-10-04 10:09:15 -07001050 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001051 allow_new_monitors_ = false;
1052}
1053
1054void MonitorList::AllowNewMonitors() {
1055 Thread* self = Thread::Current();
1056 MutexLock mu(self, monitor_list_lock_);
1057 allow_new_monitors_ = true;
1058 monitor_add_condition_.Broadcast(self);
1059}
1060
1061void MonitorList::Add(Monitor* m) {
1062 Thread* self = Thread::Current();
1063 MutexLock mu(self, monitor_list_lock_);
1064 while (UNLIKELY(!allow_new_monitors_)) {
1065 monitor_add_condition_.WaitHoldingLocks(self);
1066 }
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001067 list_.push_front(m);
1068}
1069
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08001070void MonitorList::SweepMonitorList(IsMarkedCallback* callback, void* arg) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001071 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001072 for (auto it = list_.begin(); it != list_.end(); ) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001073 Monitor* m = *it;
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001074 mirror::Object* obj = m->GetObject();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001075 // The object of a monitor can be null if we have deflated it.
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08001076 mirror::Object* new_obj = obj != nullptr ? callback(obj, arg) : nullptr;
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001077 if (new_obj == nullptr) {
1078 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
1079 << m->GetObject();
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001080 delete m;
1081 it = list_.erase(it);
1082 } else {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001083 m->SetObject(new_obj);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001084 ++it;
1085 }
1086 }
1087}
1088
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001089MonitorInfo::MonitorInfo(mirror::Object* obj) : owner_(NULL), entry_count_(0) {
1090 DCHECK(obj != NULL);
1091
1092 LockWord lock_word = obj->GetLockWord();
1093 switch (lock_word.GetState()) {
1094 case LockWord::kUnlocked:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001095 // Fall-through.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001096 case LockWord::kForwardingAddress:
1097 // Fall-through.
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001098 case LockWord::kHashCode:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001099 break;
1100 case LockWord::kThinLocked:
1101 owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
1102 entry_count_ = 1 + lock_word.ThinLockCount();
1103 // Thin locks have no waiters.
1104 break;
1105 case LockWord::kFatLocked: {
1106 Monitor* mon = lock_word.FatLockMonitor();
1107 owner_ = mon->owner_;
1108 entry_count_ = 1 + mon->lock_count_;
1109 for (Thread* waiter = mon->wait_set_; waiter != NULL; waiter = waiter->wait_next_) {
1110 waiters_.push_back(waiter);
1111 }
1112 break;
Elliott Hughesf327e072013-01-09 16:01:26 -08001113 }
1114 }
1115}
1116
Elliott Hughes5f791332011-09-15 17:45:30 -07001117} // namespace art