blob: 0cf077a4002bd11ee434c054ccf5408ee8d95f39 [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
Mathieu Chartierb9001ab2014-10-03 13:28:46 -070039static constexpr uint64_t kLongWaitMs = 100;
40
Elliott Hughes5f791332011-09-15 17:45:30 -070041/*
Ian Rogersd9c4fc92013-10-01 19:45:43 -070042 * Every Object has a monitor associated with it, but not every Object is actually locked. Even
43 * the ones that are locked do not need a full-fledged monitor until a) there is actual contention
44 * or b) wait() is called on the Object.
Elliott Hughes5f791332011-09-15 17:45:30 -070045 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070046 * For Android, we have implemented a scheme similar to the one described in Bacon et al.'s
47 * "Thin locks: featherweight synchronization for Java" (ACM 1998). Things are even easier for us,
48 * though, because we have a full 32 bits to work with.
Elliott Hughes5f791332011-09-15 17:45:30 -070049 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070050 * The two states of an Object's lock are referred to as "thin" and "fat". A lock may transition
51 * from the "thin" state to the "fat" state and this transition is referred to as inflation. Once
52 * a lock has been inflated it remains in the "fat" state indefinitely.
Elliott Hughes5f791332011-09-15 17:45:30 -070053 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070054 * The lock value itself is stored in mirror::Object::monitor_ and the representation is described
55 * in the LockWord value type.
Elliott Hughes54e7df12011-09-16 11:47:04 -070056 *
Elliott Hughes5f791332011-09-15 17:45:30 -070057 * Monitors provide:
58 * - mutually exclusive access to resources
59 * - a way for multiple threads to wait for notification
60 *
61 * In effect, they fill the role of both mutexes and condition variables.
62 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070063 * Only one thread can own the monitor at any time. There may be several threads waiting on it
64 * (the wait call unlocks it). One or more waiting threads may be getting interrupted or notified
65 * at any given time.
Elliott Hughes5f791332011-09-15 17:45:30 -070066 */
Elliott Hughes54e7df12011-09-16 11:47:04 -070067
Elliott Hughesfc861622011-10-17 17:57:47 -070068bool (*Monitor::is_sensitive_thread_hook_)() = NULL;
Elliott Hughesfc861622011-10-17 17:57:47 -070069uint32_t Monitor::lock_profiling_threshold_ = 0;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070070
Elliott Hughesfc861622011-10-17 17:57:47 -070071bool Monitor::IsSensitiveThread() {
72 if (is_sensitive_thread_hook_ != NULL) {
73 return (*is_sensitive_thread_hook_)();
74 }
75 return false;
76}
77
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -080078void Monitor::Init(uint32_t lock_profiling_threshold, bool (*is_sensitive_thread_hook)()) {
Elliott Hughesfc861622011-10-17 17:57:47 -070079 lock_profiling_threshold_ = lock_profiling_threshold;
80 is_sensitive_thread_hook_ = is_sensitive_thread_hook;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070081}
82
Ian Rogersef7d42f2014-01-06 12:55:46 -080083Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code)
Ian Rogers00f7d0e2012-07-19 15:28:27 -070084 : monitor_lock_("a monitor lock", kMonitorLock),
Ian Rogersd9c4fc92013-10-01 19:45:43 -070085 monitor_contenders_("monitor contenders", monitor_lock_),
Mathieu Chartier46bc7782013-11-12 17:03:02 -080086 num_waiters_(0),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070087 owner_(owner),
Elliott Hughes5f791332011-09-15 17:45:30 -070088 lock_count_(0),
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070089 obj_(GcRoot<mirror::Object>(obj)),
Elliott Hughes5f791332011-09-15 17:45:30 -070090 wait_set_(NULL),
Mathieu Chartierad2541a2013-10-25 10:05:23 -070091 hash_code_(hash_code),
jeffhao33dc7712011-11-09 17:54:24 -080092 locking_method_(NULL),
Ian Rogersef7d42f2014-01-06 12:55:46 -080093 locking_dex_pc_(0),
Andreas Gampe74240812014-04-17 10:35:09 -070094 monitor_id_(MonitorPool::ComputeMonitorId(this, self)) {
95#ifdef __LP64__
96 DCHECK(false) << "Should not be reached in 64b";
97 next_free_ = nullptr;
98#endif
99 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
100 // with the owner unlocking the thin-lock.
101 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
102 // The identity hash code is set for the life time of the monitor.
103}
104
105Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code,
106 MonitorId id)
107 : monitor_lock_("a monitor lock", kMonitorLock),
108 monitor_contenders_("monitor contenders", monitor_lock_),
109 num_waiters_(0),
110 owner_(owner),
111 lock_count_(0),
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700112 obj_(GcRoot<mirror::Object>(obj)),
Andreas Gampe74240812014-04-17 10:35:09 -0700113 wait_set_(NULL),
114 hash_code_(hash_code),
115 locking_method_(NULL),
116 locking_dex_pc_(0),
117 monitor_id_(id) {
118#ifdef __LP64__
119 next_free_ = nullptr;
120#endif
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700121 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
122 // with the owner unlocking the thin-lock.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800123 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700124 // The identity hash code is set for the life time of the monitor.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700125}
126
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700127int32_t Monitor::GetHashCode() {
128 while (!HasHashCode()) {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700129 if (hash_code_.CompareExchangeWeakRelaxed(0, mirror::Object::GenerateIdentityHashCode())) {
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700130 break;
131 }
132 }
133 DCHECK(HasHashCode());
Ian Rogers3e5cf302014-05-20 16:40:37 -0700134 return hash_code_.LoadRelaxed();
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700135}
136
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700137bool Monitor::Install(Thread* self) {
138 MutexLock mu(self, monitor_lock_); // Uncontended mutex acquisition as monitor isn't yet public.
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700139 CHECK(owner_ == nullptr || owner_ == self || owner_->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700140 // Propagate the lock state.
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700141 LockWord lw(GetObject()->GetLockWord(false));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700142 switch (lw.GetState()) {
143 case LockWord::kThinLocked: {
144 CHECK_EQ(owner_->GetThreadId(), lw.ThinLockOwner());
145 lock_count_ = lw.ThinLockCount();
146 break;
147 }
148 case LockWord::kHashCode: {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700149 CHECK_EQ(hash_code_.LoadRelaxed(), static_cast<int32_t>(lw.GetHashCode()));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700150 break;
151 }
152 case LockWord::kFatLocked: {
153 // The owner_ is suspended but another thread beat us to install a monitor.
154 return false;
155 }
156 case LockWord::kUnlocked: {
157 LOG(FATAL) << "Inflating unlocked lock word";
158 break;
159 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700160 default: {
161 LOG(FATAL) << "Invalid monitor state " << lw.GetState();
162 return false;
163 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700164 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700165 LockWord fat(this);
166 // Publish the updated lock word, which may race with other threads.
Ian Rogers228602f2014-07-10 02:07:54 -0700167 bool success = GetObject()->CasLockWordWeakSequentiallyConsistent(lw, fat);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700168 // Lock profiling.
Mathieu Chartier9728f912013-10-30 09:45:13 -0700169 if (success && owner_ != nullptr && lock_profiling_threshold_ != 0) {
Andreas Gampe6ec8ebd2014-07-25 13:36:56 -0700170 // Do not abort on dex pc errors. This can easily happen when we want to dump a stack trace on
171 // abort.
172 locking_method_ = owner_->GetCurrentMethod(&locking_dex_pc_, false);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700173 }
174 return success;
Elliott Hughes5f791332011-09-15 17:45:30 -0700175}
176
177Monitor::~Monitor() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700178 // Deflated monitors have a null object.
Elliott Hughes5f791332011-09-15 17:45:30 -0700179}
180
181/*
182 * Links a thread into a monitor's wait set. The monitor lock must be
183 * held by the caller of this routine.
184 */
185void Monitor::AppendToWaitSet(Thread* thread) {
186 DCHECK(owner_ == Thread::Current());
187 DCHECK(thread != NULL);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700188 DCHECK(thread->GetWaitNext() == nullptr) << thread->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700189 if (wait_set_ == NULL) {
190 wait_set_ = thread;
191 return;
192 }
193
194 // push_back.
195 Thread* t = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700196 while (t->GetWaitNext() != nullptr) {
197 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700198 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700199 t->SetWaitNext(thread);
Elliott Hughes5f791332011-09-15 17:45:30 -0700200}
201
202/*
203 * Unlinks a thread from a monitor's wait set. The monitor lock must
204 * be held by the caller of this routine.
205 */
206void Monitor::RemoveFromWaitSet(Thread *thread) {
207 DCHECK(owner_ == Thread::Current());
208 DCHECK(thread != NULL);
209 if (wait_set_ == NULL) {
210 return;
211 }
212 if (wait_set_ == thread) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700213 wait_set_ = thread->GetWaitNext();
214 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700215 return;
216 }
217
218 Thread* t = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700219 while (t->GetWaitNext() != NULL) {
220 if (t->GetWaitNext() == thread) {
221 t->SetWaitNext(thread->GetWaitNext());
222 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700223 return;
224 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700225 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700226 }
227}
228
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700229void Monitor::SetObject(mirror::Object* object) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700230 obj_ = GcRoot<mirror::Object>(object);
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700231}
232
Elliott Hughes5f791332011-09-15 17:45:30 -0700233void Monitor::Lock(Thread* self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700234 MutexLock mu(self, monitor_lock_);
235 while (true) {
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700236 if (owner_ == nullptr) { // Unowned.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700237 owner_ = self;
238 CHECK_EQ(lock_count_, 0);
239 // When debugging, save the current monitor holder for future
240 // acquisition failures to use in sampled logging.
241 if (lock_profiling_threshold_ != 0) {
242 locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
243 }
244 return;
245 } else if (owner_ == self) { // Recursive.
246 lock_count_++;
247 return;
248 }
249 // Contended.
250 const bool log_contention = (lock_profiling_threshold_ != 0);
Xin Guanb894a192014-08-22 11:55:37 -0500251 uint64_t wait_start_ms = log_contention ? MilliTime() : 0;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800252 mirror::ArtMethod* owners_method = locking_method_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700253 uint32_t owners_dex_pc = locking_dex_pc_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700254 // Do this before releasing the lock so that we don't get deflated.
Mathieu Chartierb9001ab2014-10-03 13:28:46 -0700255 size_t num_waiters = num_waiters_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700256 ++num_waiters_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700257 monitor_lock_.Unlock(self); // Let go of locks in order.
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700258 self->SetMonitorEnterObject(GetObject());
Elliott Hughes5f791332011-09-15 17:45:30 -0700259 {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700260 ScopedThreadStateChange tsc(self, kBlocked); // Change to blocked and give up mutator_lock_.
261 MutexLock mu2(self, monitor_lock_); // Reacquire monitor_lock_ without mutator_lock_ for Wait.
262 if (owner_ != NULL) { // Did the owner_ give the lock up?
263 monitor_contenders_.Wait(self); // Still contended so wait.
264 // Woken from contention.
265 if (log_contention) {
266 uint64_t wait_ms = MilliTime() - wait_start_ms;
267 uint32_t sample_percent;
268 if (wait_ms >= lock_profiling_threshold_) {
269 sample_percent = 100;
270 } else {
271 sample_percent = 100 * wait_ms / lock_profiling_threshold_;
272 }
273 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
274 const char* owners_filename;
275 uint32_t owners_line_number;
276 TranslateLocation(owners_method, owners_dex_pc, &owners_filename, &owners_line_number);
Mathieu Chartierb9001ab2014-10-03 13:28:46 -0700277 if (wait_ms > kLongWaitMs && owners_method != nullptr) {
278 LOG(WARNING) << "Long monitor contention event with owner method="
279 << PrettyMethod(owners_method) << " from " << owners_filename << ":"
280 << owners_line_number << " waiters=" << num_waiters << " for "
281 << PrettyDuration(MsToNs(wait_ms));
282 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700283 LogContentionEvent(self, wait_ms, sample_percent, owners_filename, owners_line_number);
284 }
285 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700286 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700287 }
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700288 self->SetMonitorEnterObject(nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700289 monitor_lock_.Lock(self); // Reacquire locks in order.
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700290 --num_waiters_;
Elliott Hughesfc861622011-10-17 17:57:47 -0700291 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700292}
293
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800294static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
295 __attribute__((format(printf, 1, 2)));
296
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700297static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700298 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800299 va_list args;
300 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800301 Thread* self = Thread::Current();
302 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
303 self->ThrowNewExceptionV(throw_location, "Ljava/lang/IllegalMonitorStateException;", fmt, args);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700304 if (!Runtime::Current()->IsStarted() || VLOG_IS_ON(monitor)) {
Brian Carlstrom64277f32012-03-26 23:53:34 -0700305 std::ostringstream ss;
Ian Rogers62d6c772013-02-27 08:32:07 -0800306 self->Dump(ss);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700307 LOG(Runtime::Current()->IsStarted() ? INFO : ERROR)
308 << self->GetException(NULL)->Dump() << "\n" << ss.str();
Brian Carlstrom64277f32012-03-26 23:53:34 -0700309 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800310 va_end(args);
311}
312
Elliott Hughesd4237412012-02-21 11:24:45 -0800313static std::string ThreadToString(Thread* thread) {
314 if (thread == NULL) {
315 return "NULL";
316 }
317 std::ostringstream oss;
318 // TODO: alternatively, we could just return the thread's name.
319 oss << *thread;
320 return oss.str();
321}
322
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800323void Monitor::FailedUnlock(mirror::Object* o, Thread* expected_owner, Thread* found_owner,
Elliott Hughesffb465f2012-03-01 18:46:05 -0800324 Monitor* monitor) {
325 Thread* current_owner = NULL;
326 std::string current_owner_string;
327 std::string expected_owner_string;
328 std::string found_owner_string;
329 {
330 // TODO: isn't this too late to prevent threads from disappearing?
331 // Acquire thread list lock so threads won't disappear from under us.
Ian Rogers50b35e22012-10-04 10:09:15 -0700332 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Elliott Hughesffb465f2012-03-01 18:46:05 -0800333 // Re-read owner now that we hold lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700334 current_owner = (monitor != NULL) ? monitor->GetOwner() : NULL;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800335 // Get short descriptions of the threads involved.
336 current_owner_string = ThreadToString(current_owner);
337 expected_owner_string = ThreadToString(expected_owner);
338 found_owner_string = ThreadToString(found_owner);
339 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800340 if (current_owner == NULL) {
341 if (found_owner == NULL) {
342 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
343 " on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800344 PrettyTypeOf(o).c_str(),
345 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800346 } else {
347 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800348 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
349 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800350 found_owner_string.c_str(),
351 PrettyTypeOf(o).c_str(),
352 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800353 }
354 } else {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800355 if (found_owner == NULL) {
356 // Race: originally there was no owner, there is now
357 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
358 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800359 current_owner_string.c_str(),
360 PrettyTypeOf(o).c_str(),
361 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800362 } else {
363 if (found_owner != current_owner) {
364 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800365 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
366 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800367 found_owner_string.c_str(),
368 current_owner_string.c_str(),
369 PrettyTypeOf(o).c_str(),
370 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800371 } else {
372 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
373 " on thread '%s",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800374 current_owner_string.c_str(),
375 PrettyTypeOf(o).c_str(),
376 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800377 }
378 }
379 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700380}
381
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700382bool Monitor::Unlock(Thread* self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700383 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700384 MutexLock mu(self, monitor_lock_);
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800385 Thread* owner = owner_;
386 if (owner == self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700387 // We own the monitor, so nobody else can be in here.
388 if (lock_count_ == 0) {
389 owner_ = NULL;
jeffhao33dc7712011-11-09 17:54:24 -0800390 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700391 locking_dex_pc_ = 0;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700392 // Wake a contender.
393 monitor_contenders_.Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700394 } else {
395 --lock_count_;
396 }
397 } else {
398 // We don't own this, so we're not allowed to unlock it.
399 // The JNI spec says that we should throw IllegalMonitorStateException
400 // in this case.
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700401 FailedUnlock(GetObject(), self, owner, this);
Elliott Hughes5f791332011-09-15 17:45:30 -0700402 return false;
403 }
404 return true;
405}
406
Elliott Hughes5f791332011-09-15 17:45:30 -0700407/*
408 * Wait on a monitor until timeout, interrupt, or notification. Used for
409 * Object.wait() and (somewhat indirectly) Thread.sleep() and Thread.join().
410 *
411 * If another thread calls Thread.interrupt(), we throw InterruptedException
412 * and return immediately if one of the following are true:
413 * - blocked in wait(), wait(long), or wait(long, int) methods of Object
414 * - blocked in join(), join(long), or join(long, int) methods of Thread
415 * - blocked in sleep(long), or sleep(long, int) methods of Thread
416 * Otherwise, we set the "interrupted" flag.
417 *
418 * Checks to make sure that "ns" is in the range 0-999999
419 * (i.e. fractions of a millisecond) and throws the appropriate
420 * exception if it isn't.
421 *
422 * The spec allows "spurious wakeups", and recommends that all code using
423 * Object.wait() do so in a loop. This appears to derive from concerns
424 * about pthread_cond_wait() on multiprocessor systems. Some commentary
425 * on the web casts doubt on whether these can/should occur.
426 *
427 * Since we're allowed to wake up "early", we clamp extremely long durations
428 * to return at the end of the 32-bit time epoch.
429 */
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800430void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
431 bool interruptShouldThrow, ThreadState why) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700432 DCHECK(self != NULL);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800433 DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
Elliott Hughes5f791332011-09-15 17:45:30 -0700434
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700435 monitor_lock_.Lock(self);
436
Elliott Hughes5f791332011-09-15 17:45:30 -0700437 // Make sure that we hold the lock.
438 if (owner_ != self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700439 monitor_lock_.Unlock(self);
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700440 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700441 return;
442 }
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800443
Elliott Hughesdf42c482013-01-09 12:49:02 -0800444 // We need to turn a zero-length timed wait into a regular wait because
445 // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
446 if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
447 why = kWaiting;
448 }
449
Elliott Hughes5f791332011-09-15 17:45:30 -0700450 // Enforce the timeout range.
451 if (ms < 0 || ns < 0 || ns > 999999) {
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700452 monitor_lock_.Unlock(self);
Ian Rogers62d6c772013-02-27 08:32:07 -0800453 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
454 self->ThrowNewExceptionF(throw_location, "Ljava/lang/IllegalArgumentException;",
Ian Rogersef7d42f2014-01-06 12:55:46 -0800455 "timeout arguments out of range: ms=%" PRId64 " ns=%d", ms, ns);
Elliott Hughes5f791332011-09-15 17:45:30 -0700456 return;
457 }
458
Elliott Hughes5f791332011-09-15 17:45:30 -0700459 /*
460 * Add ourselves to the set of threads waiting on this monitor, and
461 * release our hold. We need to let it go even if we're a few levels
462 * deep in a recursive lock, and we need to restore that later.
463 *
464 * We append to the wait set ahead of clearing the count and owner
465 * fields so the subroutine can check that the calling thread owns
466 * the monitor. Aside from that, the order of member updates is
467 * not order sensitive as we hold the pthread mutex.
468 */
469 AppendToWaitSet(self);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700470 ++num_waiters_;
Ian Rogers0399dde2012-06-06 17:09:28 -0700471 int prev_lock_count = lock_count_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700472 lock_count_ = 0;
473 owner_ = NULL;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800474 mirror::ArtMethod* saved_method = locking_method_;
jeffhao33dc7712011-11-09 17:54:24 -0800475 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700476 uintptr_t saved_dex_pc = locking_dex_pc_;
477 locking_dex_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700478
479 /*
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800480 * Update thread state. If the GC wakes up, it'll ignore us, knowing
Elliott Hughes5f791332011-09-15 17:45:30 -0700481 * that we won't touch any references in this state, and we'll check
482 * our suspend mode before we transition out.
483 */
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800484 self->TransitionFromRunnableToSuspended(why);
Elliott Hughes5f791332011-09-15 17:45:30 -0700485
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800486 bool was_interrupted = false;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700487 {
488 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700489 MutexLock mu(self, *self->GetWaitMutex());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700490
491 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
492 // non-NULL a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
493 // up.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700494 DCHECK(self->GetWaitMonitor() == nullptr);
495 self->SetWaitMonitor(this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700496
497 // Release the monitor lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700498 monitor_contenders_.Signal(self);
499 monitor_lock_.Unlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700500
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800501 // Handle the case where the thread was interrupted before we called wait().
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 } else {
505 // Wait for a notification or a timeout to occur.
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800506 if (why == kWaiting) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700507 self->GetWaitConditionVariable()->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700508 } else {
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800509 DCHECK(why == kTimedWaiting || why == kSleeping) << why;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700510 self->GetWaitConditionVariable()->TimedWait(self, ms, ns);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700511 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700512 if (self->IsInterruptedLocked()) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800513 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700514 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700515 self->SetInterruptedLocked(false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700516 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700517 }
518
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700519 // Set self->status back to kRunnable, and self-suspend if needed.
520 self->TransitionFromSuspendedToRunnable();
Elliott Hughes5f791332011-09-15 17:45:30 -0700521
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800522 {
523 // We reset the thread's wait_monitor_ field after transitioning back to runnable so
524 // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
525 // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
526 // are waiting on "null".)
Ian Rogersdd7624d2014-03-14 17:43:00 -0700527 MutexLock mu(self, *self->GetWaitMutex());
528 DCHECK(self->GetWaitMonitor() != nullptr);
529 self->SetWaitMonitor(nullptr);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800530 }
531
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700532 // Re-acquire the monitor and lock.
Elliott Hughes5f791332011-09-15 17:45:30 -0700533 Lock(self);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700534 monitor_lock_.Lock(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700535 self->GetWaitMutex()->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700536
Elliott Hughes5f791332011-09-15 17:45:30 -0700537 /*
538 * We remove our thread from wait set after restoring the count
539 * and owner fields so the subroutine can check that the calling
540 * thread owns the monitor. Aside from that, the order of member
541 * updates is not order sensitive as we hold the pthread mutex.
542 */
543 owner_ = self;
Ian Rogers0399dde2012-06-06 17:09:28 -0700544 lock_count_ = prev_lock_count;
545 locking_method_ = saved_method;
546 locking_dex_pc_ = saved_dex_pc;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700547 --num_waiters_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700548 RemoveFromWaitSet(self);
549
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700550 monitor_lock_.Unlock(self);
551
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800552 if (was_interrupted) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700553 /*
554 * We were interrupted while waiting, or somebody interrupted an
555 * un-interruptible thread earlier and we're bailing out immediately.
556 *
557 * The doc sayeth: "The interrupted status of the current thread is
558 * cleared when this exception is thrown."
559 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700560 {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700561 MutexLock mu(self, *self->GetWaitMutex());
562 self->SetInterruptedLocked(false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700563 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700564 if (interruptShouldThrow) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800565 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
566 self->ThrowNewException(throw_location, "Ljava/lang/InterruptedException;", NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700567 }
568 }
569}
570
571void Monitor::Notify(Thread* self) {
572 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700573 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700574 // Make sure that we hold the lock.
575 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800576 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700577 return;
578 }
579 // Signal the first waiting thread in the wait set.
580 while (wait_set_ != NULL) {
581 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700582 wait_set_ = thread->GetWaitNext();
583 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700584
585 // Check to see if the thread is still waiting.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700586 MutexLock mu(self, *thread->GetWaitMutex());
587 if (thread->GetWaitMonitor() != nullptr) {
588 thread->GetWaitConditionVariable()->Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700589 return;
590 }
591 }
592}
593
594void Monitor::NotifyAll(Thread* self) {
595 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700596 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700597 // Make sure that we hold the lock.
598 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800599 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700600 return;
601 }
602 // Signal all threads in the wait set.
603 while (wait_set_ != NULL) {
604 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700605 wait_set_ = thread->GetWaitNext();
606 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700607 thread->Notify();
608 }
609}
610
Mathieu Chartier590fee92013-09-13 13:46:47 -0700611bool Monitor::Deflate(Thread* self, mirror::Object* obj) {
612 DCHECK(obj != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700613 // Don't need volatile since we only deflate with mutators suspended.
614 LockWord lw(obj->GetLockWord(false));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700615 // If the lock isn't an inflated monitor, then we don't need to deflate anything.
616 if (lw.GetState() == LockWord::kFatLocked) {
617 Monitor* monitor = lw.FatLockMonitor();
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700618 DCHECK(monitor != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700619 MutexLock mu(self, monitor->monitor_lock_);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700620 // Can't deflate if we have anybody waiting on the CV.
621 if (monitor->num_waiters_ > 0) {
622 return false;
623 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700624 Thread* owner = monitor->owner_;
625 if (owner != nullptr) {
626 // Can't deflate if we are locked and have a hash code.
627 if (monitor->HasHashCode()) {
628 return false;
629 }
630 // Can't deflate if our lock count is too high.
631 if (monitor->lock_count_ > LockWord::kThinLockMaxCount) {
632 return false;
633 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700634 // Deflate to a thin lock.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700635 obj->SetLockWord(LockWord::FromThinLockId(owner->GetThreadId(), monitor->lock_count_), false);
636 VLOG(monitor) << "Deflated " << obj << " to thin lock " << owner->GetTid() << " / "
637 << monitor->lock_count_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700638 } else if (monitor->HasHashCode()) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700639 obj->SetLockWord(LockWord::FromHashCode(monitor->GetHashCode()), false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700640 VLOG(monitor) << "Deflated " << obj << " to hash monitor " << monitor->GetHashCode();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700641 } else {
642 // No lock and no hash, just put an empty lock word inside the object.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700643 obj->SetLockWord(LockWord(), false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700644 VLOG(monitor) << "Deflated" << obj << " to empty lock word";
Mathieu Chartier590fee92013-09-13 13:46:47 -0700645 }
646 // The monitor is deflated, mark the object as nullptr so that we know to delete it during the
647 // next GC.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700648 monitor->obj_ = GcRoot<mirror::Object>(nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700649 }
650 return true;
651}
652
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700653void Monitor::Inflate(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code) {
Andreas Gampe74240812014-04-17 10:35:09 -0700654 DCHECK(self != nullptr);
655 DCHECK(obj != nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700656 // Allocate and acquire a new monitor.
Andreas Gampe74240812014-04-17 10:35:09 -0700657 Monitor* m = MonitorPool::CreateMonitor(self, owner, obj, hash_code);
658 DCHECK(m != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700659 if (m->Install(self)) {
Haifeng Li86ab7912014-05-16 10:47:59 +0800660 if (owner != nullptr) {
661 VLOG(monitor) << "monitor: thread" << owner->GetThreadId()
Andreas Gampe74240812014-04-17 10:35:09 -0700662 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800663 } else {
664 VLOG(monitor) << "monitor: Inflate with hashcode " << hash_code
Andreas Gampe74240812014-04-17 10:35:09 -0700665 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800666 }
Andreas Gampe74240812014-04-17 10:35:09 -0700667 Runtime::Current()->GetMonitorList()->Add(m);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700668 CHECK_EQ(obj->GetLockWord(true).GetState(), LockWord::kFatLocked);
Andreas Gampe74240812014-04-17 10:35:09 -0700669 } else {
670 MonitorPool::ReleaseMonitor(self, m);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700671 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700672}
673
Mathieu Chartier0cd81352014-05-22 16:48:55 -0700674void Monitor::InflateThinLocked(Thread* self, Handle<mirror::Object> obj, LockWord lock_word,
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700675 uint32_t hash_code) {
676 DCHECK_EQ(lock_word.GetState(), LockWord::kThinLocked);
677 uint32_t owner_thread_id = lock_word.ThinLockOwner();
678 if (owner_thread_id == self->GetThreadId()) {
679 // We own the monitor, we can easily inflate it.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700680 Inflate(self, self, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700681 } else {
682 ThreadList* thread_list = Runtime::Current()->GetThreadList();
683 // Suspend the owner, inflate. First change to blocked and give up mutator_lock_.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700684 self->SetMonitorEnterObject(obj.Get());
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700685 bool timed_out;
686 Thread* owner;
687 {
688 ScopedThreadStateChange tsc(self, kBlocked);
Ian Rogersf3d874c2014-07-17 18:52:42 -0700689 // Take suspend thread lock to avoid races with threads trying to suspend this one.
690 MutexLock mu(self, *Locks::thread_list_suspend_thread_lock_);
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700691 owner = thread_list->SuspendThreadByThreadId(owner_thread_id, false, &timed_out);
692 }
693 if (owner != nullptr) {
694 // We succeeded in suspending the thread, check the lock's status didn't change.
695 lock_word = obj->GetLockWord(true);
696 if (lock_word.GetState() == LockWord::kThinLocked &&
697 lock_word.ThinLockOwner() == owner_thread_id) {
698 // Go ahead and inflate the lock.
699 Inflate(self, owner, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700700 }
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700701 thread_list->Resume(owner, false);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700702 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700703 self->SetMonitorEnterObject(nullptr);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700704 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700705}
706
Ian Rogers719d1a32014-03-06 12:13:39 -0800707// Fool annotalysis into thinking that the lock on obj is acquired.
708static mirror::Object* FakeLock(mirror::Object* obj)
709 EXCLUSIVE_LOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
710 return obj;
711}
712
713// Fool annotalysis into thinking that the lock on obj is release.
714static mirror::Object* FakeUnlock(mirror::Object* obj)
715 UNLOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
716 return obj;
717}
718
Mathieu Chartiere7e8a5f2014-02-14 16:59:41 -0800719mirror::Object* Monitor::MonitorEnter(Thread* self, mirror::Object* obj) {
Elliott Hughes4681c802011-09-25 18:04:37 -0700720 DCHECK(self != NULL);
721 DCHECK(obj != NULL);
Ian Rogers719d1a32014-03-06 12:13:39 -0800722 obj = FakeLock(obj);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700723 uint32_t thread_id = self->GetThreadId();
724 size_t contention_count = 0;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700725 StackHandleScope<1> hs(self);
726 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700727 while (true) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700728 LockWord lock_word = h_obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700729 switch (lock_word.GetState()) {
730 case LockWord::kUnlocked: {
731 LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0));
Ian Rogers228602f2014-07-10 02:07:54 -0700732 if (h_obj->CasLockWordWeakSequentiallyConsistent(lock_word, thin_locked)) {
Hans Boehm30359612014-05-21 17:46:23 -0700733 // CasLockWord enforces more than the acquire ordering we need here.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700734 return h_obj.Get(); // Success!
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700735 }
736 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -0700737 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700738 case LockWord::kThinLocked: {
739 uint32_t owner_thread_id = lock_word.ThinLockOwner();
740 if (owner_thread_id == thread_id) {
741 // We own the lock, increase the recursion count.
742 uint32_t new_count = lock_word.ThinLockCount() + 1;
743 if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
744 LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700745 h_obj->SetLockWord(thin_locked, true);
746 return h_obj.Get(); // Success!
Elliott Hughes5f791332011-09-15 17:45:30 -0700747 } else {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700748 // We'd overflow the recursion count, so inflate the monitor.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700749 InflateThinLocked(self, h_obj, lock_word, 0);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700750 }
751 } else {
752 // Contention.
753 contention_count++;
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700754 Runtime* runtime = Runtime::Current();
755 if (contention_count <= runtime->GetMaxSpinsBeforeThinkLockInflation()) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700756 // TODO: Consider switching the thread state to kBlocked when we are yielding.
Mathieu Chartier251755c2014-07-15 18:10:25 -0700757 // Use sched_yield instead of NanoSleep since NanoSleep can wait much longer than the
758 // parameter you pass in. This can cause thread suspension to take excessively long
Mathieu Chartierb363f662014-07-16 13:28:58 -0700759 // and make long pauses. See b/16307460.
Mathieu Chartier251755c2014-07-15 18:10:25 -0700760 sched_yield();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700761 } else {
762 contention_count = 0;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700763 InflateThinLocked(self, h_obj, lock_word, 0);
Elliott Hughes5f791332011-09-15 17:45:30 -0700764 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700765 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700766 continue; // Start from the beginning.
Elliott Hughes5f791332011-09-15 17:45:30 -0700767 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700768 case LockWord::kFatLocked: {
769 Monitor* mon = lock_word.FatLockMonitor();
770 mon->Lock(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700771 return h_obj.Get(); // Success!
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700772 }
Ian Rogers719d1a32014-03-06 12:13:39 -0800773 case LockWord::kHashCode:
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700774 // Inflate with the existing hashcode.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700775 Inflate(self, nullptr, h_obj.Get(), lock_word.GetHashCode());
Ian Rogers719d1a32014-03-06 12:13:39 -0800776 continue; // Start from the beginning.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700777 default: {
778 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700779 return h_obj.Get();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700780 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700781 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700782 }
783}
784
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800785bool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700786 DCHECK(self != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700787 DCHECK(obj != NULL);
Ian Rogers719d1a32014-03-06 12:13:39 -0800788 obj = FakeUnlock(obj);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700789 LockWord lock_word = obj->GetLockWord(true);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700790 StackHandleScope<1> hs(self);
791 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700792 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700793 case LockWord::kHashCode:
794 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700795 case LockWord::kUnlocked:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700796 FailedUnlock(h_obj.Get(), self, nullptr, nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700797 return false; // Failure.
798 case LockWord::kThinLocked: {
799 uint32_t thread_id = self->GetThreadId();
800 uint32_t owner_thread_id = lock_word.ThinLockOwner();
801 if (owner_thread_id != thread_id) {
802 // TODO: there's a race here with the owner dying while we unlock.
803 Thread* owner =
804 Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700805 FailedUnlock(h_obj.Get(), self, owner, nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700806 return false; // Failure.
807 } else {
808 // We own the lock, decrease the recursion count.
809 if (lock_word.ThinLockCount() != 0) {
810 uint32_t new_count = lock_word.ThinLockCount() - 1;
811 LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700812 h_obj->SetLockWord(thin_locked, true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700813 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700814 h_obj->SetLockWord(LockWord(), true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700815 }
816 return true; // Success!
817 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700818 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700819 case LockWord::kFatLocked: {
820 Monitor* mon = lock_word.FatLockMonitor();
821 return mon->Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700822 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700823 default: {
824 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700825 return false;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700826 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700827 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700828}
829
830/*
831 * Object.wait(). Also called for class init.
832 */
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800833void Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800834 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700835 DCHECK(self != nullptr);
836 DCHECK(obj != nullptr);
837 LockWord lock_word = obj->GetLockWord(true);
Ian Rogers6f22fc12014-08-15 11:09:28 -0700838 while (lock_word.GetState() != LockWord::kFatLocked) {
839 switch (lock_word.GetState()) {
840 case LockWord::kHashCode:
841 // Fall-through.
842 case LockWord::kUnlocked:
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700843 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
844 return; // Failure.
Ian Rogers6f22fc12014-08-15 11:09:28 -0700845 case LockWord::kThinLocked: {
846 uint32_t thread_id = self->GetThreadId();
847 uint32_t owner_thread_id = lock_word.ThinLockOwner();
848 if (owner_thread_id != thread_id) {
849 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
850 return; // Failure.
851 } else {
852 // We own the lock, inflate to enqueue ourself on the Monitor. May fail spuriously so
853 // re-load.
854 Inflate(self, self, obj, 0);
855 lock_word = obj->GetLockWord(true);
856 }
857 break;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700858 }
Ian Rogers6f22fc12014-08-15 11:09:28 -0700859 case LockWord::kFatLocked: // Unreachable given the loop condition above. Fall-through.
860 default: {
861 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
862 return;
863 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700864 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700865 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700866 Monitor* mon = lock_word.FatLockMonitor();
867 mon->Wait(self, ms, ns, interruptShouldThrow, why);
Elliott Hughes5f791332011-09-15 17:45:30 -0700868}
869
Ian Rogers13c479e2013-10-11 07:59:01 -0700870void Monitor::DoNotify(Thread* self, mirror::Object* obj, bool notify_all) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700871 DCHECK(self != nullptr);
872 DCHECK(obj != nullptr);
873 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700874 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700875 case LockWord::kHashCode:
876 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700877 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800878 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700879 return; // Failure.
880 case LockWord::kThinLocked: {
881 uint32_t thread_id = self->GetThreadId();
882 uint32_t owner_thread_id = lock_word.ThinLockOwner();
883 if (owner_thread_id != thread_id) {
884 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
885 return; // Failure.
886 } else {
887 // We own the lock but there's no Monitor and therefore no waiters.
888 return; // Success.
889 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700890 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700891 case LockWord::kFatLocked: {
892 Monitor* mon = lock_word.FatLockMonitor();
893 if (notify_all) {
894 mon->NotifyAll(self);
895 } else {
896 mon->Notify(self);
897 }
898 return; // Success.
899 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700900 default: {
901 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
902 return;
903 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700904 }
905}
906
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700907uint32_t Monitor::GetLockOwnerThreadId(mirror::Object* obj) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700908 DCHECK(obj != nullptr);
909 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700910 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700911 case LockWord::kHashCode:
912 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700913 case LockWord::kUnlocked:
914 return ThreadList::kInvalidThreadId;
915 case LockWord::kThinLocked:
916 return lock_word.ThinLockOwner();
917 case LockWord::kFatLocked: {
918 Monitor* mon = lock_word.FatLockMonitor();
919 return mon->GetOwnerThreadId();
Elliott Hughes5f791332011-09-15 17:45:30 -0700920 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700921 default: {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700922 LOG(FATAL) << "Unreachable";
923 return ThreadList::kInvalidThreadId;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700924 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700925 }
926}
927
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700928void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
Ian Rogersd803bc72014-04-01 15:33:03 -0700929 // Determine the wait message and object we're waiting or blocked upon.
930 mirror::Object* pretty_object = nullptr;
931 const char* wait_message = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700932 uint32_t lock_owner = ThreadList::kInvalidThreadId;
Ian Rogersd803bc72014-04-01 15:33:03 -0700933 ThreadState state = thread->GetState();
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800934 if (state == kWaiting || state == kTimedWaiting || state == kSleeping) {
Ian Rogersd803bc72014-04-01 15:33:03 -0700935 wait_message = (state == kSleeping) ? " - sleeping on " : " - waiting on ";
936 Thread* self = Thread::Current();
937 MutexLock mu(self, *thread->GetWaitMutex());
938 Monitor* monitor = thread->GetWaitMonitor();
939 if (monitor != nullptr) {
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700940 pretty_object = monitor->GetObject();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700941 }
Elliott Hughes34e06962012-04-09 13:55:55 -0700942 } else if (state == kBlocked) {
Ian Rogersd803bc72014-04-01 15:33:03 -0700943 wait_message = " - waiting to lock ";
944 pretty_object = thread->GetMonitorEnterObject();
945 if (pretty_object != nullptr) {
946 lock_owner = pretty_object->GetLockOwnerThreadId();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700947 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700948 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700949
Ian Rogersd803bc72014-04-01 15:33:03 -0700950 if (wait_message != nullptr) {
951 if (pretty_object == nullptr) {
952 os << wait_message << "an unknown object";
953 } else {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700954 if ((pretty_object->GetLockWord(true).GetState() == LockWord::kThinLocked) &&
Ian Rogersd803bc72014-04-01 15:33:03 -0700955 Locks::mutator_lock_->IsExclusiveHeld(Thread::Current())) {
956 // Getting the identity hashcode here would result in lock inflation and suspension of the
957 // current thread, which isn't safe if this is the only runnable thread.
958 os << wait_message << StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)",
959 reinterpret_cast<intptr_t>(pretty_object),
960 PrettyTypeOf(pretty_object).c_str());
961 } else {
962 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
963 os << wait_message << StringPrintf("<0x%08x> (a %s)", pretty_object->IdentityHashCode(),
964 PrettyTypeOf(pretty_object).c_str());
965 }
966 }
967 // - waiting to lock <0x613f83d8> (a java.lang.Object) held by thread 5
968 if (lock_owner != ThreadList::kInvalidThreadId) {
969 os << " held by thread " << lock_owner;
970 }
971 os << "\n";
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700972 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700973}
974
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800975mirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800976 // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
977 // definition of contended that includes a monitor a thread is trying to enter...
Ian Rogersdd7624d2014-03-14 17:43:00 -0700978 mirror::Object* result = thread->GetMonitorEnterObject();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700979 if (result == NULL) {
980 // ...but also a monitor that the thread is waiting on.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700981 MutexLock mu(Thread::Current(), *thread->GetWaitMutex());
982 Monitor* monitor = thread->GetWaitMonitor();
Elliott Hughesf9501702013-01-11 11:22:27 -0800983 if (monitor != NULL) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700984 result = monitor->GetObject();
Elliott Hughesf9501702013-01-11 11:22:27 -0800985 }
986 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700987 return result;
Elliott Hughesf9501702013-01-11 11:22:27 -0800988}
989
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800990void Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
Andreas Gampe760172c2014-08-16 13:41:10 -0700991 void* callback_context, bool abort_on_failure) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700992 mirror::ArtMethod* m = stack_visitor->GetMethod();
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700993 CHECK(m != NULL);
994
995 // Native methods are an easy special case.
996 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
997 if (m->IsNative()) {
998 if (m->IsSynchronized()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700999 mirror::Object* jni_this = stack_visitor->GetCurrentHandleScope()->GetReference(0);
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001000 callback(jni_this, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001001 }
1002 return;
1003 }
1004
jeffhao61f916c2012-10-25 17:48:51 -07001005 // Proxy methods should not be synchronized.
1006 if (m->IsProxyMethod()) {
1007 CHECK(!m->IsSynchronized());
1008 return;
1009 }
1010
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001011 // Is there any reason to believe there's any synchronization in this method?
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001012 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -07001013 CHECK(code_item != NULL) << PrettyMethod(m);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001014 if (code_item->tries_size_ == 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001015 return; // No "tries" implies no synchronization, so no held locks to report.
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001016 }
1017
Andreas Gampe760172c2014-08-16 13:41:10 -07001018 // Get the dex pc. If abort_on_failure is false, GetDexPc will not abort in the case it cannot
1019 // find the dex pc, and instead return kDexNoIndex. Then bail out, as it indicates we have an
1020 // inconsistent stack anyways.
1021 uint32_t dex_pc = stack_visitor->GetDexPc(abort_on_failure);
1022 if (!abort_on_failure && dex_pc == DexFile::kDexNoIndex) {
1023 LOG(ERROR) << "Could not find dex_pc for " << PrettyMethod(m);
1024 return;
1025 }
1026
Elliott Hughes80537bb2013-01-04 16:37:26 -08001027 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
1028 // the locks held in this stack frame.
1029 std::vector<uint32_t> monitor_enter_dex_pcs;
Andreas Gampe760172c2014-08-16 13:41:10 -07001030 verifier::MethodVerifier::FindLocksAtDexPc(m, dex_pc, &monitor_enter_dex_pcs);
Elliott Hughes80537bb2013-01-04 16:37:26 -08001031 if (monitor_enter_dex_pcs.empty()) {
1032 return;
1033 }
1034
Elliott Hughes80537bb2013-01-04 16:37:26 -08001035 for (size_t i = 0; i < monitor_enter_dex_pcs.size(); ++i) {
1036 // The verifier works in terms of the dex pcs of the monitor-enter instructions.
1037 // We want the registers used by those instructions (so we can read the values out of them).
1038 uint32_t dex_pc = monitor_enter_dex_pcs[i];
1039 uint16_t monitor_enter_instruction = code_item->insns_[dex_pc];
1040
1041 // Quick sanity check.
1042 if ((monitor_enter_instruction & 0xff) != Instruction::MONITOR_ENTER) {
1043 LOG(FATAL) << "expected monitor-enter @" << dex_pc << "; was "
1044 << reinterpret_cast<void*>(monitor_enter_instruction);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001045 }
1046
Elliott Hughes80537bb2013-01-04 16:37:26 -08001047 uint16_t monitor_register = ((monitor_enter_instruction >> 8) & 0xff);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001048 mirror::Object* o = reinterpret_cast<mirror::Object*>(stack_visitor->GetVReg(m, monitor_register,
1049 kReferenceVReg));
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001050 callback(o, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001051 }
1052}
1053
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001054bool Monitor::IsValidLockWord(LockWord lock_word) {
1055 switch (lock_word.GetState()) {
1056 case LockWord::kUnlocked:
1057 // Nothing to check.
1058 return true;
1059 case LockWord::kThinLocked:
1060 // Basic sanity check of owner.
1061 return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
1062 case LockWord::kFatLocked: {
1063 // Check the monitor appears in the monitor list.
1064 Monitor* mon = lock_word.FatLockMonitor();
1065 MonitorList* list = Runtime::Current()->GetMonitorList();
1066 MutexLock mu(Thread::Current(), list->monitor_list_lock_);
1067 for (Monitor* list_mon : list->list_) {
1068 if (mon == list_mon) {
1069 return true; // Found our monitor.
1070 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001071 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001072 return false; // Fail - unowned monitor in an object.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001073 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001074 case LockWord::kHashCode:
1075 return true;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001076 default:
1077 LOG(FATAL) << "Unreachable";
1078 return false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001079 }
1080}
1081
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001082bool Monitor::IsLocked() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1083 MutexLock mu(Thread::Current(), monitor_lock_);
1084 return owner_ != nullptr;
1085}
1086
Ian Rogersef7d42f2014-01-06 12:55:46 -08001087void Monitor::TranslateLocation(mirror::ArtMethod* method, uint32_t dex_pc,
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001088 const char** source_file, uint32_t* line_number) const {
jeffhao33dc7712011-11-09 17:54:24 -08001089 // If method is null, location is unknown
1090 if (method == NULL) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001091 *source_file = "";
1092 *line_number = 0;
jeffhao33dc7712011-11-09 17:54:24 -08001093 return;
1094 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001095 *source_file = method->GetDeclaringClassSourceFile();
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001096 if (*source_file == NULL) {
1097 *source_file = "";
Elliott Hughes12c51e32012-01-17 20:25:05 -08001098 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001099 *line_number = method->GetLineNumFromDexPC(dex_pc);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001100}
1101
1102uint32_t Monitor::GetOwnerThreadId() {
1103 MutexLock mu(Thread::Current(), monitor_lock_);
1104 Thread* owner = owner_;
1105 if (owner != NULL) {
1106 return owner->GetThreadId();
1107 } else {
1108 return ThreadList::kInvalidThreadId;
1109 }
jeffhao33dc7712011-11-09 17:54:24 -08001110}
1111
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001112MonitorList::MonitorList()
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001113 : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock", kMonitorListLock),
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001114 monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001115}
1116
1117MonitorList::~MonitorList() {
Andreas Gampe74240812014-04-17 10:35:09 -07001118 Thread* self = Thread::Current();
1119 MutexLock mu(self, monitor_list_lock_);
1120 // Release all monitors to the pool.
1121 // TODO: Is it an invariant that *all* open monitors are in the list? Then we could
1122 // clear faster in the pool.
1123 MonitorPool::ReleaseMonitors(self, &list_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001124}
1125
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001126void MonitorList::DisallowNewMonitors() {
Ian Rogers50b35e22012-10-04 10:09:15 -07001127 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001128 allow_new_monitors_ = false;
1129}
1130
1131void MonitorList::AllowNewMonitors() {
1132 Thread* self = Thread::Current();
1133 MutexLock mu(self, monitor_list_lock_);
1134 allow_new_monitors_ = true;
1135 monitor_add_condition_.Broadcast(self);
1136}
1137
1138void MonitorList::Add(Monitor* m) {
1139 Thread* self = Thread::Current();
1140 MutexLock mu(self, monitor_list_lock_);
1141 while (UNLIKELY(!allow_new_monitors_)) {
1142 monitor_add_condition_.WaitHoldingLocks(self);
1143 }
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001144 list_.push_front(m);
1145}
1146
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08001147void MonitorList::SweepMonitorList(IsMarkedCallback* callback, void* arg) {
Andreas Gampe74240812014-04-17 10:35:09 -07001148 Thread* self = Thread::Current();
1149 MutexLock mu(self, monitor_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001150 for (auto it = list_.begin(); it != list_.end(); ) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001151 Monitor* m = *it;
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001152 // Disable the read barrier in GetObject() as this is called by GC.
1153 mirror::Object* obj = m->GetObject<kWithoutReadBarrier>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001154 // The object of a monitor can be null if we have deflated it.
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08001155 mirror::Object* new_obj = obj != nullptr ? callback(obj, arg) : nullptr;
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001156 if (new_obj == nullptr) {
1157 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001158 << obj;
Andreas Gampe74240812014-04-17 10:35:09 -07001159 MonitorPool::ReleaseMonitor(self, m);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001160 it = list_.erase(it);
1161 } else {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001162 m->SetObject(new_obj);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001163 ++it;
1164 }
1165 }
1166}
1167
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001168struct MonitorDeflateArgs {
1169 MonitorDeflateArgs() : self(Thread::Current()), deflate_count(0) {}
1170 Thread* const self;
1171 size_t deflate_count;
1172};
1173
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001174static mirror::Object* MonitorDeflateCallback(mirror::Object* object, void* arg)
1175 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001176 MonitorDeflateArgs* args = reinterpret_cast<MonitorDeflateArgs*>(arg);
1177 if (Monitor::Deflate(args->self, object)) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001178 DCHECK_NE(object->GetLockWord(true).GetState(), LockWord::kFatLocked);
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001179 ++args->deflate_count;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001180 // If we deflated, return nullptr so that the monitor gets removed from the array.
1181 return nullptr;
1182 }
1183 return object; // Monitor was not deflated.
1184}
1185
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001186size_t MonitorList::DeflateMonitors() {
1187 MonitorDeflateArgs args;
1188 Locks::mutator_lock_->AssertExclusiveHeld(args.self);
1189 SweepMonitorList(MonitorDeflateCallback, &args);
1190 return args.deflate_count;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001191}
1192
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001193MonitorInfo::MonitorInfo(mirror::Object* obj) : owner_(NULL), entry_count_(0) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001194 DCHECK(obj != nullptr);
1195 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001196 switch (lock_word.GetState()) {
1197 case LockWord::kUnlocked:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001198 // Fall-through.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001199 case LockWord::kForwardingAddress:
1200 // Fall-through.
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001201 case LockWord::kHashCode:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001202 break;
1203 case LockWord::kThinLocked:
1204 owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
1205 entry_count_ = 1 + lock_word.ThinLockCount();
1206 // Thin locks have no waiters.
1207 break;
1208 case LockWord::kFatLocked: {
1209 Monitor* mon = lock_word.FatLockMonitor();
1210 owner_ = mon->owner_;
1211 entry_count_ = 1 + mon->lock_count_;
Ian Rogersdd7624d2014-03-14 17:43:00 -07001212 for (Thread* waiter = mon->wait_set_; waiter != NULL; waiter = waiter->GetWaitNext()) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001213 waiters_.push_back(waiter);
1214 }
1215 break;
Elliott Hughesf327e072013-01-09 16:01:26 -08001216 }
1217 }
1218}
1219
Elliott Hughes5f791332011-09-15 17:45:30 -07001220} // namespace art