blob: da481e41710625ca21d8105e394f915418c4664a [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),
Andreas Gampe74240812014-04-17 10:35:09 -070093 monitor_id_(MonitorPool::ComputeMonitorId(this, self)) {
94#ifdef __LP64__
95 DCHECK(false) << "Should not be reached in 64b";
96 next_free_ = nullptr;
97#endif
98 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
99 // with the owner unlocking the thin-lock.
100 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
101 // The identity hash code is set for the life time of the monitor.
102}
103
104Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code,
105 MonitorId id)
106 : monitor_lock_("a monitor lock", kMonitorLock),
107 monitor_contenders_("monitor contenders", monitor_lock_),
108 num_waiters_(0),
109 owner_(owner),
110 lock_count_(0),
111 obj_(obj),
112 wait_set_(NULL),
113 hash_code_(hash_code),
114 locking_method_(NULL),
115 locking_dex_pc_(0),
116 monitor_id_(id) {
117#ifdef __LP64__
118 next_free_ = nullptr;
119#endif
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700120 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
121 // with the owner unlocking the thin-lock.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800122 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700123 // The identity hash code is set for the life time of the monitor.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700124}
125
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700126int32_t Monitor::GetHashCode() {
127 while (!HasHashCode()) {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700128 if (hash_code_.CompareExchangeWeakRelaxed(0, mirror::Object::GenerateIdentityHashCode())) {
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700129 break;
130 }
131 }
132 DCHECK(HasHashCode());
Ian Rogers3e5cf302014-05-20 16:40:37 -0700133 return hash_code_.LoadRelaxed();
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700134}
135
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700136bool Monitor::Install(Thread* self) {
137 MutexLock mu(self, monitor_lock_); // Uncontended mutex acquisition as monitor isn't yet public.
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700138 CHECK(owner_ == nullptr || owner_ == self || owner_->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700139 // Propagate the lock state.
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700140 LockWord lw(GetObject()->GetLockWord(false));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700141 switch (lw.GetState()) {
142 case LockWord::kThinLocked: {
143 CHECK_EQ(owner_->GetThreadId(), lw.ThinLockOwner());
144 lock_count_ = lw.ThinLockCount();
145 break;
146 }
147 case LockWord::kHashCode: {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700148 CHECK_EQ(hash_code_.LoadRelaxed(), static_cast<int32_t>(lw.GetHashCode()));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700149 break;
150 }
151 case LockWord::kFatLocked: {
152 // The owner_ is suspended but another thread beat us to install a monitor.
153 return false;
154 }
155 case LockWord::kUnlocked: {
156 LOG(FATAL) << "Inflating unlocked lock word";
157 break;
158 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700159 default: {
160 LOG(FATAL) << "Invalid monitor state " << lw.GetState();
161 return false;
162 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700163 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700164 LockWord fat(this);
165 // Publish the updated lock word, which may race with other threads.
Ian Rogers228602f2014-07-10 02:07:54 -0700166 bool success = GetObject()->CasLockWordWeakSequentiallyConsistent(lw, fat);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700167 // Lock profiling.
Mathieu Chartier9728f912013-10-30 09:45:13 -0700168 if (success && owner_ != nullptr && lock_profiling_threshold_ != 0) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700169 locking_method_ = owner_->GetCurrentMethod(&locking_dex_pc_);
170 }
171 return success;
Elliott Hughes5f791332011-09-15 17:45:30 -0700172}
173
174Monitor::~Monitor() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700175 // Deflated monitors have a null object.
Elliott Hughes5f791332011-09-15 17:45:30 -0700176}
177
178/*
179 * Links a thread into a monitor's wait set. The monitor lock must be
180 * held by the caller of this routine.
181 */
182void Monitor::AppendToWaitSet(Thread* thread) {
183 DCHECK(owner_ == Thread::Current());
184 DCHECK(thread != NULL);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700185 DCHECK(thread->GetWaitNext() == nullptr) << thread->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700186 if (wait_set_ == NULL) {
187 wait_set_ = thread;
188 return;
189 }
190
191 // push_back.
192 Thread* t = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700193 while (t->GetWaitNext() != nullptr) {
194 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700195 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700196 t->SetWaitNext(thread);
Elliott Hughes5f791332011-09-15 17:45:30 -0700197}
198
199/*
200 * Unlinks a thread from a monitor's wait set. The monitor lock must
201 * be held by the caller of this routine.
202 */
203void Monitor::RemoveFromWaitSet(Thread *thread) {
204 DCHECK(owner_ == Thread::Current());
205 DCHECK(thread != NULL);
206 if (wait_set_ == NULL) {
207 return;
208 }
209 if (wait_set_ == thread) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700210 wait_set_ = thread->GetWaitNext();
211 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700212 return;
213 }
214
215 Thread* t = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700216 while (t->GetWaitNext() != NULL) {
217 if (t->GetWaitNext() == thread) {
218 t->SetWaitNext(thread->GetWaitNext());
219 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700220 return;
221 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700222 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700223 }
224}
225
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700226void Monitor::SetObject(mirror::Object* object) {
227 obj_ = object;
228}
229
Elliott Hughes5f791332011-09-15 17:45:30 -0700230void Monitor::Lock(Thread* self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700231 MutexLock mu(self, monitor_lock_);
232 while (true) {
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700233 if (owner_ == nullptr) { // Unowned.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700234 owner_ = self;
235 CHECK_EQ(lock_count_, 0);
236 // When debugging, save the current monitor holder for future
237 // acquisition failures to use in sampled logging.
238 if (lock_profiling_threshold_ != 0) {
239 locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
240 }
241 return;
242 } else if (owner_ == self) { // Recursive.
243 lock_count_++;
244 return;
245 }
246 // Contended.
247 const bool log_contention = (lock_profiling_threshold_ != 0);
248 uint64_t wait_start_ms = log_contention ? 0 : MilliTime();
Ian Rogersef7d42f2014-01-06 12:55:46 -0800249 mirror::ArtMethod* owners_method = locking_method_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700250 uint32_t owners_dex_pc = locking_dex_pc_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700251 // Do this before releasing the lock so that we don't get deflated.
252 ++num_waiters_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700253 monitor_lock_.Unlock(self); // Let go of locks in order.
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700254 self->SetMonitorEnterObject(GetObject());
Elliott Hughes5f791332011-09-15 17:45:30 -0700255 {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700256 ScopedThreadStateChange tsc(self, kBlocked); // Change to blocked and give up mutator_lock_.
257 MutexLock mu2(self, monitor_lock_); // Reacquire monitor_lock_ without mutator_lock_ for Wait.
258 if (owner_ != NULL) { // Did the owner_ give the lock up?
259 monitor_contenders_.Wait(self); // Still contended so wait.
260 // Woken from contention.
261 if (log_contention) {
262 uint64_t wait_ms = MilliTime() - wait_start_ms;
263 uint32_t sample_percent;
264 if (wait_ms >= lock_profiling_threshold_) {
265 sample_percent = 100;
266 } else {
267 sample_percent = 100 * wait_ms / lock_profiling_threshold_;
268 }
269 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
270 const char* owners_filename;
271 uint32_t owners_line_number;
272 TranslateLocation(owners_method, owners_dex_pc, &owners_filename, &owners_line_number);
273 LogContentionEvent(self, wait_ms, sample_percent, owners_filename, owners_line_number);
274 }
275 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700276 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700277 }
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700278 self->SetMonitorEnterObject(nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700279 monitor_lock_.Lock(self); // Reacquire locks in order.
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700280 --num_waiters_;
Elliott Hughesfc861622011-10-17 17:57:47 -0700281 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700282}
283
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800284static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
285 __attribute__((format(printf, 1, 2)));
286
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700287static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700288 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800289 va_list args;
290 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800291 Thread* self = Thread::Current();
292 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
293 self->ThrowNewExceptionV(throw_location, "Ljava/lang/IllegalMonitorStateException;", fmt, args);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700294 if (!Runtime::Current()->IsStarted() || VLOG_IS_ON(monitor)) {
Brian Carlstrom64277f32012-03-26 23:53:34 -0700295 std::ostringstream ss;
Ian Rogers62d6c772013-02-27 08:32:07 -0800296 self->Dump(ss);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700297 LOG(Runtime::Current()->IsStarted() ? INFO : ERROR)
298 << self->GetException(NULL)->Dump() << "\n" << ss.str();
Brian Carlstrom64277f32012-03-26 23:53:34 -0700299 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800300 va_end(args);
301}
302
Elliott Hughesd4237412012-02-21 11:24:45 -0800303static std::string ThreadToString(Thread* thread) {
304 if (thread == NULL) {
305 return "NULL";
306 }
307 std::ostringstream oss;
308 // TODO: alternatively, we could just return the thread's name.
309 oss << *thread;
310 return oss.str();
311}
312
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800313void Monitor::FailedUnlock(mirror::Object* o, Thread* expected_owner, Thread* found_owner,
Elliott Hughesffb465f2012-03-01 18:46:05 -0800314 Monitor* monitor) {
315 Thread* current_owner = NULL;
316 std::string current_owner_string;
317 std::string expected_owner_string;
318 std::string found_owner_string;
319 {
320 // TODO: isn't this too late to prevent threads from disappearing?
321 // Acquire thread list lock so threads won't disappear from under us.
Ian Rogers50b35e22012-10-04 10:09:15 -0700322 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Elliott Hughesffb465f2012-03-01 18:46:05 -0800323 // Re-read owner now that we hold lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700324 current_owner = (monitor != NULL) ? monitor->GetOwner() : NULL;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800325 // Get short descriptions of the threads involved.
326 current_owner_string = ThreadToString(current_owner);
327 expected_owner_string = ThreadToString(expected_owner);
328 found_owner_string = ThreadToString(found_owner);
329 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800330 if (current_owner == NULL) {
331 if (found_owner == NULL) {
332 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
333 " on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800334 PrettyTypeOf(o).c_str(),
335 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800336 } else {
337 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800338 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
339 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800340 found_owner_string.c_str(),
341 PrettyTypeOf(o).c_str(),
342 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800343 }
344 } else {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800345 if (found_owner == NULL) {
346 // Race: originally there was no owner, there is now
347 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
348 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800349 current_owner_string.c_str(),
350 PrettyTypeOf(o).c_str(),
351 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800352 } else {
353 if (found_owner != current_owner) {
354 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800355 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
356 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800357 found_owner_string.c_str(),
358 current_owner_string.c_str(),
359 PrettyTypeOf(o).c_str(),
360 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800361 } else {
362 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
363 " on thread '%s",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800364 current_owner_string.c_str(),
365 PrettyTypeOf(o).c_str(),
366 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800367 }
368 }
369 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700370}
371
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700372bool Monitor::Unlock(Thread* self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700373 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700374 MutexLock mu(self, monitor_lock_);
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800375 Thread* owner = owner_;
376 if (owner == self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700377 // We own the monitor, so nobody else can be in here.
378 if (lock_count_ == 0) {
379 owner_ = NULL;
jeffhao33dc7712011-11-09 17:54:24 -0800380 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700381 locking_dex_pc_ = 0;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700382 // Wake a contender.
383 monitor_contenders_.Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700384 } else {
385 --lock_count_;
386 }
387 } else {
388 // We don't own this, so we're not allowed to unlock it.
389 // The JNI spec says that we should throw IllegalMonitorStateException
390 // in this case.
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700391 FailedUnlock(GetObject(), self, owner, this);
Elliott Hughes5f791332011-09-15 17:45:30 -0700392 return false;
393 }
394 return true;
395}
396
Elliott Hughes5f791332011-09-15 17:45:30 -0700397/*
398 * Wait on a monitor until timeout, interrupt, or notification. Used for
399 * Object.wait() and (somewhat indirectly) Thread.sleep() and Thread.join().
400 *
401 * If another thread calls Thread.interrupt(), we throw InterruptedException
402 * and return immediately if one of the following are true:
403 * - blocked in wait(), wait(long), or wait(long, int) methods of Object
404 * - blocked in join(), join(long), or join(long, int) methods of Thread
405 * - blocked in sleep(long), or sleep(long, int) methods of Thread
406 * Otherwise, we set the "interrupted" flag.
407 *
408 * Checks to make sure that "ns" is in the range 0-999999
409 * (i.e. fractions of a millisecond) and throws the appropriate
410 * exception if it isn't.
411 *
412 * The spec allows "spurious wakeups", and recommends that all code using
413 * Object.wait() do so in a loop. This appears to derive from concerns
414 * about pthread_cond_wait() on multiprocessor systems. Some commentary
415 * on the web casts doubt on whether these can/should occur.
416 *
417 * Since we're allowed to wake up "early", we clamp extremely long durations
418 * to return at the end of the 32-bit time epoch.
419 */
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800420void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
421 bool interruptShouldThrow, ThreadState why) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700422 DCHECK(self != NULL);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800423 DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
Elliott Hughes5f791332011-09-15 17:45:30 -0700424
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700425 monitor_lock_.Lock(self);
426
Elliott Hughes5f791332011-09-15 17:45:30 -0700427 // Make sure that we hold the lock.
428 if (owner_ != self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700429 monitor_lock_.Unlock(self);
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700430 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700431 return;
432 }
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800433
Elliott Hughesdf42c482013-01-09 12:49:02 -0800434 // We need to turn a zero-length timed wait into a regular wait because
435 // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
436 if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
437 why = kWaiting;
438 }
439
Elliott Hughes5f791332011-09-15 17:45:30 -0700440 // Enforce the timeout range.
441 if (ms < 0 || ns < 0 || ns > 999999) {
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700442 monitor_lock_.Unlock(self);
Ian Rogers62d6c772013-02-27 08:32:07 -0800443 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
444 self->ThrowNewExceptionF(throw_location, "Ljava/lang/IllegalArgumentException;",
Ian Rogersef7d42f2014-01-06 12:55:46 -0800445 "timeout arguments out of range: ms=%" PRId64 " ns=%d", ms, ns);
Elliott Hughes5f791332011-09-15 17:45:30 -0700446 return;
447 }
448
Elliott Hughes5f791332011-09-15 17:45:30 -0700449 /*
450 * Add ourselves to the set of threads waiting on this monitor, and
451 * release our hold. We need to let it go even if we're a few levels
452 * deep in a recursive lock, and we need to restore that later.
453 *
454 * We append to the wait set ahead of clearing the count and owner
455 * fields so the subroutine can check that the calling thread owns
456 * the monitor. Aside from that, the order of member updates is
457 * not order sensitive as we hold the pthread mutex.
458 */
459 AppendToWaitSet(self);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700460 ++num_waiters_;
Ian Rogers0399dde2012-06-06 17:09:28 -0700461 int prev_lock_count = lock_count_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700462 lock_count_ = 0;
463 owner_ = NULL;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800464 mirror::ArtMethod* saved_method = locking_method_;
jeffhao33dc7712011-11-09 17:54:24 -0800465 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700466 uintptr_t saved_dex_pc = locking_dex_pc_;
467 locking_dex_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700468
469 /*
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800470 * Update thread state. If the GC wakes up, it'll ignore us, knowing
Elliott Hughes5f791332011-09-15 17:45:30 -0700471 * that we won't touch any references in this state, and we'll check
472 * our suspend mode before we transition out.
473 */
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800474 self->TransitionFromRunnableToSuspended(why);
Elliott Hughes5f791332011-09-15 17:45:30 -0700475
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800476 bool was_interrupted = false;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700477 {
478 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700479 MutexLock mu(self, *self->GetWaitMutex());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700480
481 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
482 // non-NULL a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
483 // up.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700484 DCHECK(self->GetWaitMonitor() == nullptr);
485 self->SetWaitMonitor(this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700486
487 // Release the monitor lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700488 monitor_contenders_.Signal(self);
489 monitor_lock_.Unlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700490
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800491 // Handle the case where the thread was interrupted before we called wait().
Ian Rogersdd7624d2014-03-14 17:43:00 -0700492 if (self->IsInterruptedLocked()) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800493 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700494 } else {
495 // Wait for a notification or a timeout to occur.
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800496 if (why == kWaiting) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700497 self->GetWaitConditionVariable()->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700498 } else {
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800499 DCHECK(why == kTimedWaiting || why == kSleeping) << why;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700500 self->GetWaitConditionVariable()->TimedWait(self, ms, ns);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700501 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700502 if (self->IsInterruptedLocked()) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800503 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700504 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700505 self->SetInterruptedLocked(false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700506 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700507 }
508
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700509 // Set self->status back to kRunnable, and self-suspend if needed.
510 self->TransitionFromSuspendedToRunnable();
Elliott Hughes5f791332011-09-15 17:45:30 -0700511
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800512 {
513 // We reset the thread's wait_monitor_ field after transitioning back to runnable so
514 // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
515 // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
516 // are waiting on "null".)
Ian Rogersdd7624d2014-03-14 17:43:00 -0700517 MutexLock mu(self, *self->GetWaitMutex());
518 DCHECK(self->GetWaitMonitor() != nullptr);
519 self->SetWaitMonitor(nullptr);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800520 }
521
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700522 // Re-acquire the monitor and lock.
Elliott Hughes5f791332011-09-15 17:45:30 -0700523 Lock(self);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700524 monitor_lock_.Lock(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700525 self->GetWaitMutex()->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700526
Elliott Hughes5f791332011-09-15 17:45:30 -0700527 /*
528 * We remove our thread from wait set after restoring the count
529 * and owner fields so the subroutine can check that the calling
530 * thread owns the monitor. Aside from that, the order of member
531 * updates is not order sensitive as we hold the pthread mutex.
532 */
533 owner_ = self;
Ian Rogers0399dde2012-06-06 17:09:28 -0700534 lock_count_ = prev_lock_count;
535 locking_method_ = saved_method;
536 locking_dex_pc_ = saved_dex_pc;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700537 --num_waiters_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700538 RemoveFromWaitSet(self);
539
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700540 monitor_lock_.Unlock(self);
541
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800542 if (was_interrupted) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700543 /*
544 * We were interrupted while waiting, or somebody interrupted an
545 * un-interruptible thread earlier and we're bailing out immediately.
546 *
547 * The doc sayeth: "The interrupted status of the current thread is
548 * cleared when this exception is thrown."
549 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700550 {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700551 MutexLock mu(self, *self->GetWaitMutex());
552 self->SetInterruptedLocked(false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700553 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700554 if (interruptShouldThrow) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800555 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
556 self->ThrowNewException(throw_location, "Ljava/lang/InterruptedException;", NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700557 }
558 }
559}
560
561void Monitor::Notify(Thread* self) {
562 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700563 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700564 // Make sure that we hold the lock.
565 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800566 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700567 return;
568 }
569 // Signal the first waiting thread in the wait set.
570 while (wait_set_ != NULL) {
571 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700572 wait_set_ = thread->GetWaitNext();
573 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700574
575 // Check to see if the thread is still waiting.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700576 MutexLock mu(self, *thread->GetWaitMutex());
577 if (thread->GetWaitMonitor() != nullptr) {
578 thread->GetWaitConditionVariable()->Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700579 return;
580 }
581 }
582}
583
584void Monitor::NotifyAll(Thread* self) {
585 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700586 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700587 // Make sure that we hold the lock.
588 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800589 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700590 return;
591 }
592 // Signal all threads in the wait set.
593 while (wait_set_ != NULL) {
594 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700595 wait_set_ = thread->GetWaitNext();
596 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700597 thread->Notify();
598 }
599}
600
Mathieu Chartier590fee92013-09-13 13:46:47 -0700601bool Monitor::Deflate(Thread* self, mirror::Object* obj) {
602 DCHECK(obj != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700603 // Don't need volatile since we only deflate with mutators suspended.
604 LockWord lw(obj->GetLockWord(false));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700605 // If the lock isn't an inflated monitor, then we don't need to deflate anything.
606 if (lw.GetState() == LockWord::kFatLocked) {
607 Monitor* monitor = lw.FatLockMonitor();
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700608 DCHECK(monitor != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700609 MutexLock mu(self, monitor->monitor_lock_);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700610 // Can't deflate if we have anybody waiting on the CV.
611 if (monitor->num_waiters_ > 0) {
612 return false;
613 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700614 Thread* owner = monitor->owner_;
615 if (owner != nullptr) {
616 // Can't deflate if we are locked and have a hash code.
617 if (monitor->HasHashCode()) {
618 return false;
619 }
620 // Can't deflate if our lock count is too high.
621 if (monitor->lock_count_ > LockWord::kThinLockMaxCount) {
622 return false;
623 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700624 // Deflate to a thin lock.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700625 obj->SetLockWord(LockWord::FromThinLockId(owner->GetThreadId(), monitor->lock_count_), false);
626 VLOG(monitor) << "Deflated " << obj << " to thin lock " << owner->GetTid() << " / "
627 << monitor->lock_count_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700628 } else if (monitor->HasHashCode()) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700629 obj->SetLockWord(LockWord::FromHashCode(monitor->GetHashCode()), false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700630 VLOG(monitor) << "Deflated " << obj << " to hash monitor " << monitor->GetHashCode();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700631 } else {
632 // No lock and no hash, just put an empty lock word inside the object.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700633 obj->SetLockWord(LockWord(), false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700634 VLOG(monitor) << "Deflated" << obj << " to empty lock word";
Mathieu Chartier590fee92013-09-13 13:46:47 -0700635 }
636 // The monitor is deflated, mark the object as nullptr so that we know to delete it during the
637 // next GC.
638 monitor->obj_ = nullptr;
639 }
640 return true;
641}
642
Elliott Hughes5f791332011-09-15 17:45:30 -0700643/*
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700644 * Changes the shape of a monitor from thin to fat, preserving the internal lock state. The calling
645 * thread must own the lock or the owner must be suspended. There's a race with other threads
646 * inflating the lock and so the caller should read the monitor following the call.
Elliott Hughes5f791332011-09-15 17:45:30 -0700647 */
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700648void Monitor::Inflate(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code) {
Andreas Gampe74240812014-04-17 10:35:09 -0700649 DCHECK(self != nullptr);
650 DCHECK(obj != nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700651 // Allocate and acquire a new monitor.
Andreas Gampe74240812014-04-17 10:35:09 -0700652 Monitor* m = MonitorPool::CreateMonitor(self, owner, obj, hash_code);
653 DCHECK(m != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700654 if (m->Install(self)) {
Haifeng Li86ab7912014-05-16 10:47:59 +0800655 if (owner != nullptr) {
656 VLOG(monitor) << "monitor: thread" << owner->GetThreadId()
Andreas Gampe74240812014-04-17 10:35:09 -0700657 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800658 } else {
659 VLOG(monitor) << "monitor: Inflate with hashcode " << hash_code
Andreas Gampe74240812014-04-17 10:35:09 -0700660 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800661 }
Andreas Gampe74240812014-04-17 10:35:09 -0700662 Runtime::Current()->GetMonitorList()->Add(m);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700663 CHECK_EQ(obj->GetLockWord(true).GetState(), LockWord::kFatLocked);
Andreas Gampe74240812014-04-17 10:35:09 -0700664 } else {
665 MonitorPool::ReleaseMonitor(self, m);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700666 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700667}
668
Mathieu Chartier0cd81352014-05-22 16:48:55 -0700669void Monitor::InflateThinLocked(Thread* self, Handle<mirror::Object> obj, LockWord lock_word,
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700670 uint32_t hash_code) {
671 DCHECK_EQ(lock_word.GetState(), LockWord::kThinLocked);
672 uint32_t owner_thread_id = lock_word.ThinLockOwner();
673 if (owner_thread_id == self->GetThreadId()) {
674 // We own the monitor, we can easily inflate it.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700675 Inflate(self, self, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700676 } else {
677 ThreadList* thread_list = Runtime::Current()->GetThreadList();
678 // Suspend the owner, inflate. First change to blocked and give up mutator_lock_.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700679 self->SetMonitorEnterObject(obj.Get());
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700680 bool timed_out;
681 Thread* owner;
682 {
683 ScopedThreadStateChange tsc(self, kBlocked);
684 owner = thread_list->SuspendThreadByThreadId(owner_thread_id, false, &timed_out);
685 }
686 if (owner != nullptr) {
687 // We succeeded in suspending the thread, check the lock's status didn't change.
688 lock_word = obj->GetLockWord(true);
689 if (lock_word.GetState() == LockWord::kThinLocked &&
690 lock_word.ThinLockOwner() == owner_thread_id) {
691 // Go ahead and inflate the lock.
692 Inflate(self, owner, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700693 }
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700694 thread_list->Resume(owner, false);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700695 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700696 self->SetMonitorEnterObject(nullptr);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700697 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700698}
699
Ian Rogers719d1a32014-03-06 12:13:39 -0800700// Fool annotalysis into thinking that the lock on obj is acquired.
701static mirror::Object* FakeLock(mirror::Object* obj)
702 EXCLUSIVE_LOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
703 return obj;
704}
705
706// Fool annotalysis into thinking that the lock on obj is release.
707static mirror::Object* FakeUnlock(mirror::Object* obj)
708 UNLOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
709 return obj;
710}
711
Mathieu Chartiere7e8a5f2014-02-14 16:59:41 -0800712mirror::Object* Monitor::MonitorEnter(Thread* self, mirror::Object* obj) {
Elliott Hughes4681c802011-09-25 18:04:37 -0700713 DCHECK(self != NULL);
714 DCHECK(obj != NULL);
Ian Rogers719d1a32014-03-06 12:13:39 -0800715 obj = FakeLock(obj);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700716 uint32_t thread_id = self->GetThreadId();
717 size_t contention_count = 0;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700718 StackHandleScope<1> hs(self);
719 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700720 while (true) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700721 LockWord lock_word = h_obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700722 switch (lock_word.GetState()) {
723 case LockWord::kUnlocked: {
724 LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0));
Ian Rogers228602f2014-07-10 02:07:54 -0700725 if (h_obj->CasLockWordWeakSequentiallyConsistent(lock_word, thin_locked)) {
Hans Boehm30359612014-05-21 17:46:23 -0700726 // CasLockWord enforces more than the acquire ordering we need here.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700727 return h_obj.Get(); // Success!
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700728 }
729 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -0700730 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700731 case LockWord::kThinLocked: {
732 uint32_t owner_thread_id = lock_word.ThinLockOwner();
733 if (owner_thread_id == thread_id) {
734 // We own the lock, increase the recursion count.
735 uint32_t new_count = lock_word.ThinLockCount() + 1;
736 if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
737 LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700738 h_obj->SetLockWord(thin_locked, true);
739 return h_obj.Get(); // Success!
Elliott Hughes5f791332011-09-15 17:45:30 -0700740 } else {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700741 // We'd overflow the recursion count, so inflate the monitor.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700742 InflateThinLocked(self, h_obj, lock_word, 0);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700743 }
744 } else {
745 // Contention.
746 contention_count++;
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700747 Runtime* runtime = Runtime::Current();
748 if (contention_count <= runtime->GetMaxSpinsBeforeThinkLockInflation()) {
Mathieu Chartier251755c2014-07-15 18:10:25 -0700749 // TODO: Consider switch thread state to kBlocked when we are yielding.
750 // Use sched_yield instead of NanoSleep since NanoSleep can wait much longer than the
751 // parameter you pass in. This can cause thread suspension to take excessively long
752 // make long pauses. See b/16307460.
753 sched_yield();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700754 } else {
755 contention_count = 0;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700756 InflateThinLocked(self, h_obj, lock_word, 0);
Elliott Hughes5f791332011-09-15 17:45:30 -0700757 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700758 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700759 continue; // Start from the beginning.
Elliott Hughes5f791332011-09-15 17:45:30 -0700760 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700761 case LockWord::kFatLocked: {
762 Monitor* mon = lock_word.FatLockMonitor();
763 mon->Lock(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700764 return h_obj.Get(); // Success!
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700765 }
Ian Rogers719d1a32014-03-06 12:13:39 -0800766 case LockWord::kHashCode:
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700767 // Inflate with the existing hashcode.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700768 Inflate(self, nullptr, h_obj.Get(), lock_word.GetHashCode());
Ian Rogers719d1a32014-03-06 12:13:39 -0800769 continue; // Start from the beginning.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700770 default: {
771 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700772 return h_obj.Get();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700773 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700774 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700775 }
776}
777
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800778bool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700779 DCHECK(self != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700780 DCHECK(obj != NULL);
Ian Rogers719d1a32014-03-06 12:13:39 -0800781 obj = FakeUnlock(obj);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700782 LockWord lock_word = obj->GetLockWord(true);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700783 StackHandleScope<1> hs(self);
784 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700785 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700786 case LockWord::kHashCode:
787 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700788 case LockWord::kUnlocked:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700789 FailedUnlock(h_obj.Get(), self, nullptr, nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700790 return false; // Failure.
791 case LockWord::kThinLocked: {
792 uint32_t thread_id = self->GetThreadId();
793 uint32_t owner_thread_id = lock_word.ThinLockOwner();
794 if (owner_thread_id != thread_id) {
795 // TODO: there's a race here with the owner dying while we unlock.
796 Thread* owner =
797 Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700798 FailedUnlock(h_obj.Get(), self, owner, nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700799 return false; // Failure.
800 } else {
801 // We own the lock, decrease the recursion count.
802 if (lock_word.ThinLockCount() != 0) {
803 uint32_t new_count = lock_word.ThinLockCount() - 1;
804 LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700805 h_obj->SetLockWord(thin_locked, true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700806 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700807 h_obj->SetLockWord(LockWord(), true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700808 }
809 return true; // Success!
810 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700811 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700812 case LockWord::kFatLocked: {
813 Monitor* mon = lock_word.FatLockMonitor();
814 return mon->Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700815 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700816 default: {
817 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700818 return false;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700819 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700820 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700821}
822
823/*
824 * Object.wait(). Also called for class init.
825 */
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800826void Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800827 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700828 DCHECK(self != nullptr);
829 DCHECK(obj != nullptr);
830 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700831 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700832 case LockWord::kHashCode:
833 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700834 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800835 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700836 return; // Failure.
837 case LockWord::kThinLocked: {
838 uint32_t thread_id = self->GetThreadId();
839 uint32_t owner_thread_id = lock_word.ThinLockOwner();
840 if (owner_thread_id != thread_id) {
841 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
842 return; // Failure.
843 } else {
844 // We own the lock, inflate to enqueue ourself on the Monitor.
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700845 Inflate(self, self, obj, 0);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700846 lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700847 }
848 break;
Elliott Hughes5f791332011-09-15 17:45:30 -0700849 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700850 case LockWord::kFatLocked:
851 break; // Already set for a wait.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700852 default: {
853 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
854 return;
855 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700856 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700857 Monitor* mon = lock_word.FatLockMonitor();
858 mon->Wait(self, ms, ns, interruptShouldThrow, why);
Elliott Hughes5f791332011-09-15 17:45:30 -0700859}
860
Ian Rogers13c479e2013-10-11 07:59:01 -0700861void Monitor::DoNotify(Thread* self, mirror::Object* obj, bool notify_all) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700862 DCHECK(self != nullptr);
863 DCHECK(obj != nullptr);
864 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700865 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700866 case LockWord::kHashCode:
867 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700868 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800869 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700870 return; // Failure.
871 case LockWord::kThinLocked: {
872 uint32_t thread_id = self->GetThreadId();
873 uint32_t owner_thread_id = lock_word.ThinLockOwner();
874 if (owner_thread_id != thread_id) {
875 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
876 return; // Failure.
877 } else {
878 // We own the lock but there's no Monitor and therefore no waiters.
879 return; // Success.
880 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700881 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700882 case LockWord::kFatLocked: {
883 Monitor* mon = lock_word.FatLockMonitor();
884 if (notify_all) {
885 mon->NotifyAll(self);
886 } else {
887 mon->Notify(self);
888 }
889 return; // Success.
890 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700891 default: {
892 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
893 return;
894 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700895 }
896}
897
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700898uint32_t Monitor::GetLockOwnerThreadId(mirror::Object* obj) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700899 DCHECK(obj != nullptr);
900 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700901 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700902 case LockWord::kHashCode:
903 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700904 case LockWord::kUnlocked:
905 return ThreadList::kInvalidThreadId;
906 case LockWord::kThinLocked:
907 return lock_word.ThinLockOwner();
908 case LockWord::kFatLocked: {
909 Monitor* mon = lock_word.FatLockMonitor();
910 return mon->GetOwnerThreadId();
Elliott Hughes5f791332011-09-15 17:45:30 -0700911 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700912 default: {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700913 LOG(FATAL) << "Unreachable";
914 return ThreadList::kInvalidThreadId;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700915 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700916 }
917}
918
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700919void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
Ian Rogersd803bc72014-04-01 15:33:03 -0700920 // Determine the wait message and object we're waiting or blocked upon.
921 mirror::Object* pretty_object = nullptr;
922 const char* wait_message = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700923 uint32_t lock_owner = ThreadList::kInvalidThreadId;
Ian Rogersd803bc72014-04-01 15:33:03 -0700924 ThreadState state = thread->GetState();
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800925 if (state == kWaiting || state == kTimedWaiting || state == kSleeping) {
Ian Rogersd803bc72014-04-01 15:33:03 -0700926 wait_message = (state == kSleeping) ? " - sleeping on " : " - waiting on ";
927 Thread* self = Thread::Current();
928 MutexLock mu(self, *thread->GetWaitMutex());
929 Monitor* monitor = thread->GetWaitMonitor();
930 if (monitor != nullptr) {
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700931 pretty_object = monitor->GetObject();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700932 }
Elliott Hughes34e06962012-04-09 13:55:55 -0700933 } else if (state == kBlocked) {
Ian Rogersd803bc72014-04-01 15:33:03 -0700934 wait_message = " - waiting to lock ";
935 pretty_object = thread->GetMonitorEnterObject();
936 if (pretty_object != nullptr) {
937 lock_owner = pretty_object->GetLockOwnerThreadId();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700938 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700939 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700940
Ian Rogersd803bc72014-04-01 15:33:03 -0700941 if (wait_message != nullptr) {
942 if (pretty_object == nullptr) {
943 os << wait_message << "an unknown object";
944 } else {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700945 if ((pretty_object->GetLockWord(true).GetState() == LockWord::kThinLocked) &&
Ian Rogersd803bc72014-04-01 15:33:03 -0700946 Locks::mutator_lock_->IsExclusiveHeld(Thread::Current())) {
947 // Getting the identity hashcode here would result in lock inflation and suspension of the
948 // current thread, which isn't safe if this is the only runnable thread.
949 os << wait_message << StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)",
950 reinterpret_cast<intptr_t>(pretty_object),
951 PrettyTypeOf(pretty_object).c_str());
952 } else {
953 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
954 os << wait_message << StringPrintf("<0x%08x> (a %s)", pretty_object->IdentityHashCode(),
955 PrettyTypeOf(pretty_object).c_str());
956 }
957 }
958 // - waiting to lock <0x613f83d8> (a java.lang.Object) held by thread 5
959 if (lock_owner != ThreadList::kInvalidThreadId) {
960 os << " held by thread " << lock_owner;
961 }
962 os << "\n";
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700963 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700964}
965
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800966mirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800967 // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
968 // definition of contended that includes a monitor a thread is trying to enter...
Ian Rogersdd7624d2014-03-14 17:43:00 -0700969 mirror::Object* result = thread->GetMonitorEnterObject();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700970 if (result == NULL) {
971 // ...but also a monitor that the thread is waiting on.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700972 MutexLock mu(Thread::Current(), *thread->GetWaitMutex());
973 Monitor* monitor = thread->GetWaitMonitor();
Elliott Hughesf9501702013-01-11 11:22:27 -0800974 if (monitor != NULL) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700975 result = monitor->GetObject();
Elliott Hughesf9501702013-01-11 11:22:27 -0800976 }
977 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700978 return result;
Elliott Hughesf9501702013-01-11 11:22:27 -0800979}
980
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800981void Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
982 void* callback_context) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700983 mirror::ArtMethod* m = stack_visitor->GetMethod();
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700984 CHECK(m != NULL);
985
986 // Native methods are an easy special case.
987 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
988 if (m->IsNative()) {
989 if (m->IsSynchronized()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700990 mirror::Object* jni_this = stack_visitor->GetCurrentHandleScope()->GetReference(0);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800991 callback(jni_this, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700992 }
993 return;
994 }
995
jeffhao61f916c2012-10-25 17:48:51 -0700996 // Proxy methods should not be synchronized.
997 if (m->IsProxyMethod()) {
998 CHECK(!m->IsSynchronized());
999 return;
1000 }
1001
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001002 // <clinit> is another special case. The runtime holds the class lock while calling <clinit>.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001003 if (m->IsClassInitializer()) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001004 callback(m->GetDeclaringClass(), callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001005 // Fall through because there might be synchronization in the user code too.
1006 }
1007
1008 // Is there any reason to believe there's any synchronization in this method?
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001009 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07001010 CHECK(code_item != NULL) << PrettyMethod(m);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001011 if (code_item->tries_size_ == 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001012 return; // No "tries" implies no synchronization, so no held locks to report.
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001013 }
1014
Elliott Hughes80537bb2013-01-04 16:37:26 -08001015 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
1016 // the locks held in this stack frame.
1017 std::vector<uint32_t> monitor_enter_dex_pcs;
Ian Rogers46960fe2014-05-23 10:43:43 -07001018 verifier::MethodVerifier::FindLocksAtDexPc(m, stack_visitor->GetDexPc(), &monitor_enter_dex_pcs);
Elliott Hughes80537bb2013-01-04 16:37:26 -08001019 if (monitor_enter_dex_pcs.empty()) {
1020 return;
1021 }
1022
Elliott Hughes80537bb2013-01-04 16:37:26 -08001023 for (size_t i = 0; i < monitor_enter_dex_pcs.size(); ++i) {
1024 // The verifier works in terms of the dex pcs of the monitor-enter instructions.
1025 // We want the registers used by those instructions (so we can read the values out of them).
1026 uint32_t dex_pc = monitor_enter_dex_pcs[i];
1027 uint16_t monitor_enter_instruction = code_item->insns_[dex_pc];
1028
1029 // Quick sanity check.
1030 if ((monitor_enter_instruction & 0xff) != Instruction::MONITOR_ENTER) {
1031 LOG(FATAL) << "expected monitor-enter @" << dex_pc << "; was "
1032 << reinterpret_cast<void*>(monitor_enter_instruction);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001033 }
1034
Elliott Hughes80537bb2013-01-04 16:37:26 -08001035 uint16_t monitor_register = ((monitor_enter_instruction >> 8) & 0xff);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001036 mirror::Object* o = reinterpret_cast<mirror::Object*>(stack_visitor->GetVReg(m, monitor_register,
1037 kReferenceVReg));
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001038 callback(o, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001039 }
1040}
1041
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001042bool Monitor::IsValidLockWord(LockWord lock_word) {
1043 switch (lock_word.GetState()) {
1044 case LockWord::kUnlocked:
1045 // Nothing to check.
1046 return true;
1047 case LockWord::kThinLocked:
1048 // Basic sanity check of owner.
1049 return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
1050 case LockWord::kFatLocked: {
1051 // Check the monitor appears in the monitor list.
1052 Monitor* mon = lock_word.FatLockMonitor();
1053 MonitorList* list = Runtime::Current()->GetMonitorList();
1054 MutexLock mu(Thread::Current(), list->monitor_list_lock_);
1055 for (Monitor* list_mon : list->list_) {
1056 if (mon == list_mon) {
1057 return true; // Found our monitor.
1058 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001059 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001060 return false; // Fail - unowned monitor in an object.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001061 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001062 case LockWord::kHashCode:
1063 return true;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001064 default:
1065 LOG(FATAL) << "Unreachable";
1066 return false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001067 }
1068}
1069
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001070bool Monitor::IsLocked() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1071 MutexLock mu(Thread::Current(), monitor_lock_);
1072 return owner_ != nullptr;
1073}
1074
Ian Rogersef7d42f2014-01-06 12:55:46 -08001075void Monitor::TranslateLocation(mirror::ArtMethod* method, uint32_t dex_pc,
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001076 const char** source_file, uint32_t* line_number) const {
jeffhao33dc7712011-11-09 17:54:24 -08001077 // If method is null, location is unknown
1078 if (method == NULL) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001079 *source_file = "";
1080 *line_number = 0;
jeffhao33dc7712011-11-09 17:54:24 -08001081 return;
1082 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001083 *source_file = method->GetDeclaringClassSourceFile();
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001084 if (*source_file == NULL) {
1085 *source_file = "";
Elliott Hughes12c51e32012-01-17 20:25:05 -08001086 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001087 *line_number = method->GetLineNumFromDexPC(dex_pc);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001088}
1089
1090uint32_t Monitor::GetOwnerThreadId() {
1091 MutexLock mu(Thread::Current(), monitor_lock_);
1092 Thread* owner = owner_;
1093 if (owner != NULL) {
1094 return owner->GetThreadId();
1095 } else {
1096 return ThreadList::kInvalidThreadId;
1097 }
jeffhao33dc7712011-11-09 17:54:24 -08001098}
1099
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001100MonitorList::MonitorList()
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001101 : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock", kMonitorListLock),
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001102 monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001103}
1104
1105MonitorList::~MonitorList() {
Andreas Gampe74240812014-04-17 10:35:09 -07001106 Thread* self = Thread::Current();
1107 MutexLock mu(self, monitor_list_lock_);
1108 // Release all monitors to the pool.
1109 // TODO: Is it an invariant that *all* open monitors are in the list? Then we could
1110 // clear faster in the pool.
1111 MonitorPool::ReleaseMonitors(self, &list_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001112}
1113
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001114void MonitorList::DisallowNewMonitors() {
Ian Rogers50b35e22012-10-04 10:09:15 -07001115 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001116 allow_new_monitors_ = false;
1117}
1118
1119void MonitorList::AllowNewMonitors() {
1120 Thread* self = Thread::Current();
1121 MutexLock mu(self, monitor_list_lock_);
1122 allow_new_monitors_ = true;
1123 monitor_add_condition_.Broadcast(self);
1124}
1125
1126void MonitorList::Add(Monitor* m) {
1127 Thread* self = Thread::Current();
1128 MutexLock mu(self, monitor_list_lock_);
1129 while (UNLIKELY(!allow_new_monitors_)) {
1130 monitor_add_condition_.WaitHoldingLocks(self);
1131 }
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001132 list_.push_front(m);
1133}
1134
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08001135void MonitorList::SweepMonitorList(IsMarkedCallback* callback, void* arg) {
Andreas Gampe74240812014-04-17 10:35:09 -07001136 Thread* self = Thread::Current();
1137 MutexLock mu(self, monitor_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001138 for (auto it = list_.begin(); it != list_.end(); ) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001139 Monitor* m = *it;
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001140 // Disable the read barrier in GetObject() as this is called by GC.
1141 mirror::Object* obj = m->GetObject<kWithoutReadBarrier>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001142 // The object of a monitor can be null if we have deflated it.
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08001143 mirror::Object* new_obj = obj != nullptr ? callback(obj, arg) : nullptr;
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001144 if (new_obj == nullptr) {
1145 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001146 << obj;
Andreas Gampe74240812014-04-17 10:35:09 -07001147 MonitorPool::ReleaseMonitor(self, m);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001148 it = list_.erase(it);
1149 } else {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001150 m->SetObject(new_obj);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001151 ++it;
1152 }
1153 }
1154}
1155
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001156struct MonitorDeflateArgs {
1157 MonitorDeflateArgs() : self(Thread::Current()), deflate_count(0) {}
1158 Thread* const self;
1159 size_t deflate_count;
1160};
1161
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001162static mirror::Object* MonitorDeflateCallback(mirror::Object* object, void* arg)
1163 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001164 MonitorDeflateArgs* args = reinterpret_cast<MonitorDeflateArgs*>(arg);
1165 if (Monitor::Deflate(args->self, object)) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001166 DCHECK_NE(object->GetLockWord(true).GetState(), LockWord::kFatLocked);
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001167 ++args->deflate_count;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001168 // If we deflated, return nullptr so that the monitor gets removed from the array.
1169 return nullptr;
1170 }
1171 return object; // Monitor was not deflated.
1172}
1173
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001174size_t MonitorList::DeflateMonitors() {
1175 MonitorDeflateArgs args;
1176 Locks::mutator_lock_->AssertExclusiveHeld(args.self);
1177 SweepMonitorList(MonitorDeflateCallback, &args);
1178 return args.deflate_count;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001179}
1180
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001181MonitorInfo::MonitorInfo(mirror::Object* obj) : owner_(NULL), entry_count_(0) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001182 DCHECK(obj != nullptr);
1183 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001184 switch (lock_word.GetState()) {
1185 case LockWord::kUnlocked:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001186 // Fall-through.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001187 case LockWord::kForwardingAddress:
1188 // Fall-through.
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001189 case LockWord::kHashCode:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001190 break;
1191 case LockWord::kThinLocked:
1192 owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
1193 entry_count_ = 1 + lock_word.ThinLockCount();
1194 // Thin locks have no waiters.
1195 break;
1196 case LockWord::kFatLocked: {
1197 Monitor* mon = lock_word.FatLockMonitor();
1198 owner_ = mon->owner_;
1199 entry_count_ = 1 + mon->lock_count_;
Ian Rogersdd7624d2014-03-14 17:43:00 -07001200 for (Thread* waiter = mon->wait_set_; waiter != NULL; waiter = waiter->GetWaitNext()) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001201 waiters_.push_back(waiter);
1202 }
1203 break;
Elliott Hughesf327e072013-01-09 16:01:26 -08001204 }
1205 }
1206}
1207
Elliott Hughes5f791332011-09-15 17:45:30 -07001208} // namespace art