blob: e0cd193b56777f3009bcb2bdd26189d697c76bf2 [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.
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700114 LockWord lw(GetObject()->GetLockWord(false));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700115 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.
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700140 bool success = GetObject()->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);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700160 DCHECK(thread->GetWaitNext() == nullptr) << thread->GetWaitNext();
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_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700168 while (t->GetWaitNext() != nullptr) {
169 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700170 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700171 t->SetWaitNext(thread);
Elliott Hughes5f791332011-09-15 17:45:30 -0700172}
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) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700185 wait_set_ = thread->GetWaitNext();
186 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700187 return;
188 }
189
190 Thread* t = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700191 while (t->GetWaitNext() != NULL) {
192 if (t->GetWaitNext() == thread) {
193 t->SetWaitNext(thread->GetWaitNext());
194 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700195 return;
196 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700197 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700198 }
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) {
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700208 if (owner_ == nullptr) { // Unowned.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700209 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_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700226 // Do this before releasing the lock so that we don't get deflated.
227 ++num_waiters_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700228 monitor_lock_.Unlock(self); // Let go of locks in order.
Elliott Hughes5f791332011-09-15 17:45:30 -0700229 {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700230 ScopedThreadStateChange tsc(self, kBlocked); // Change to blocked and give up mutator_lock_.
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700231 self->SetMonitorEnterObject(GetObject());
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700232 MutexLock mu2(self, monitor_lock_); // Reacquire monitor_lock_ without mutator_lock_ for Wait.
233 if (owner_ != NULL) { // Did the owner_ give the lock up?
234 monitor_contenders_.Wait(self); // Still contended so wait.
235 // Woken from contention.
236 if (log_contention) {
237 uint64_t wait_ms = MilliTime() - wait_start_ms;
238 uint32_t sample_percent;
239 if (wait_ms >= lock_profiling_threshold_) {
240 sample_percent = 100;
241 } else {
242 sample_percent = 100 * wait_ms / lock_profiling_threshold_;
243 }
244 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
245 const char* owners_filename;
246 uint32_t owners_line_number;
247 TranslateLocation(owners_method, owners_dex_pc, &owners_filename, &owners_line_number);
248 LogContentionEvent(self, wait_ms, sample_percent, owners_filename, owners_line_number);
249 }
250 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700251 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700252 self->SetMonitorEnterObject(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700253 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700254 monitor_lock_.Lock(self); // Reacquire locks in order.
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700255 --num_waiters_;
Elliott Hughesfc861622011-10-17 17:57:47 -0700256 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700257}
258
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800259static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
260 __attribute__((format(printf, 1, 2)));
261
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700262static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700263 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800264 va_list args;
265 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800266 Thread* self = Thread::Current();
267 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
268 self->ThrowNewExceptionV(throw_location, "Ljava/lang/IllegalMonitorStateException;", fmt, args);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700269 if (!Runtime::Current()->IsStarted() || VLOG_IS_ON(monitor)) {
Brian Carlstrom64277f32012-03-26 23:53:34 -0700270 std::ostringstream ss;
Ian Rogers62d6c772013-02-27 08:32:07 -0800271 self->Dump(ss);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700272 LOG(Runtime::Current()->IsStarted() ? INFO : ERROR)
273 << self->GetException(NULL)->Dump() << "\n" << ss.str();
Brian Carlstrom64277f32012-03-26 23:53:34 -0700274 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800275 va_end(args);
276}
277
Elliott Hughesd4237412012-02-21 11:24:45 -0800278static std::string ThreadToString(Thread* thread) {
279 if (thread == NULL) {
280 return "NULL";
281 }
282 std::ostringstream oss;
283 // TODO: alternatively, we could just return the thread's name.
284 oss << *thread;
285 return oss.str();
286}
287
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800288void Monitor::FailedUnlock(mirror::Object* o, Thread* expected_owner, Thread* found_owner,
Elliott Hughesffb465f2012-03-01 18:46:05 -0800289 Monitor* monitor) {
290 Thread* current_owner = NULL;
291 std::string current_owner_string;
292 std::string expected_owner_string;
293 std::string found_owner_string;
294 {
295 // TODO: isn't this too late to prevent threads from disappearing?
296 // Acquire thread list lock so threads won't disappear from under us.
Ian Rogers50b35e22012-10-04 10:09:15 -0700297 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Elliott Hughesffb465f2012-03-01 18:46:05 -0800298 // Re-read owner now that we hold lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700299 current_owner = (monitor != NULL) ? monitor->GetOwner() : NULL;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800300 // Get short descriptions of the threads involved.
301 current_owner_string = ThreadToString(current_owner);
302 expected_owner_string = ThreadToString(expected_owner);
303 found_owner_string = ThreadToString(found_owner);
304 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800305 if (current_owner == NULL) {
306 if (found_owner == NULL) {
307 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
308 " on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800309 PrettyTypeOf(o).c_str(),
310 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800311 } else {
312 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800313 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
314 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800315 found_owner_string.c_str(),
316 PrettyTypeOf(o).c_str(),
317 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800318 }
319 } else {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800320 if (found_owner == NULL) {
321 // Race: originally there was no owner, there is now
322 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
323 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800324 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 if (found_owner != current_owner) {
329 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800330 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
331 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800332 found_owner_string.c_str(),
333 current_owner_string.c_str(),
334 PrettyTypeOf(o).c_str(),
335 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800336 } else {
337 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
338 " on thread '%s",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800339 current_owner_string.c_str(),
340 PrettyTypeOf(o).c_str(),
341 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800342 }
343 }
344 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700345}
346
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700347bool Monitor::Unlock(Thread* self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700348 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700349 MutexLock mu(self, monitor_lock_);
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800350 Thread* owner = owner_;
351 if (owner == self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700352 // We own the monitor, so nobody else can be in here.
353 if (lock_count_ == 0) {
354 owner_ = NULL;
jeffhao33dc7712011-11-09 17:54:24 -0800355 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700356 locking_dex_pc_ = 0;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700357 // Wake a contender.
358 monitor_contenders_.Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700359 } else {
360 --lock_count_;
361 }
362 } else {
363 // We don't own this, so we're not allowed to unlock it.
364 // The JNI spec says that we should throw IllegalMonitorStateException
365 // in this case.
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700366 FailedUnlock(GetObject(), self, owner, this);
Elliott Hughes5f791332011-09-15 17:45:30 -0700367 return false;
368 }
369 return true;
370}
371
Elliott Hughes5f791332011-09-15 17:45:30 -0700372/*
373 * Wait on a monitor until timeout, interrupt, or notification. Used for
374 * Object.wait() and (somewhat indirectly) Thread.sleep() and Thread.join().
375 *
376 * If another thread calls Thread.interrupt(), we throw InterruptedException
377 * and return immediately if one of the following are true:
378 * - blocked in wait(), wait(long), or wait(long, int) methods of Object
379 * - blocked in join(), join(long), or join(long, int) methods of Thread
380 * - blocked in sleep(long), or sleep(long, int) methods of Thread
381 * Otherwise, we set the "interrupted" flag.
382 *
383 * Checks to make sure that "ns" is in the range 0-999999
384 * (i.e. fractions of a millisecond) and throws the appropriate
385 * exception if it isn't.
386 *
387 * The spec allows "spurious wakeups", and recommends that all code using
388 * Object.wait() do so in a loop. This appears to derive from concerns
389 * about pthread_cond_wait() on multiprocessor systems. Some commentary
390 * on the web casts doubt on whether these can/should occur.
391 *
392 * Since we're allowed to wake up "early", we clamp extremely long durations
393 * to return at the end of the 32-bit time epoch.
394 */
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800395void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
396 bool interruptShouldThrow, ThreadState why) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700397 DCHECK(self != NULL);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800398 DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
Elliott Hughes5f791332011-09-15 17:45:30 -0700399
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700400 monitor_lock_.Lock(self);
401
Elliott Hughes5f791332011-09-15 17:45:30 -0700402 // Make sure that we hold the lock.
403 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800404 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700405 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700406 return;
407 }
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800408
Elliott Hughesdf42c482013-01-09 12:49:02 -0800409 // We need to turn a zero-length timed wait into a regular wait because
410 // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
411 if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
412 why = kWaiting;
413 }
414
Elliott Hughes5f791332011-09-15 17:45:30 -0700415 // Enforce the timeout range.
416 if (ms < 0 || ns < 0 || ns > 999999) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800417 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
418 self->ThrowNewExceptionF(throw_location, "Ljava/lang/IllegalArgumentException;",
Ian Rogersef7d42f2014-01-06 12:55:46 -0800419 "timeout arguments out of range: ms=%" PRId64 " ns=%d", ms, ns);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700420 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700421 return;
422 }
423
Elliott Hughes5f791332011-09-15 17:45:30 -0700424 /*
425 * Add ourselves to the set of threads waiting on this monitor, and
426 * release our hold. We need to let it go even if we're a few levels
427 * deep in a recursive lock, and we need to restore that later.
428 *
429 * We append to the wait set ahead of clearing the count and owner
430 * fields so the subroutine can check that the calling thread owns
431 * the monitor. Aside from that, the order of member updates is
432 * not order sensitive as we hold the pthread mutex.
433 */
434 AppendToWaitSet(self);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700435 ++num_waiters_;
Ian Rogers0399dde2012-06-06 17:09:28 -0700436 int prev_lock_count = lock_count_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700437 lock_count_ = 0;
438 owner_ = NULL;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800439 mirror::ArtMethod* saved_method = locking_method_;
jeffhao33dc7712011-11-09 17:54:24 -0800440 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700441 uintptr_t saved_dex_pc = locking_dex_pc_;
442 locking_dex_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700443
444 /*
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800445 * Update thread state. If the GC wakes up, it'll ignore us, knowing
Elliott Hughes5f791332011-09-15 17:45:30 -0700446 * that we won't touch any references in this state, and we'll check
447 * our suspend mode before we transition out.
448 */
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800449 self->TransitionFromRunnableToSuspended(why);
Elliott Hughes5f791332011-09-15 17:45:30 -0700450
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800451 bool was_interrupted = false;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700452 {
453 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700454 MutexLock mu(self, *self->GetWaitMutex());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700455
456 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
457 // non-NULL a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
458 // up.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700459 DCHECK(self->GetWaitMonitor() == nullptr);
460 self->SetWaitMonitor(this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700461
462 // Release the monitor lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700463 monitor_contenders_.Signal(self);
464 monitor_lock_.Unlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700465
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800466 // Handle the case where the thread was interrupted before we called wait().
Ian Rogersdd7624d2014-03-14 17:43:00 -0700467 if (self->IsInterruptedLocked()) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800468 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700469 } else {
470 // Wait for a notification or a timeout to occur.
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800471 if (why == kWaiting) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700472 self->GetWaitConditionVariable()->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700473 } else {
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800474 DCHECK(why == kTimedWaiting || why == kSleeping) << why;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700475 self->GetWaitConditionVariable()->TimedWait(self, ms, ns);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700476 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700477 if (self->IsInterruptedLocked()) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800478 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700479 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700480 self->SetInterruptedLocked(false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700481 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700482 }
483
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700484 // Set self->status back to kRunnable, and self-suspend if needed.
485 self->TransitionFromSuspendedToRunnable();
Elliott Hughes5f791332011-09-15 17:45:30 -0700486
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800487 {
488 // We reset the thread's wait_monitor_ field after transitioning back to runnable so
489 // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
490 // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
491 // are waiting on "null".)
Ian Rogersdd7624d2014-03-14 17:43:00 -0700492 MutexLock mu(self, *self->GetWaitMutex());
493 DCHECK(self->GetWaitMonitor() != nullptr);
494 self->SetWaitMonitor(nullptr);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800495 }
496
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700497 // Re-acquire the monitor and lock.
Elliott Hughes5f791332011-09-15 17:45:30 -0700498 Lock(self);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700499 monitor_lock_.Lock(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700500 self->GetWaitMutex()->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700501
Elliott Hughes5f791332011-09-15 17:45:30 -0700502 /*
503 * We remove our thread from wait set after restoring the count
504 * and owner fields so the subroutine can check that the calling
505 * thread owns the monitor. Aside from that, the order of member
506 * updates is not order sensitive as we hold the pthread mutex.
507 */
508 owner_ = self;
Ian Rogers0399dde2012-06-06 17:09:28 -0700509 lock_count_ = prev_lock_count;
510 locking_method_ = saved_method;
511 locking_dex_pc_ = saved_dex_pc;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700512 --num_waiters_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700513 RemoveFromWaitSet(self);
514
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800515 if (was_interrupted) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700516 /*
517 * We were interrupted while waiting, or somebody interrupted an
518 * un-interruptible thread earlier and we're bailing out immediately.
519 *
520 * The doc sayeth: "The interrupted status of the current thread is
521 * cleared when this exception is thrown."
522 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700523 {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700524 MutexLock mu(self, *self->GetWaitMutex());
525 self->SetInterruptedLocked(false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700526 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700527 if (interruptShouldThrow) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800528 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
529 self->ThrowNewException(throw_location, "Ljava/lang/InterruptedException;", NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700530 }
531 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700532 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700533}
534
535void Monitor::Notify(Thread* self) {
536 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700537 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700538 // Make sure that we hold the lock.
539 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800540 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700541 return;
542 }
543 // Signal the first waiting thread in the wait set.
544 while (wait_set_ != NULL) {
545 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700546 wait_set_ = thread->GetWaitNext();
547 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700548
549 // Check to see if the thread is still waiting.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700550 MutexLock mu(self, *thread->GetWaitMutex());
551 if (thread->GetWaitMonitor() != nullptr) {
552 thread->GetWaitConditionVariable()->Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700553 return;
554 }
555 }
556}
557
558void Monitor::NotifyAll(Thread* self) {
559 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700560 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700561 // Make sure that we hold the lock.
562 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800563 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700564 return;
565 }
566 // Signal all threads in the wait set.
567 while (wait_set_ != NULL) {
568 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700569 wait_set_ = thread->GetWaitNext();
570 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700571 thread->Notify();
572 }
573}
574
Mathieu Chartier590fee92013-09-13 13:46:47 -0700575bool Monitor::Deflate(Thread* self, mirror::Object* obj) {
576 DCHECK(obj != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700577 // Don't need volatile since we only deflate with mutators suspended.
578 LockWord lw(obj->GetLockWord(false));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700579 // If the lock isn't an inflated monitor, then we don't need to deflate anything.
580 if (lw.GetState() == LockWord::kFatLocked) {
581 Monitor* monitor = lw.FatLockMonitor();
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700582 DCHECK(monitor != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700583 MutexLock mu(self, monitor->monitor_lock_);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700584 // Can't deflate if we have anybody waiting on the CV.
585 if (monitor->num_waiters_ > 0) {
586 return false;
587 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700588 Thread* owner = monitor->owner_;
589 if (owner != nullptr) {
590 // Can't deflate if we are locked and have a hash code.
591 if (monitor->HasHashCode()) {
592 return false;
593 }
594 // Can't deflate if our lock count is too high.
595 if (monitor->lock_count_ > LockWord::kThinLockMaxCount) {
596 return false;
597 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700598 // Deflate to a thin lock.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700599 obj->SetLockWord(LockWord::FromThinLockId(owner->GetThreadId(), monitor->lock_count_), false);
600 VLOG(monitor) << "Deflated " << obj << " to thin lock " << owner->GetTid() << " / "
601 << monitor->lock_count_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700602 } else if (monitor->HasHashCode()) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700603 obj->SetLockWord(LockWord::FromHashCode(monitor->GetHashCode()), false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700604 VLOG(monitor) << "Deflated " << obj << " to hash monitor " << monitor->GetHashCode();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700605 } else {
606 // No lock and no hash, just put an empty lock word inside the object.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700607 obj->SetLockWord(LockWord(), false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700608 VLOG(monitor) << "Deflated" << obj << " to empty lock word";
Mathieu Chartier590fee92013-09-13 13:46:47 -0700609 }
610 // The monitor is deflated, mark the object as nullptr so that we know to delete it during the
611 // next GC.
612 monitor->obj_ = nullptr;
613 }
614 return true;
615}
616
Elliott Hughes5f791332011-09-15 17:45:30 -0700617/*
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700618 * Changes the shape of a monitor from thin to fat, preserving the internal lock state. The calling
619 * thread must own the lock or the owner must be suspended. There's a race with other threads
620 * inflating the lock and so the caller should read the monitor following the call.
Elliott Hughes5f791332011-09-15 17:45:30 -0700621 */
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700622void Monitor::Inflate(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700623 DCHECK(self != NULL);
624 DCHECK(obj != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700625 // Allocate and acquire a new monitor.
Ian Rogers700a4022014-05-19 16:49:03 -0700626 std::unique_ptr<Monitor> m(new Monitor(self, owner, obj, hash_code));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700627 if (m->Install(self)) {
Haifeng Li86ab7912014-05-16 10:47:59 +0800628 if (owner != nullptr) {
629 VLOG(monitor) << "monitor: thread" << owner->GetThreadId()
630 << " created monitor " << m.get() << " for object " << obj;
631 } else {
632 VLOG(monitor) << "monitor: Inflate with hashcode " << hash_code
633 << " created monitor " << m.get() << " for object " << obj;
634 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700635 Runtime::Current()->GetMonitorList()->Add(m.release());
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700636 CHECK_EQ(obj->GetLockWord(true).GetState(), LockWord::kFatLocked);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700637 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700638}
639
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700640void Monitor::InflateThinLocked(Thread* self, Handle<mirror::Object>& obj, LockWord lock_word,
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700641 uint32_t hash_code) {
642 DCHECK_EQ(lock_word.GetState(), LockWord::kThinLocked);
643 uint32_t owner_thread_id = lock_word.ThinLockOwner();
644 if (owner_thread_id == self->GetThreadId()) {
645 // We own the monitor, we can easily inflate it.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700646 Inflate(self, self, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700647 } else {
648 ThreadList* thread_list = Runtime::Current()->GetThreadList();
649 // Suspend the owner, inflate. First change to blocked and give up mutator_lock_.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700650 self->SetMonitorEnterObject(obj.Get());
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700651 bool timed_out;
652 Thread* owner;
653 {
654 ScopedThreadStateChange tsc(self, kBlocked);
655 owner = thread_list->SuspendThreadByThreadId(owner_thread_id, false, &timed_out);
656 }
657 if (owner != nullptr) {
658 // We succeeded in suspending the thread, check the lock's status didn't change.
659 lock_word = obj->GetLockWord(true);
660 if (lock_word.GetState() == LockWord::kThinLocked &&
661 lock_word.ThinLockOwner() == owner_thread_id) {
662 // Go ahead and inflate the lock.
663 Inflate(self, owner, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700664 }
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700665 thread_list->Resume(owner, false);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700666 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700667 self->SetMonitorEnterObject(nullptr);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700668 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700669}
670
Ian Rogers719d1a32014-03-06 12:13:39 -0800671// Fool annotalysis into thinking that the lock on obj is acquired.
672static mirror::Object* FakeLock(mirror::Object* obj)
673 EXCLUSIVE_LOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
674 return obj;
675}
676
677// Fool annotalysis into thinking that the lock on obj is release.
678static mirror::Object* FakeUnlock(mirror::Object* obj)
679 UNLOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
680 return obj;
681}
682
Mathieu Chartiere7e8a5f2014-02-14 16:59:41 -0800683mirror::Object* Monitor::MonitorEnter(Thread* self, mirror::Object* obj) {
Elliott Hughes4681c802011-09-25 18:04:37 -0700684 DCHECK(self != NULL);
685 DCHECK(obj != NULL);
Ian Rogers719d1a32014-03-06 12:13:39 -0800686 obj = FakeLock(obj);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700687 uint32_t thread_id = self->GetThreadId();
688 size_t contention_count = 0;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700689 StackHandleScope<1> hs(self);
690 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700691 while (true) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700692 LockWord lock_word = h_obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700693 switch (lock_word.GetState()) {
694 case LockWord::kUnlocked: {
695 LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700696 if (h_obj->CasLockWord(lock_word, thin_locked)) {
Ian Rogersb122a4b2013-11-19 18:00:50 -0800697 QuasiAtomic::MembarLoadLoad();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700698 return h_obj.Get(); // Success!
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700699 }
700 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -0700701 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700702 case LockWord::kThinLocked: {
703 uint32_t owner_thread_id = lock_word.ThinLockOwner();
704 if (owner_thread_id == thread_id) {
705 // We own the lock, increase the recursion count.
706 uint32_t new_count = lock_word.ThinLockCount() + 1;
707 if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
708 LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700709 h_obj->SetLockWord(thin_locked, true);
710 return h_obj.Get(); // Success!
Elliott Hughes5f791332011-09-15 17:45:30 -0700711 } else {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700712 // We'd overflow the recursion count, so inflate the monitor.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700713 InflateThinLocked(self, h_obj, lock_word, 0);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700714 }
715 } else {
716 // Contention.
717 contention_count++;
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700718 Runtime* runtime = Runtime::Current();
719 if (contention_count <= runtime->GetMaxSpinsBeforeThinkLockInflation()) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700720 NanoSleep(1000); // Sleep for 1us and re-attempt.
721 } else {
722 contention_count = 0;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700723 InflateThinLocked(self, h_obj, lock_word, 0);
Elliott Hughes5f791332011-09-15 17:45:30 -0700724 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700725 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700726 continue; // Start from the beginning.
Elliott Hughes5f791332011-09-15 17:45:30 -0700727 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700728 case LockWord::kFatLocked: {
729 Monitor* mon = lock_word.FatLockMonitor();
730 mon->Lock(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700731 return h_obj.Get(); // Success!
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700732 }
Ian Rogers719d1a32014-03-06 12:13:39 -0800733 case LockWord::kHashCode:
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700734 // Inflate with the existing hashcode.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700735 Inflate(self, nullptr, h_obj.Get(), lock_word.GetHashCode());
Ian Rogers719d1a32014-03-06 12:13:39 -0800736 continue; // Start from the beginning.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700737 default: {
738 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700739 return h_obj.Get();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700740 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700741 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700742 }
743}
744
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800745bool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700746 DCHECK(self != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700747 DCHECK(obj != NULL);
Ian Rogers719d1a32014-03-06 12:13:39 -0800748 obj = FakeUnlock(obj);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700749 LockWord lock_word = obj->GetLockWord(true);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700750 StackHandleScope<1> hs(self);
751 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700752 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700753 case LockWord::kHashCode:
754 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700755 case LockWord::kUnlocked:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700756 FailedUnlock(h_obj.Get(), self, nullptr, nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700757 return false; // Failure.
758 case LockWord::kThinLocked: {
759 uint32_t thread_id = self->GetThreadId();
760 uint32_t owner_thread_id = lock_word.ThinLockOwner();
761 if (owner_thread_id != thread_id) {
762 // TODO: there's a race here with the owner dying while we unlock.
763 Thread* owner =
764 Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700765 FailedUnlock(h_obj.Get(), self, owner, nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700766 return false; // Failure.
767 } else {
768 // We own the lock, decrease the recursion count.
769 if (lock_word.ThinLockCount() != 0) {
770 uint32_t new_count = lock_word.ThinLockCount() - 1;
771 LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700772 h_obj->SetLockWord(thin_locked, true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700773 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700774 h_obj->SetLockWord(LockWord(), true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700775 }
776 return true; // Success!
777 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700778 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700779 case LockWord::kFatLocked: {
780 Monitor* mon = lock_word.FatLockMonitor();
781 return mon->Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700782 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700783 default: {
784 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700785 return false;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700786 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700787 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700788}
789
790/*
791 * Object.wait(). Also called for class init.
792 */
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800793void Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800794 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700795 DCHECK(self != nullptr);
796 DCHECK(obj != nullptr);
797 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700798 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700799 case LockWord::kHashCode:
800 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700801 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800802 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700803 return; // Failure.
804 case LockWord::kThinLocked: {
805 uint32_t thread_id = self->GetThreadId();
806 uint32_t owner_thread_id = lock_word.ThinLockOwner();
807 if (owner_thread_id != thread_id) {
808 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
809 return; // Failure.
810 } else {
811 // We own the lock, inflate to enqueue ourself on the Monitor.
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700812 Inflate(self, self, obj, 0);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700813 lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700814 }
815 break;
Elliott Hughes5f791332011-09-15 17:45:30 -0700816 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700817 case LockWord::kFatLocked:
818 break; // Already set for a wait.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700819 default: {
820 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
821 return;
822 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700823 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700824 Monitor* mon = lock_word.FatLockMonitor();
825 mon->Wait(self, ms, ns, interruptShouldThrow, why);
Elliott Hughes5f791332011-09-15 17:45:30 -0700826}
827
Ian Rogers13c479e2013-10-11 07:59:01 -0700828void Monitor::DoNotify(Thread* self, mirror::Object* obj, bool notify_all) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700829 DCHECK(self != nullptr);
830 DCHECK(obj != nullptr);
831 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700832 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700833 case LockWord::kHashCode:
834 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700835 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800836 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700837 return; // Failure.
838 case LockWord::kThinLocked: {
839 uint32_t thread_id = self->GetThreadId();
840 uint32_t owner_thread_id = lock_word.ThinLockOwner();
841 if (owner_thread_id != thread_id) {
842 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
843 return; // Failure.
844 } else {
845 // We own the lock but there's no Monitor and therefore no waiters.
846 return; // Success.
847 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700848 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700849 case LockWord::kFatLocked: {
850 Monitor* mon = lock_word.FatLockMonitor();
851 if (notify_all) {
852 mon->NotifyAll(self);
853 } else {
854 mon->Notify(self);
855 }
856 return; // Success.
857 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700858 default: {
859 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
860 return;
861 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700862 }
863}
864
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700865uint32_t Monitor::GetLockOwnerThreadId(mirror::Object* obj) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700866 DCHECK(obj != nullptr);
867 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700868 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700869 case LockWord::kHashCode:
870 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700871 case LockWord::kUnlocked:
872 return ThreadList::kInvalidThreadId;
873 case LockWord::kThinLocked:
874 return lock_word.ThinLockOwner();
875 case LockWord::kFatLocked: {
876 Monitor* mon = lock_word.FatLockMonitor();
877 return mon->GetOwnerThreadId();
Elliott Hughes5f791332011-09-15 17:45:30 -0700878 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700879 default: {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700880 LOG(FATAL) << "Unreachable";
881 return ThreadList::kInvalidThreadId;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700882 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700883 }
884}
885
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700886void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
Ian Rogersd803bc72014-04-01 15:33:03 -0700887 // Determine the wait message and object we're waiting or blocked upon.
888 mirror::Object* pretty_object = nullptr;
889 const char* wait_message = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700890 uint32_t lock_owner = ThreadList::kInvalidThreadId;
Ian Rogersd803bc72014-04-01 15:33:03 -0700891 ThreadState state = thread->GetState();
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800892 if (state == kWaiting || state == kTimedWaiting || state == kSleeping) {
Ian Rogersd803bc72014-04-01 15:33:03 -0700893 wait_message = (state == kSleeping) ? " - sleeping on " : " - waiting on ";
894 Thread* self = Thread::Current();
895 MutexLock mu(self, *thread->GetWaitMutex());
896 Monitor* monitor = thread->GetWaitMonitor();
897 if (monitor != nullptr) {
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700898 pretty_object = monitor->GetObject();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700899 }
Elliott Hughes34e06962012-04-09 13:55:55 -0700900 } else if (state == kBlocked) {
Ian Rogersd803bc72014-04-01 15:33:03 -0700901 wait_message = " - waiting to lock ";
902 pretty_object = thread->GetMonitorEnterObject();
903 if (pretty_object != nullptr) {
904 lock_owner = pretty_object->GetLockOwnerThreadId();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700905 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700906 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700907
Ian Rogersd803bc72014-04-01 15:33:03 -0700908 if (wait_message != nullptr) {
909 if (pretty_object == nullptr) {
910 os << wait_message << "an unknown object";
911 } else {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700912 if ((pretty_object->GetLockWord(true).GetState() == LockWord::kThinLocked) &&
Ian Rogersd803bc72014-04-01 15:33:03 -0700913 Locks::mutator_lock_->IsExclusiveHeld(Thread::Current())) {
914 // Getting the identity hashcode here would result in lock inflation and suspension of the
915 // current thread, which isn't safe if this is the only runnable thread.
916 os << wait_message << StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)",
917 reinterpret_cast<intptr_t>(pretty_object),
918 PrettyTypeOf(pretty_object).c_str());
919 } else {
920 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
921 os << wait_message << StringPrintf("<0x%08x> (a %s)", pretty_object->IdentityHashCode(),
922 PrettyTypeOf(pretty_object).c_str());
923 }
924 }
925 // - waiting to lock <0x613f83d8> (a java.lang.Object) held by thread 5
926 if (lock_owner != ThreadList::kInvalidThreadId) {
927 os << " held by thread " << lock_owner;
928 }
929 os << "\n";
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700930 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700931}
932
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800933mirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800934 // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
935 // definition of contended that includes a monitor a thread is trying to enter...
Ian Rogersdd7624d2014-03-14 17:43:00 -0700936 mirror::Object* result = thread->GetMonitorEnterObject();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700937 if (result == NULL) {
938 // ...but also a monitor that the thread is waiting on.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700939 MutexLock mu(Thread::Current(), *thread->GetWaitMutex());
940 Monitor* monitor = thread->GetWaitMonitor();
Elliott Hughesf9501702013-01-11 11:22:27 -0800941 if (monitor != NULL) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700942 result = monitor->GetObject();
Elliott Hughesf9501702013-01-11 11:22:27 -0800943 }
944 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700945 return result;
Elliott Hughesf9501702013-01-11 11:22:27 -0800946}
947
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800948void Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
949 void* callback_context) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700950 mirror::ArtMethod* m = stack_visitor->GetMethod();
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700951 CHECK(m != NULL);
952
953 // Native methods are an easy special case.
954 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
955 if (m->IsNative()) {
956 if (m->IsSynchronized()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700957 mirror::Object* jni_this = stack_visitor->GetCurrentHandleScope()->GetReference(0);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800958 callback(jni_this, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700959 }
960 return;
961 }
962
jeffhao61f916c2012-10-25 17:48:51 -0700963 // Proxy methods should not be synchronized.
964 if (m->IsProxyMethod()) {
965 CHECK(!m->IsSynchronized());
966 return;
967 }
968
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700969 // <clinit> is another special case. The runtime holds the class lock while calling <clinit>.
970 MethodHelper mh(m);
971 if (mh.IsClassInitializer()) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800972 callback(m->GetDeclaringClass(), callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700973 // Fall through because there might be synchronization in the user code too.
974 }
975
976 // Is there any reason to believe there's any synchronization in this method?
977 const DexFile::CodeItem* code_item = mh.GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -0700978 CHECK(code_item != NULL) << PrettyMethod(m);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700979 if (code_item->tries_size_ == 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700980 return; // No "tries" implies no synchronization, so no held locks to report.
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700981 }
982
Elliott Hughes80537bb2013-01-04 16:37:26 -0800983 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
984 // the locks held in this stack frame.
985 std::vector<uint32_t> monitor_enter_dex_pcs;
986 verifier::MethodVerifier::FindLocksAtDexPc(m, stack_visitor->GetDexPc(), monitor_enter_dex_pcs);
987 if (monitor_enter_dex_pcs.empty()) {
988 return;
989 }
990
Elliott Hughes80537bb2013-01-04 16:37:26 -0800991 for (size_t i = 0; i < monitor_enter_dex_pcs.size(); ++i) {
992 // The verifier works in terms of the dex pcs of the monitor-enter instructions.
993 // We want the registers used by those instructions (so we can read the values out of them).
994 uint32_t dex_pc = monitor_enter_dex_pcs[i];
995 uint16_t monitor_enter_instruction = code_item->insns_[dex_pc];
996
997 // Quick sanity check.
998 if ((monitor_enter_instruction & 0xff) != Instruction::MONITOR_ENTER) {
999 LOG(FATAL) << "expected monitor-enter @" << dex_pc << "; was "
1000 << reinterpret_cast<void*>(monitor_enter_instruction);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001001 }
1002
Elliott Hughes80537bb2013-01-04 16:37:26 -08001003 uint16_t monitor_register = ((monitor_enter_instruction >> 8) & 0xff);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001004 mirror::Object* o = reinterpret_cast<mirror::Object*>(stack_visitor->GetVReg(m, monitor_register,
1005 kReferenceVReg));
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001006 callback(o, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001007 }
1008}
1009
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001010bool Monitor::IsValidLockWord(LockWord lock_word) {
1011 switch (lock_word.GetState()) {
1012 case LockWord::kUnlocked:
1013 // Nothing to check.
1014 return true;
1015 case LockWord::kThinLocked:
1016 // Basic sanity check of owner.
1017 return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
1018 case LockWord::kFatLocked: {
1019 // Check the monitor appears in the monitor list.
1020 Monitor* mon = lock_word.FatLockMonitor();
1021 MonitorList* list = Runtime::Current()->GetMonitorList();
1022 MutexLock mu(Thread::Current(), list->monitor_list_lock_);
1023 for (Monitor* list_mon : list->list_) {
1024 if (mon == list_mon) {
1025 return true; // Found our monitor.
1026 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001027 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001028 return false; // Fail - unowned monitor in an object.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001029 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001030 case LockWord::kHashCode:
1031 return true;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001032 default:
1033 LOG(FATAL) << "Unreachable";
1034 return false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001035 }
1036}
1037
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001038bool Monitor::IsLocked() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1039 MutexLock mu(Thread::Current(), monitor_lock_);
1040 return owner_ != nullptr;
1041}
1042
Ian Rogersef7d42f2014-01-06 12:55:46 -08001043void Monitor::TranslateLocation(mirror::ArtMethod* method, uint32_t dex_pc,
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001044 const char** source_file, uint32_t* line_number) const {
jeffhao33dc7712011-11-09 17:54:24 -08001045 // If method is null, location is unknown
1046 if (method == NULL) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001047 *source_file = "";
1048 *line_number = 0;
jeffhao33dc7712011-11-09 17:54:24 -08001049 return;
1050 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001051 MethodHelper mh(method);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001052 *source_file = mh.GetDeclaringClassSourceFile();
1053 if (*source_file == NULL) {
1054 *source_file = "";
Elliott Hughes12c51e32012-01-17 20:25:05 -08001055 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001056 *line_number = mh.GetLineNumFromDexPC(dex_pc);
1057}
1058
1059uint32_t Monitor::GetOwnerThreadId() {
1060 MutexLock mu(Thread::Current(), monitor_lock_);
1061 Thread* owner = owner_;
1062 if (owner != NULL) {
1063 return owner->GetThreadId();
1064 } else {
1065 return ThreadList::kInvalidThreadId;
1066 }
jeffhao33dc7712011-11-09 17:54:24 -08001067}
1068
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001069MonitorList::MonitorList()
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001070 : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock", kMonitorListLock),
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001071 monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001072}
1073
1074MonitorList::~MonitorList() {
Ian Rogers50b35e22012-10-04 10:09:15 -07001075 MutexLock mu(Thread::Current(), monitor_list_lock_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001076 STLDeleteElements(&list_);
1077}
1078
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001079void MonitorList::DisallowNewMonitors() {
Ian Rogers50b35e22012-10-04 10:09:15 -07001080 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001081 allow_new_monitors_ = false;
1082}
1083
1084void MonitorList::AllowNewMonitors() {
1085 Thread* self = Thread::Current();
1086 MutexLock mu(self, monitor_list_lock_);
1087 allow_new_monitors_ = true;
1088 monitor_add_condition_.Broadcast(self);
1089}
1090
1091void MonitorList::Add(Monitor* m) {
1092 Thread* self = Thread::Current();
1093 MutexLock mu(self, monitor_list_lock_);
1094 while (UNLIKELY(!allow_new_monitors_)) {
1095 monitor_add_condition_.WaitHoldingLocks(self);
1096 }
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001097 list_.push_front(m);
1098}
1099
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08001100void MonitorList::SweepMonitorList(IsMarkedCallback* callback, void* arg) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001101 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001102 for (auto it = list_.begin(); it != list_.end(); ) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001103 Monitor* m = *it;
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001104 // Disable the read barrier in GetObject() as this is called by GC.
1105 mirror::Object* obj = m->GetObject<kWithoutReadBarrier>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001106 // The object of a monitor can be null if we have deflated it.
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08001107 mirror::Object* new_obj = obj != nullptr ? callback(obj, arg) : nullptr;
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001108 if (new_obj == nullptr) {
1109 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001110 << obj;
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001111 delete m;
1112 it = list_.erase(it);
1113 } else {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001114 m->SetObject(new_obj);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001115 ++it;
1116 }
1117 }
1118}
1119
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001120static mirror::Object* MonitorDeflateCallback(mirror::Object* object, void* arg)
1121 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1122 if (Monitor::Deflate(reinterpret_cast<Thread*>(arg), object)) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001123 DCHECK_NE(object->GetLockWord(true).GetState(), LockWord::kFatLocked);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001124 // If we deflated, return nullptr so that the monitor gets removed from the array.
1125 return nullptr;
1126 }
1127 return object; // Monitor was not deflated.
1128}
1129
1130void MonitorList::DeflateMonitors() {
1131 Thread* self = Thread::Current();
1132 Locks::mutator_lock_->AssertExclusiveHeld(self);
1133 SweepMonitorList(MonitorDeflateCallback, reinterpret_cast<Thread*>(self));
1134}
1135
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001136MonitorInfo::MonitorInfo(mirror::Object* obj) : owner_(NULL), entry_count_(0) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001137 DCHECK(obj != nullptr);
1138 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001139 switch (lock_word.GetState()) {
1140 case LockWord::kUnlocked:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001141 // Fall-through.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001142 case LockWord::kForwardingAddress:
1143 // Fall-through.
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001144 case LockWord::kHashCode:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001145 break;
1146 case LockWord::kThinLocked:
1147 owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
1148 entry_count_ = 1 + lock_word.ThinLockCount();
1149 // Thin locks have no waiters.
1150 break;
1151 case LockWord::kFatLocked: {
1152 Monitor* mon = lock_word.FatLockMonitor();
1153 owner_ = mon->owner_;
1154 entry_count_ = 1 + mon->lock_count_;
Ian Rogersdd7624d2014-03-14 17:43:00 -07001155 for (Thread* waiter = mon->wait_set_; waiter != NULL; waiter = waiter->GetWaitNext()) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001156 waiters_.push_back(waiter);
1157 }
1158 break;
Elliott Hughesf327e072013-01-09 16:01:26 -08001159 }
1160 }
1161}
1162
Elliott Hughes5f791332011-09-15 17:45:30 -07001163} // namespace art