blob: b33b286f8b9d56ed3e17279a230a2fbb3de83c76 [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 Rogers00f7d0e2012-07-19 15:28:27 -070031#include "scoped_thread_state_change.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070032#include "thread.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070033#include "thread_list.h"
Elliott Hughes08fc03a2012-06-26 17:34:00 -070034#include "verifier/method_verifier.h"
Elliott Hughes044288f2012-06-25 14:46:39 -070035#include "well_known_classes.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070036
37namespace art {
38
39/*
Ian Rogersd9c4fc92013-10-01 19:45:43 -070040 * Every Object has a monitor associated with it, but not every Object is actually locked. Even
41 * the ones that are locked do not need a full-fledged monitor until a) there is actual contention
42 * or b) wait() is called on the Object.
Elliott Hughes5f791332011-09-15 17:45:30 -070043 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070044 * For Android, we have implemented a scheme similar to the one described in Bacon et al.'s
45 * "Thin locks: featherweight synchronization for Java" (ACM 1998). Things are even easier for us,
46 * though, because we have a full 32 bits to work with.
Elliott Hughes5f791332011-09-15 17:45:30 -070047 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070048 * The two states of an Object's lock are referred to as "thin" and "fat". A lock may transition
49 * from the "thin" state to the "fat" state and this transition is referred to as inflation. Once
50 * a lock has been inflated it remains in the "fat" state indefinitely.
Elliott Hughes5f791332011-09-15 17:45:30 -070051 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070052 * The lock value itself is stored in mirror::Object::monitor_ and the representation is described
53 * in the LockWord value type.
Elliott Hughes54e7df12011-09-16 11:47:04 -070054 *
Elliott Hughes5f791332011-09-15 17:45:30 -070055 * Monitors provide:
56 * - mutually exclusive access to resources
57 * - a way for multiple threads to wait for notification
58 *
59 * In effect, they fill the role of both mutexes and condition variables.
60 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070061 * Only one thread can own the monitor at any time. There may be several threads waiting on it
62 * (the wait call unlocks it). One or more waiting threads may be getting interrupted or notified
63 * at any given time.
Elliott Hughes5f791332011-09-15 17:45:30 -070064 */
Elliott Hughes54e7df12011-09-16 11:47:04 -070065
Elliott Hughesfc861622011-10-17 17:57:47 -070066bool (*Monitor::is_sensitive_thread_hook_)() = NULL;
Elliott Hughesfc861622011-10-17 17:57:47 -070067uint32_t Monitor::lock_profiling_threshold_ = 0;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070068
Elliott Hughesfc861622011-10-17 17:57:47 -070069bool Monitor::IsSensitiveThread() {
70 if (is_sensitive_thread_hook_ != NULL) {
71 return (*is_sensitive_thread_hook_)();
72 }
73 return false;
74}
75
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -080076void Monitor::Init(uint32_t lock_profiling_threshold, bool (*is_sensitive_thread_hook)()) {
Elliott Hughesfc861622011-10-17 17:57:47 -070077 lock_profiling_threshold_ = lock_profiling_threshold;
78 is_sensitive_thread_hook_ = is_sensitive_thread_hook;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070079}
80
Ian Rogersef7d42f2014-01-06 12:55:46 -080081Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code)
Ian Rogers00f7d0e2012-07-19 15:28:27 -070082 : monitor_lock_("a monitor lock", kMonitorLock),
Ian Rogersd9c4fc92013-10-01 19:45:43 -070083 monitor_contenders_("monitor contenders", monitor_lock_),
Mathieu Chartier46bc7782013-11-12 17:03:02 -080084 num_waiters_(0),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070085 owner_(owner),
Elliott Hughes5f791332011-09-15 17:45:30 -070086 lock_count_(0),
87 obj_(obj),
88 wait_set_(NULL),
Mathieu Chartierad2541a2013-10-25 10:05:23 -070089 hash_code_(hash_code),
jeffhao33dc7712011-11-09 17:54:24 -080090 locking_method_(NULL),
Ian Rogersef7d42f2014-01-06 12:55:46 -080091 locking_dex_pc_(0),
Andreas Gampe74240812014-04-17 10:35:09 -070092 monitor_id_(MonitorPool::ComputeMonitorId(this, self)) {
93#ifdef __LP64__
94 DCHECK(false) << "Should not be reached in 64b";
95 next_free_ = nullptr;
96#endif
97 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
98 // with the owner unlocking the thin-lock.
99 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
100 // The identity hash code is set for the life time of the monitor.
101}
102
103Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code,
104 MonitorId id)
105 : monitor_lock_("a monitor lock", kMonitorLock),
106 monitor_contenders_("monitor contenders", monitor_lock_),
107 num_waiters_(0),
108 owner_(owner),
109 lock_count_(0),
110 obj_(obj),
111 wait_set_(NULL),
112 hash_code_(hash_code),
113 locking_method_(NULL),
114 locking_dex_pc_(0),
115 monitor_id_(id) {
116#ifdef __LP64__
117 next_free_ = nullptr;
118#endif
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700119 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
120 // with the owner unlocking the thin-lock.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800121 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700122 // The identity hash code is set for the life time of the monitor.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700123}
124
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700125int32_t Monitor::GetHashCode() {
126 while (!HasHashCode()) {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700127 if (hash_code_.CompareExchangeWeakRelaxed(0, mirror::Object::GenerateIdentityHashCode())) {
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700128 break;
129 }
130 }
131 DCHECK(HasHashCode());
Ian Rogers3e5cf302014-05-20 16:40:37 -0700132 return hash_code_.LoadRelaxed();
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700133}
134
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700135bool Monitor::Install(Thread* self) {
136 MutexLock mu(self, monitor_lock_); // Uncontended mutex acquisition as monitor isn't yet public.
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700137 CHECK(owner_ == nullptr || owner_ == self || owner_->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700138 // Propagate the lock state.
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700139 LockWord lw(GetObject()->GetLockWord(false));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700140 switch (lw.GetState()) {
141 case LockWord::kThinLocked: {
142 CHECK_EQ(owner_->GetThreadId(), lw.ThinLockOwner());
143 lock_count_ = lw.ThinLockCount();
144 break;
145 }
146 case LockWord::kHashCode: {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700147 CHECK_EQ(hash_code_.LoadRelaxed(), static_cast<int32_t>(lw.GetHashCode()));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700148 break;
149 }
150 case LockWord::kFatLocked: {
151 // The owner_ is suspended but another thread beat us to install a monitor.
152 return false;
153 }
154 case LockWord::kUnlocked: {
155 LOG(FATAL) << "Inflating unlocked lock word";
156 break;
157 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700158 default: {
159 LOG(FATAL) << "Invalid monitor state " << lw.GetState();
160 return false;
161 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700162 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700163 LockWord fat(this);
164 // Publish the updated lock word, which may race with other threads.
Ian Rogers228602f2014-07-10 02:07:54 -0700165 bool success = GetObject()->CasLockWordWeakSequentiallyConsistent(lw, fat);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700166 // Lock profiling.
Mathieu Chartier9728f912013-10-30 09:45:13 -0700167 if (success && owner_ != nullptr && lock_profiling_threshold_ != 0) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700168 locking_method_ = owner_->GetCurrentMethod(&locking_dex_pc_);
169 }
170 return success;
Elliott Hughes5f791332011-09-15 17:45:30 -0700171}
172
173Monitor::~Monitor() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700174 // Deflated monitors have a null object.
Elliott Hughes5f791332011-09-15 17:45:30 -0700175}
176
177/*
178 * Links a thread into a monitor's wait set. The monitor lock must be
179 * held by the caller of this routine.
180 */
181void Monitor::AppendToWaitSet(Thread* thread) {
182 DCHECK(owner_ == Thread::Current());
183 DCHECK(thread != NULL);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700184 DCHECK(thread->GetWaitNext() == nullptr) << thread->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700185 if (wait_set_ == NULL) {
186 wait_set_ = thread;
187 return;
188 }
189
190 // push_back.
191 Thread* t = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700192 while (t->GetWaitNext() != nullptr) {
193 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700194 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700195 t->SetWaitNext(thread);
Elliott Hughes5f791332011-09-15 17:45:30 -0700196}
197
198/*
199 * Unlinks a thread from a monitor's wait set. The monitor lock must
200 * be held by the caller of this routine.
201 */
202void Monitor::RemoveFromWaitSet(Thread *thread) {
203 DCHECK(owner_ == Thread::Current());
204 DCHECK(thread != NULL);
205 if (wait_set_ == NULL) {
206 return;
207 }
208 if (wait_set_ == thread) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700209 wait_set_ = thread->GetWaitNext();
210 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700211 return;
212 }
213
214 Thread* t = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700215 while (t->GetWaitNext() != NULL) {
216 if (t->GetWaitNext() == thread) {
217 t->SetWaitNext(thread->GetWaitNext());
218 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700219 return;
220 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700221 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700222 }
223}
224
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700225void Monitor::SetObject(mirror::Object* object) {
226 obj_ = object;
227}
228
Elliott Hughes5f791332011-09-15 17:45:30 -0700229void Monitor::Lock(Thread* self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700230 MutexLock mu(self, monitor_lock_);
231 while (true) {
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700232 if (owner_ == nullptr) { // Unowned.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700233 owner_ = self;
234 CHECK_EQ(lock_count_, 0);
235 // When debugging, save the current monitor holder for future
236 // acquisition failures to use in sampled logging.
237 if (lock_profiling_threshold_ != 0) {
238 locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
239 }
240 return;
241 } else if (owner_ == self) { // Recursive.
242 lock_count_++;
243 return;
244 }
245 // Contended.
246 const bool log_contention = (lock_profiling_threshold_ != 0);
247 uint64_t wait_start_ms = log_contention ? 0 : MilliTime();
Ian Rogersef7d42f2014-01-06 12:55:46 -0800248 mirror::ArtMethod* owners_method = locking_method_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700249 uint32_t owners_dex_pc = locking_dex_pc_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700250 // Do this before releasing the lock so that we don't get deflated.
251 ++num_waiters_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700252 monitor_lock_.Unlock(self); // Let go of locks in order.
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700253 self->SetMonitorEnterObject(GetObject());
Elliott Hughes5f791332011-09-15 17:45:30 -0700254 {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700255 ScopedThreadStateChange tsc(self, kBlocked); // Change to blocked and give up mutator_lock_.
256 MutexLock mu2(self, monitor_lock_); // Reacquire monitor_lock_ without mutator_lock_ for Wait.
257 if (owner_ != NULL) { // Did the owner_ give the lock up?
258 monitor_contenders_.Wait(self); // Still contended so wait.
259 // Woken from contention.
260 if (log_contention) {
261 uint64_t wait_ms = MilliTime() - wait_start_ms;
262 uint32_t sample_percent;
263 if (wait_ms >= lock_profiling_threshold_) {
264 sample_percent = 100;
265 } else {
266 sample_percent = 100 * wait_ms / lock_profiling_threshold_;
267 }
268 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
269 const char* owners_filename;
270 uint32_t owners_line_number;
271 TranslateLocation(owners_method, owners_dex_pc, &owners_filename, &owners_line_number);
272 LogContentionEvent(self, wait_ms, sample_percent, owners_filename, owners_line_number);
273 }
274 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700275 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700276 }
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700277 self->SetMonitorEnterObject(nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700278 monitor_lock_.Lock(self); // Reacquire locks in order.
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700279 --num_waiters_;
Elliott Hughesfc861622011-10-17 17:57:47 -0700280 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700281}
282
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800283static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
284 __attribute__((format(printf, 1, 2)));
285
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700286static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700287 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800288 va_list args;
289 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800290 Thread* self = Thread::Current();
291 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
292 self->ThrowNewExceptionV(throw_location, "Ljava/lang/IllegalMonitorStateException;", fmt, args);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700293 if (!Runtime::Current()->IsStarted() || VLOG_IS_ON(monitor)) {
Brian Carlstrom64277f32012-03-26 23:53:34 -0700294 std::ostringstream ss;
Ian Rogers62d6c772013-02-27 08:32:07 -0800295 self->Dump(ss);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700296 LOG(Runtime::Current()->IsStarted() ? INFO : ERROR)
297 << self->GetException(NULL)->Dump() << "\n" << ss.str();
Brian Carlstrom64277f32012-03-26 23:53:34 -0700298 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800299 va_end(args);
300}
301
Elliott Hughesd4237412012-02-21 11:24:45 -0800302static std::string ThreadToString(Thread* thread) {
303 if (thread == NULL) {
304 return "NULL";
305 }
306 std::ostringstream oss;
307 // TODO: alternatively, we could just return the thread's name.
308 oss << *thread;
309 return oss.str();
310}
311
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800312void Monitor::FailedUnlock(mirror::Object* o, Thread* expected_owner, Thread* found_owner,
Elliott Hughesffb465f2012-03-01 18:46:05 -0800313 Monitor* monitor) {
314 Thread* current_owner = NULL;
315 std::string current_owner_string;
316 std::string expected_owner_string;
317 std::string found_owner_string;
318 {
319 // TODO: isn't this too late to prevent threads from disappearing?
320 // Acquire thread list lock so threads won't disappear from under us.
Ian Rogers50b35e22012-10-04 10:09:15 -0700321 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Elliott Hughesffb465f2012-03-01 18:46:05 -0800322 // Re-read owner now that we hold lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700323 current_owner = (monitor != NULL) ? monitor->GetOwner() : NULL;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800324 // Get short descriptions of the threads involved.
325 current_owner_string = ThreadToString(current_owner);
326 expected_owner_string = ThreadToString(expected_owner);
327 found_owner_string = ThreadToString(found_owner);
328 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800329 if (current_owner == NULL) {
330 if (found_owner == NULL) {
331 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
332 " on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800333 PrettyTypeOf(o).c_str(),
334 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800335 } else {
336 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800337 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
338 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800339 found_owner_string.c_str(),
340 PrettyTypeOf(o).c_str(),
341 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800342 }
343 } else {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800344 if (found_owner == NULL) {
345 // Race: originally there was no owner, there is now
346 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
347 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800348 current_owner_string.c_str(),
349 PrettyTypeOf(o).c_str(),
350 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800351 } else {
352 if (found_owner != current_owner) {
353 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800354 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
355 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800356 found_owner_string.c_str(),
357 current_owner_string.c_str(),
358 PrettyTypeOf(o).c_str(),
359 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800360 } else {
361 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
362 " on thread '%s",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800363 current_owner_string.c_str(),
364 PrettyTypeOf(o).c_str(),
365 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800366 }
367 }
368 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700369}
370
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700371bool Monitor::Unlock(Thread* self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700372 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700373 MutexLock mu(self, monitor_lock_);
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800374 Thread* owner = owner_;
375 if (owner == self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700376 // We own the monitor, so nobody else can be in here.
377 if (lock_count_ == 0) {
378 owner_ = NULL;
jeffhao33dc7712011-11-09 17:54:24 -0800379 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700380 locking_dex_pc_ = 0;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700381 // Wake a contender.
382 monitor_contenders_.Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700383 } else {
384 --lock_count_;
385 }
386 } else {
387 // We don't own this, so we're not allowed to unlock it.
388 // The JNI spec says that we should throw IllegalMonitorStateException
389 // in this case.
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700390 FailedUnlock(GetObject(), self, owner, this);
Elliott Hughes5f791332011-09-15 17:45:30 -0700391 return false;
392 }
393 return true;
394}
395
Elliott Hughes5f791332011-09-15 17:45:30 -0700396/*
397 * Wait on a monitor until timeout, interrupt, or notification. Used for
398 * Object.wait() and (somewhat indirectly) Thread.sleep() and Thread.join().
399 *
400 * If another thread calls Thread.interrupt(), we throw InterruptedException
401 * and return immediately if one of the following are true:
402 * - blocked in wait(), wait(long), or wait(long, int) methods of Object
403 * - blocked in join(), join(long), or join(long, int) methods of Thread
404 * - blocked in sleep(long), or sleep(long, int) methods of Thread
405 * Otherwise, we set the "interrupted" flag.
406 *
407 * Checks to make sure that "ns" is in the range 0-999999
408 * (i.e. fractions of a millisecond) and throws the appropriate
409 * exception if it isn't.
410 *
411 * The spec allows "spurious wakeups", and recommends that all code using
412 * Object.wait() do so in a loop. This appears to derive from concerns
413 * about pthread_cond_wait() on multiprocessor systems. Some commentary
414 * on the web casts doubt on whether these can/should occur.
415 *
416 * Since we're allowed to wake up "early", we clamp extremely long durations
417 * to return at the end of the 32-bit time epoch.
418 */
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800419void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
420 bool interruptShouldThrow, ThreadState why) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700421 DCHECK(self != NULL);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800422 DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
Elliott Hughes5f791332011-09-15 17:45:30 -0700423
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700424 monitor_lock_.Lock(self);
425
Elliott Hughes5f791332011-09-15 17:45:30 -0700426 // Make sure that we hold the lock.
427 if (owner_ != self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700428 monitor_lock_.Unlock(self);
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700429 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700430 return;
431 }
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800432
Elliott Hughesdf42c482013-01-09 12:49:02 -0800433 // We need to turn a zero-length timed wait into a regular wait because
434 // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
435 if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
436 why = kWaiting;
437 }
438
Elliott Hughes5f791332011-09-15 17:45:30 -0700439 // Enforce the timeout range.
440 if (ms < 0 || ns < 0 || ns > 999999) {
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700441 monitor_lock_.Unlock(self);
Ian Rogers62d6c772013-02-27 08:32:07 -0800442 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
443 self->ThrowNewExceptionF(throw_location, "Ljava/lang/IllegalArgumentException;",
Ian Rogersef7d42f2014-01-06 12:55:46 -0800444 "timeout arguments out of range: ms=%" PRId64 " ns=%d", ms, ns);
Elliott Hughes5f791332011-09-15 17:45:30 -0700445 return;
446 }
447
Elliott Hughes5f791332011-09-15 17:45:30 -0700448 /*
449 * Add ourselves to the set of threads waiting on this monitor, and
450 * release our hold. We need to let it go even if we're a few levels
451 * deep in a recursive lock, and we need to restore that later.
452 *
453 * We append to the wait set ahead of clearing the count and owner
454 * fields so the subroutine can check that the calling thread owns
455 * the monitor. Aside from that, the order of member updates is
456 * not order sensitive as we hold the pthread mutex.
457 */
458 AppendToWaitSet(self);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700459 ++num_waiters_;
Ian Rogers0399dde2012-06-06 17:09:28 -0700460 int prev_lock_count = lock_count_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700461 lock_count_ = 0;
462 owner_ = NULL;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800463 mirror::ArtMethod* saved_method = locking_method_;
jeffhao33dc7712011-11-09 17:54:24 -0800464 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700465 uintptr_t saved_dex_pc = locking_dex_pc_;
466 locking_dex_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700467
468 /*
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800469 * Update thread state. If the GC wakes up, it'll ignore us, knowing
Elliott Hughes5f791332011-09-15 17:45:30 -0700470 * that we won't touch any references in this state, and we'll check
471 * our suspend mode before we transition out.
472 */
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800473 self->TransitionFromRunnableToSuspended(why);
Elliott Hughes5f791332011-09-15 17:45:30 -0700474
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800475 bool was_interrupted = false;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700476 {
477 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700478 MutexLock mu(self, *self->GetWaitMutex());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700479
480 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
481 // non-NULL a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
482 // up.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700483 DCHECK(self->GetWaitMonitor() == nullptr);
484 self->SetWaitMonitor(this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700485
486 // Release the monitor lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700487 monitor_contenders_.Signal(self);
488 monitor_lock_.Unlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700489
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800490 // Handle the case where the thread was interrupted before we called wait().
Ian Rogersdd7624d2014-03-14 17:43:00 -0700491 if (self->IsInterruptedLocked()) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800492 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700493 } else {
494 // Wait for a notification or a timeout to occur.
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800495 if (why == kWaiting) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700496 self->GetWaitConditionVariable()->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700497 } else {
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800498 DCHECK(why == kTimedWaiting || why == kSleeping) << why;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700499 self->GetWaitConditionVariable()->TimedWait(self, ms, ns);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700500 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700501 if (self->IsInterruptedLocked()) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800502 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700503 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700504 self->SetInterruptedLocked(false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700505 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700506 }
507
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700508 // Set self->status back to kRunnable, and self-suspend if needed.
509 self->TransitionFromSuspendedToRunnable();
Elliott Hughes5f791332011-09-15 17:45:30 -0700510
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800511 {
512 // We reset the thread's wait_monitor_ field after transitioning back to runnable so
513 // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
514 // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
515 // are waiting on "null".)
Ian Rogersdd7624d2014-03-14 17:43:00 -0700516 MutexLock mu(self, *self->GetWaitMutex());
517 DCHECK(self->GetWaitMonitor() != nullptr);
518 self->SetWaitMonitor(nullptr);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800519 }
520
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700521 // Re-acquire the monitor and lock.
Elliott Hughes5f791332011-09-15 17:45:30 -0700522 Lock(self);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700523 monitor_lock_.Lock(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700524 self->GetWaitMutex()->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700525
Elliott Hughes5f791332011-09-15 17:45:30 -0700526 /*
527 * We remove our thread from wait set after restoring the count
528 * and owner fields so the subroutine can check that the calling
529 * thread owns the monitor. Aside from that, the order of member
530 * updates is not order sensitive as we hold the pthread mutex.
531 */
532 owner_ = self;
Ian Rogers0399dde2012-06-06 17:09:28 -0700533 lock_count_ = prev_lock_count;
534 locking_method_ = saved_method;
535 locking_dex_pc_ = saved_dex_pc;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700536 --num_waiters_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700537 RemoveFromWaitSet(self);
538
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700539 monitor_lock_.Unlock(self);
540
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800541 if (was_interrupted) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700542 /*
543 * We were interrupted while waiting, or somebody interrupted an
544 * un-interruptible thread earlier and we're bailing out immediately.
545 *
546 * The doc sayeth: "The interrupted status of the current thread is
547 * cleared when this exception is thrown."
548 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700549 {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700550 MutexLock mu(self, *self->GetWaitMutex());
551 self->SetInterruptedLocked(false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700552 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700553 if (interruptShouldThrow) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800554 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
555 self->ThrowNewException(throw_location, "Ljava/lang/InterruptedException;", NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700556 }
557 }
558}
559
560void Monitor::Notify(Thread* self) {
561 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700562 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700563 // Make sure that we hold the lock.
564 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800565 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700566 return;
567 }
568 // Signal the first waiting thread in the wait set.
569 while (wait_set_ != NULL) {
570 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700571 wait_set_ = thread->GetWaitNext();
572 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700573
574 // Check to see if the thread is still waiting.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700575 MutexLock mu(self, *thread->GetWaitMutex());
576 if (thread->GetWaitMonitor() != nullptr) {
577 thread->GetWaitConditionVariable()->Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700578 return;
579 }
580 }
581}
582
583void Monitor::NotifyAll(Thread* self) {
584 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700585 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700586 // Make sure that we hold the lock.
587 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800588 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700589 return;
590 }
591 // Signal all threads in the wait set.
592 while (wait_set_ != NULL) {
593 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700594 wait_set_ = thread->GetWaitNext();
595 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700596 thread->Notify();
597 }
598}
599
Mathieu Chartier590fee92013-09-13 13:46:47 -0700600bool Monitor::Deflate(Thread* self, mirror::Object* obj) {
601 DCHECK(obj != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700602 // Don't need volatile since we only deflate with mutators suspended.
603 LockWord lw(obj->GetLockWord(false));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700604 // If the lock isn't an inflated monitor, then we don't need to deflate anything.
605 if (lw.GetState() == LockWord::kFatLocked) {
606 Monitor* monitor = lw.FatLockMonitor();
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700607 DCHECK(monitor != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700608 MutexLock mu(self, monitor->monitor_lock_);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700609 // Can't deflate if we have anybody waiting on the CV.
610 if (monitor->num_waiters_ > 0) {
611 return false;
612 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700613 Thread* owner = monitor->owner_;
614 if (owner != nullptr) {
615 // Can't deflate if we are locked and have a hash code.
616 if (monitor->HasHashCode()) {
617 return false;
618 }
619 // Can't deflate if our lock count is too high.
620 if (monitor->lock_count_ > LockWord::kThinLockMaxCount) {
621 return false;
622 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700623 // Deflate to a thin lock.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700624 obj->SetLockWord(LockWord::FromThinLockId(owner->GetThreadId(), monitor->lock_count_), false);
625 VLOG(monitor) << "Deflated " << obj << " to thin lock " << owner->GetTid() << " / "
626 << monitor->lock_count_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700627 } else if (monitor->HasHashCode()) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700628 obj->SetLockWord(LockWord::FromHashCode(monitor->GetHashCode()), false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700629 VLOG(monitor) << "Deflated " << obj << " to hash monitor " << monitor->GetHashCode();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700630 } else {
631 // No lock and no hash, just put an empty lock word inside the object.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700632 obj->SetLockWord(LockWord(), false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700633 VLOG(monitor) << "Deflated" << obj << " to empty lock word";
Mathieu Chartier590fee92013-09-13 13:46:47 -0700634 }
635 // The monitor is deflated, mark the object as nullptr so that we know to delete it during the
636 // next GC.
637 monitor->obj_ = nullptr;
638 }
639 return true;
640}
641
Elliott Hughes5f791332011-09-15 17:45:30 -0700642/*
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700643 * Changes the shape of a monitor from thin to fat, preserving the internal lock state. The calling
644 * thread must own the lock or the owner must be suspended. There's a race with other threads
645 * inflating the lock and so the caller should read the monitor following the call.
Elliott Hughes5f791332011-09-15 17:45:30 -0700646 */
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700647void Monitor::Inflate(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code) {
Andreas Gampe74240812014-04-17 10:35:09 -0700648 DCHECK(self != nullptr);
649 DCHECK(obj != nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700650 // Allocate and acquire a new monitor.
Andreas Gampe74240812014-04-17 10:35:09 -0700651 Monitor* m = MonitorPool::CreateMonitor(self, owner, obj, hash_code);
652 DCHECK(m != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700653 if (m->Install(self)) {
Haifeng Li86ab7912014-05-16 10:47:59 +0800654 if (owner != nullptr) {
655 VLOG(monitor) << "monitor: thread" << owner->GetThreadId()
Andreas Gampe74240812014-04-17 10:35:09 -0700656 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800657 } else {
658 VLOG(monitor) << "monitor: Inflate with hashcode " << hash_code
Andreas Gampe74240812014-04-17 10:35:09 -0700659 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800660 }
Andreas Gampe74240812014-04-17 10:35:09 -0700661 Runtime::Current()->GetMonitorList()->Add(m);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700662 CHECK_EQ(obj->GetLockWord(true).GetState(), LockWord::kFatLocked);
Andreas Gampe74240812014-04-17 10:35:09 -0700663 } else {
664 MonitorPool::ReleaseMonitor(self, m);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700665 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700666}
667
Mathieu Chartier0cd81352014-05-22 16:48:55 -0700668void Monitor::InflateThinLocked(Thread* self, Handle<mirror::Object> obj, LockWord lock_word,
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700669 uint32_t hash_code) {
670 DCHECK_EQ(lock_word.GetState(), LockWord::kThinLocked);
671 uint32_t owner_thread_id = lock_word.ThinLockOwner();
672 if (owner_thread_id == self->GetThreadId()) {
673 // We own the monitor, we can easily inflate it.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700674 Inflate(self, self, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700675 } else {
676 ThreadList* thread_list = Runtime::Current()->GetThreadList();
677 // Suspend the owner, inflate. First change to blocked and give up mutator_lock_.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700678 self->SetMonitorEnterObject(obj.Get());
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700679 bool timed_out;
680 Thread* owner;
681 {
682 ScopedThreadStateChange tsc(self, kBlocked);
Ian Rogersf3d874c2014-07-17 18:52:42 -0700683 // Take suspend thread lock to avoid races with threads trying to suspend this one.
684 MutexLock mu(self, *Locks::thread_list_suspend_thread_lock_);
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700685 owner = thread_list->SuspendThreadByThreadId(owner_thread_id, false, &timed_out);
686 }
687 if (owner != nullptr) {
688 // We succeeded in suspending the thread, check the lock's status didn't change.
689 lock_word = obj->GetLockWord(true);
690 if (lock_word.GetState() == LockWord::kThinLocked &&
691 lock_word.ThinLockOwner() == owner_thread_id) {
692 // Go ahead and inflate the lock.
693 Inflate(self, owner, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700694 }
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700695 thread_list->Resume(owner, false);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700696 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700697 self->SetMonitorEnterObject(nullptr);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700698 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700699}
700
Ian Rogers719d1a32014-03-06 12:13:39 -0800701// Fool annotalysis into thinking that the lock on obj is acquired.
702static mirror::Object* FakeLock(mirror::Object* obj)
703 EXCLUSIVE_LOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
704 return obj;
705}
706
707// Fool annotalysis into thinking that the lock on obj is release.
708static mirror::Object* FakeUnlock(mirror::Object* obj)
709 UNLOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
710 return obj;
711}
712
Mathieu Chartiere7e8a5f2014-02-14 16:59:41 -0800713mirror::Object* Monitor::MonitorEnter(Thread* self, mirror::Object* obj) {
Elliott Hughes4681c802011-09-25 18:04:37 -0700714 DCHECK(self != NULL);
715 DCHECK(obj != NULL);
Ian Rogers719d1a32014-03-06 12:13:39 -0800716 obj = FakeLock(obj);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700717 uint32_t thread_id = self->GetThreadId();
718 size_t contention_count = 0;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700719 StackHandleScope<1> hs(self);
720 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700721 while (true) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700722 LockWord lock_word = h_obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700723 switch (lock_word.GetState()) {
724 case LockWord::kUnlocked: {
725 LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0));
Ian Rogers228602f2014-07-10 02:07:54 -0700726 if (h_obj->CasLockWordWeakSequentiallyConsistent(lock_word, thin_locked)) {
Hans Boehm30359612014-05-21 17:46:23 -0700727 // CasLockWord enforces more than the acquire ordering we need here.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700728 return h_obj.Get(); // Success!
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700729 }
730 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -0700731 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700732 case LockWord::kThinLocked: {
733 uint32_t owner_thread_id = lock_word.ThinLockOwner();
734 if (owner_thread_id == thread_id) {
735 // We own the lock, increase the recursion count.
736 uint32_t new_count = lock_word.ThinLockCount() + 1;
737 if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
738 LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700739 h_obj->SetLockWord(thin_locked, true);
740 return h_obj.Get(); // Success!
Elliott Hughes5f791332011-09-15 17:45:30 -0700741 } else {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700742 // We'd overflow the recursion count, so inflate the monitor.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700743 InflateThinLocked(self, h_obj, lock_word, 0);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700744 }
745 } else {
746 // Contention.
747 contention_count++;
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700748 Runtime* runtime = Runtime::Current();
749 if (contention_count <= runtime->GetMaxSpinsBeforeThinkLockInflation()) {
Mathieu Chartier251755c2014-07-15 18:10:25 -0700750 // TODO: Consider switch thread state to kBlocked when we are yielding.
751 // Use sched_yield instead of NanoSleep since NanoSleep can wait much longer than the
752 // parameter you pass in. This can cause thread suspension to take excessively long
753 // make long pauses. See b/16307460.
754 sched_yield();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700755 } else {
756 contention_count = 0;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700757 InflateThinLocked(self, h_obj, lock_word, 0);
Elliott Hughes5f791332011-09-15 17:45:30 -0700758 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700759 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700760 continue; // Start from the beginning.
Elliott Hughes5f791332011-09-15 17:45:30 -0700761 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700762 case LockWord::kFatLocked: {
763 Monitor* mon = lock_word.FatLockMonitor();
764 mon->Lock(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700765 return h_obj.Get(); // Success!
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700766 }
Ian Rogers719d1a32014-03-06 12:13:39 -0800767 case LockWord::kHashCode:
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700768 // Inflate with the existing hashcode.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700769 Inflate(self, nullptr, h_obj.Get(), lock_word.GetHashCode());
Ian Rogers719d1a32014-03-06 12:13:39 -0800770 continue; // Start from the beginning.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700771 default: {
772 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700773 return h_obj.Get();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700774 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700775 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700776 }
777}
778
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800779bool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700780 DCHECK(self != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700781 DCHECK(obj != NULL);
Ian Rogers719d1a32014-03-06 12:13:39 -0800782 obj = FakeUnlock(obj);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700783 LockWord lock_word = obj->GetLockWord(true);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700784 StackHandleScope<1> hs(self);
785 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700786 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700787 case LockWord::kHashCode:
788 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700789 case LockWord::kUnlocked:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700790 FailedUnlock(h_obj.Get(), self, nullptr, nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700791 return false; // Failure.
792 case LockWord::kThinLocked: {
793 uint32_t thread_id = self->GetThreadId();
794 uint32_t owner_thread_id = lock_word.ThinLockOwner();
795 if (owner_thread_id != thread_id) {
796 // TODO: there's a race here with the owner dying while we unlock.
797 Thread* owner =
798 Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700799 FailedUnlock(h_obj.Get(), self, owner, nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700800 return false; // Failure.
801 } else {
802 // We own the lock, decrease the recursion count.
803 if (lock_word.ThinLockCount() != 0) {
804 uint32_t new_count = lock_word.ThinLockCount() - 1;
805 LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700806 h_obj->SetLockWord(thin_locked, true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700807 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700808 h_obj->SetLockWord(LockWord(), true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700809 }
810 return true; // Success!
811 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700812 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700813 case LockWord::kFatLocked: {
814 Monitor* mon = lock_word.FatLockMonitor();
815 return mon->Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700816 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700817 default: {
818 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700819 return false;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700820 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700821 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700822}
823
824/*
825 * Object.wait(). Also called for class init.
826 */
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800827void Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800828 bool interruptShouldThrow, ThreadState why) {
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 wait()");
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 wait()");
843 return; // Failure.
844 } else {
845 // We own the lock, inflate to enqueue ourself on the Monitor.
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700846 Inflate(self, self, obj, 0);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700847 lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700848 }
849 break;
Elliott Hughes5f791332011-09-15 17:45:30 -0700850 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700851 case LockWord::kFatLocked:
852 break; // Already set for a wait.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700853 default: {
854 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
855 return;
856 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700857 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700858 Monitor* mon = lock_word.FatLockMonitor();
859 mon->Wait(self, ms, ns, interruptShouldThrow, why);
Elliott Hughes5f791332011-09-15 17:45:30 -0700860}
861
Ian Rogers13c479e2013-10-11 07:59:01 -0700862void Monitor::DoNotify(Thread* self, mirror::Object* obj, bool notify_all) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700863 DCHECK(self != nullptr);
864 DCHECK(obj != nullptr);
865 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700866 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700867 case LockWord::kHashCode:
868 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700869 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800870 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700871 return; // Failure.
872 case LockWord::kThinLocked: {
873 uint32_t thread_id = self->GetThreadId();
874 uint32_t owner_thread_id = lock_word.ThinLockOwner();
875 if (owner_thread_id != thread_id) {
876 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
877 return; // Failure.
878 } else {
879 // We own the lock but there's no Monitor and therefore no waiters.
880 return; // Success.
881 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700882 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700883 case LockWord::kFatLocked: {
884 Monitor* mon = lock_word.FatLockMonitor();
885 if (notify_all) {
886 mon->NotifyAll(self);
887 } else {
888 mon->Notify(self);
889 }
890 return; // Success.
891 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700892 default: {
893 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
894 return;
895 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700896 }
897}
898
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700899uint32_t Monitor::GetLockOwnerThreadId(mirror::Object* obj) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700900 DCHECK(obj != nullptr);
901 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700902 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700903 case LockWord::kHashCode:
904 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700905 case LockWord::kUnlocked:
906 return ThreadList::kInvalidThreadId;
907 case LockWord::kThinLocked:
908 return lock_word.ThinLockOwner();
909 case LockWord::kFatLocked: {
910 Monitor* mon = lock_word.FatLockMonitor();
911 return mon->GetOwnerThreadId();
Elliott Hughes5f791332011-09-15 17:45:30 -0700912 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700913 default: {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700914 LOG(FATAL) << "Unreachable";
915 return ThreadList::kInvalidThreadId;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700916 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700917 }
918}
919
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700920void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
Ian Rogersd803bc72014-04-01 15:33:03 -0700921 // Determine the wait message and object we're waiting or blocked upon.
922 mirror::Object* pretty_object = nullptr;
923 const char* wait_message = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700924 uint32_t lock_owner = ThreadList::kInvalidThreadId;
Ian Rogersd803bc72014-04-01 15:33:03 -0700925 ThreadState state = thread->GetState();
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800926 if (state == kWaiting || state == kTimedWaiting || state == kSleeping) {
Ian Rogersd803bc72014-04-01 15:33:03 -0700927 wait_message = (state == kSleeping) ? " - sleeping on " : " - waiting on ";
928 Thread* self = Thread::Current();
929 MutexLock mu(self, *thread->GetWaitMutex());
930 Monitor* monitor = thread->GetWaitMonitor();
931 if (monitor != nullptr) {
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700932 pretty_object = monitor->GetObject();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700933 }
Elliott Hughes34e06962012-04-09 13:55:55 -0700934 } else if (state == kBlocked) {
Ian Rogersd803bc72014-04-01 15:33:03 -0700935 wait_message = " - waiting to lock ";
936 pretty_object = thread->GetMonitorEnterObject();
937 if (pretty_object != nullptr) {
938 lock_owner = pretty_object->GetLockOwnerThreadId();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700939 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700940 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700941
Ian Rogersd803bc72014-04-01 15:33:03 -0700942 if (wait_message != nullptr) {
943 if (pretty_object == nullptr) {
944 os << wait_message << "an unknown object";
945 } else {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700946 if ((pretty_object->GetLockWord(true).GetState() == LockWord::kThinLocked) &&
Ian Rogersd803bc72014-04-01 15:33:03 -0700947 Locks::mutator_lock_->IsExclusiveHeld(Thread::Current())) {
948 // Getting the identity hashcode here would result in lock inflation and suspension of the
949 // current thread, which isn't safe if this is the only runnable thread.
950 os << wait_message << StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)",
951 reinterpret_cast<intptr_t>(pretty_object),
952 PrettyTypeOf(pretty_object).c_str());
953 } else {
954 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
955 os << wait_message << StringPrintf("<0x%08x> (a %s)", pretty_object->IdentityHashCode(),
956 PrettyTypeOf(pretty_object).c_str());
957 }
958 }
959 // - waiting to lock <0x613f83d8> (a java.lang.Object) held by thread 5
960 if (lock_owner != ThreadList::kInvalidThreadId) {
961 os << " held by thread " << lock_owner;
962 }
963 os << "\n";
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700964 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700965}
966
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800967mirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800968 // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
969 // definition of contended that includes a monitor a thread is trying to enter...
Ian Rogersdd7624d2014-03-14 17:43:00 -0700970 mirror::Object* result = thread->GetMonitorEnterObject();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700971 if (result == NULL) {
972 // ...but also a monitor that the thread is waiting on.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700973 MutexLock mu(Thread::Current(), *thread->GetWaitMutex());
974 Monitor* monitor = thread->GetWaitMonitor();
Elliott Hughesf9501702013-01-11 11:22:27 -0800975 if (monitor != NULL) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700976 result = monitor->GetObject();
Elliott Hughesf9501702013-01-11 11:22:27 -0800977 }
978 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700979 return result;
Elliott Hughesf9501702013-01-11 11:22:27 -0800980}
981
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800982void Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
983 void* callback_context) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700984 mirror::ArtMethod* m = stack_visitor->GetMethod();
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700985 CHECK(m != NULL);
986
987 // Native methods are an easy special case.
988 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
989 if (m->IsNative()) {
990 if (m->IsSynchronized()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700991 mirror::Object* jni_this = stack_visitor->GetCurrentHandleScope()->GetReference(0);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800992 callback(jni_this, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700993 }
994 return;
995 }
996
jeffhao61f916c2012-10-25 17:48:51 -0700997 // Proxy methods should not be synchronized.
998 if (m->IsProxyMethod()) {
999 CHECK(!m->IsSynchronized());
1000 return;
1001 }
1002
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001003 // <clinit> is another special case. The runtime holds the class lock while calling <clinit>.
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001004 if (m->IsClassInitializer()) {
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001005 callback(m->GetDeclaringClass(), callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001006 // Fall through because there might be synchronization in the user code too.
1007 }
1008
1009 // Is there any reason to believe there's any synchronization in this method?
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001010 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07001011 CHECK(code_item != NULL) << PrettyMethod(m);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001012 if (code_item->tries_size_ == 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001013 return; // No "tries" implies no synchronization, so no held locks to report.
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001014 }
1015
Elliott Hughes80537bb2013-01-04 16:37:26 -08001016 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
1017 // the locks held in this stack frame.
1018 std::vector<uint32_t> monitor_enter_dex_pcs;
Ian Rogers46960fe2014-05-23 10:43:43 -07001019 verifier::MethodVerifier::FindLocksAtDexPc(m, stack_visitor->GetDexPc(), &monitor_enter_dex_pcs);
Elliott Hughes80537bb2013-01-04 16:37:26 -08001020 if (monitor_enter_dex_pcs.empty()) {
1021 return;
1022 }
1023
Elliott Hughes80537bb2013-01-04 16:37:26 -08001024 for (size_t i = 0; i < monitor_enter_dex_pcs.size(); ++i) {
1025 // The verifier works in terms of the dex pcs of the monitor-enter instructions.
1026 // We want the registers used by those instructions (so we can read the values out of them).
1027 uint32_t dex_pc = monitor_enter_dex_pcs[i];
1028 uint16_t monitor_enter_instruction = code_item->insns_[dex_pc];
1029
1030 // Quick sanity check.
1031 if ((monitor_enter_instruction & 0xff) != Instruction::MONITOR_ENTER) {
1032 LOG(FATAL) << "expected monitor-enter @" << dex_pc << "; was "
1033 << reinterpret_cast<void*>(monitor_enter_instruction);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001034 }
1035
Elliott Hughes80537bb2013-01-04 16:37:26 -08001036 uint16_t monitor_register = ((monitor_enter_instruction >> 8) & 0xff);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001037 mirror::Object* o = reinterpret_cast<mirror::Object*>(stack_visitor->GetVReg(m, monitor_register,
1038 kReferenceVReg));
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001039 callback(o, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001040 }
1041}
1042
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001043bool Monitor::IsValidLockWord(LockWord lock_word) {
1044 switch (lock_word.GetState()) {
1045 case LockWord::kUnlocked:
1046 // Nothing to check.
1047 return true;
1048 case LockWord::kThinLocked:
1049 // Basic sanity check of owner.
1050 return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
1051 case LockWord::kFatLocked: {
1052 // Check the monitor appears in the monitor list.
1053 Monitor* mon = lock_word.FatLockMonitor();
1054 MonitorList* list = Runtime::Current()->GetMonitorList();
1055 MutexLock mu(Thread::Current(), list->monitor_list_lock_);
1056 for (Monitor* list_mon : list->list_) {
1057 if (mon == list_mon) {
1058 return true; // Found our monitor.
1059 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001060 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001061 return false; // Fail - unowned monitor in an object.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001062 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001063 case LockWord::kHashCode:
1064 return true;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001065 default:
1066 LOG(FATAL) << "Unreachable";
1067 return false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001068 }
1069}
1070
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001071bool Monitor::IsLocked() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1072 MutexLock mu(Thread::Current(), monitor_lock_);
1073 return owner_ != nullptr;
1074}
1075
Ian Rogersef7d42f2014-01-06 12:55:46 -08001076void Monitor::TranslateLocation(mirror::ArtMethod* method, uint32_t dex_pc,
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001077 const char** source_file, uint32_t* line_number) const {
jeffhao33dc7712011-11-09 17:54:24 -08001078 // If method is null, location is unknown
1079 if (method == NULL) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001080 *source_file = "";
1081 *line_number = 0;
jeffhao33dc7712011-11-09 17:54:24 -08001082 return;
1083 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001084 *source_file = method->GetDeclaringClassSourceFile();
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001085 if (*source_file == NULL) {
1086 *source_file = "";
Elliott Hughes12c51e32012-01-17 20:25:05 -08001087 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001088 *line_number = method->GetLineNumFromDexPC(dex_pc);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001089}
1090
1091uint32_t Monitor::GetOwnerThreadId() {
1092 MutexLock mu(Thread::Current(), monitor_lock_);
1093 Thread* owner = owner_;
1094 if (owner != NULL) {
1095 return owner->GetThreadId();
1096 } else {
1097 return ThreadList::kInvalidThreadId;
1098 }
jeffhao33dc7712011-11-09 17:54:24 -08001099}
1100
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001101MonitorList::MonitorList()
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001102 : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock", kMonitorListLock),
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001103 monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001104}
1105
1106MonitorList::~MonitorList() {
Andreas Gampe74240812014-04-17 10:35:09 -07001107 Thread* self = Thread::Current();
1108 MutexLock mu(self, monitor_list_lock_);
1109 // Release all monitors to the pool.
1110 // TODO: Is it an invariant that *all* open monitors are in the list? Then we could
1111 // clear faster in the pool.
1112 MonitorPool::ReleaseMonitors(self, &list_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001113}
1114
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001115void MonitorList::DisallowNewMonitors() {
Ian Rogers50b35e22012-10-04 10:09:15 -07001116 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001117 allow_new_monitors_ = false;
1118}
1119
1120void MonitorList::AllowNewMonitors() {
1121 Thread* self = Thread::Current();
1122 MutexLock mu(self, monitor_list_lock_);
1123 allow_new_monitors_ = true;
1124 monitor_add_condition_.Broadcast(self);
1125}
1126
1127void MonitorList::Add(Monitor* m) {
1128 Thread* self = Thread::Current();
1129 MutexLock mu(self, monitor_list_lock_);
1130 while (UNLIKELY(!allow_new_monitors_)) {
1131 monitor_add_condition_.WaitHoldingLocks(self);
1132 }
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001133 list_.push_front(m);
1134}
1135
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08001136void MonitorList::SweepMonitorList(IsMarkedCallback* callback, void* arg) {
Andreas Gampe74240812014-04-17 10:35:09 -07001137 Thread* self = Thread::Current();
1138 MutexLock mu(self, monitor_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001139 for (auto it = list_.begin(); it != list_.end(); ) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001140 Monitor* m = *it;
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001141 // Disable the read barrier in GetObject() as this is called by GC.
1142 mirror::Object* obj = m->GetObject<kWithoutReadBarrier>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001143 // The object of a monitor can be null if we have deflated it.
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08001144 mirror::Object* new_obj = obj != nullptr ? callback(obj, arg) : nullptr;
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001145 if (new_obj == nullptr) {
1146 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001147 << obj;
Andreas Gampe74240812014-04-17 10:35:09 -07001148 MonitorPool::ReleaseMonitor(self, m);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001149 it = list_.erase(it);
1150 } else {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001151 m->SetObject(new_obj);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001152 ++it;
1153 }
1154 }
1155}
1156
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001157struct MonitorDeflateArgs {
1158 MonitorDeflateArgs() : self(Thread::Current()), deflate_count(0) {}
1159 Thread* const self;
1160 size_t deflate_count;
1161};
1162
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001163static mirror::Object* MonitorDeflateCallback(mirror::Object* object, void* arg)
1164 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001165 MonitorDeflateArgs* args = reinterpret_cast<MonitorDeflateArgs*>(arg);
1166 if (Monitor::Deflate(args->self, object)) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001167 DCHECK_NE(object->GetLockWord(true).GetState(), LockWord::kFatLocked);
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001168 ++args->deflate_count;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001169 // If we deflated, return nullptr so that the monitor gets removed from the array.
1170 return nullptr;
1171 }
1172 return object; // Monitor was not deflated.
1173}
1174
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001175size_t MonitorList::DeflateMonitors() {
1176 MonitorDeflateArgs args;
1177 Locks::mutator_lock_->AssertExclusiveHeld(args.self);
1178 SweepMonitorList(MonitorDeflateCallback, &args);
1179 return args.deflate_count;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001180}
1181
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001182MonitorInfo::MonitorInfo(mirror::Object* obj) : owner_(NULL), entry_count_(0) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001183 DCHECK(obj != nullptr);
1184 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001185 switch (lock_word.GetState()) {
1186 case LockWord::kUnlocked:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001187 // Fall-through.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001188 case LockWord::kForwardingAddress:
1189 // Fall-through.
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001190 case LockWord::kHashCode:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001191 break;
1192 case LockWord::kThinLocked:
1193 owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
1194 entry_count_ = 1 + lock_word.ThinLockCount();
1195 // Thin locks have no waiters.
1196 break;
1197 case LockWord::kFatLocked: {
1198 Monitor* mon = lock_word.FatLockMonitor();
1199 owner_ = mon->owner_;
1200 entry_count_ = 1 + mon->lock_count_;
Ian Rogersdd7624d2014-03-14 17:43:00 -07001201 for (Thread* waiter = mon->wait_set_; waiter != NULL; waiter = waiter->GetWaitNext()) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001202 waiters_.push_back(waiter);
1203 }
1204 break;
Elliott Hughesf327e072013-01-09 16:01:26 -08001205 }
1206 }
1207}
1208
Elliott Hughes5f791332011-09-15 17:45:30 -07001209} // namespace art