blob: 233267b53ce54217aaabe6a628c90f3f3be836b0 [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
Elliott Hughes5f791332011-09-15 17:45:30 -0700181void 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
Elliott Hughes5f791332011-09-15 17:45:30 -0700198void Monitor::RemoveFromWaitSet(Thread *thread) {
199 DCHECK(owner_ == Thread::Current());
200 DCHECK(thread != NULL);
201 if (wait_set_ == NULL) {
202 return;
203 }
204 if (wait_set_ == thread) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700205 wait_set_ = thread->GetWaitNext();
206 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700207 return;
208 }
209
210 Thread* t = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700211 while (t->GetWaitNext() != NULL) {
212 if (t->GetWaitNext() == thread) {
213 t->SetWaitNext(thread->GetWaitNext());
214 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700215 return;
216 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700217 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700218 }
219}
220
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700221void Monitor::SetObject(mirror::Object* object) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700222 obj_ = GcRoot<mirror::Object>(object);
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700223}
224
Elliott Hughes5f791332011-09-15 17:45:30 -0700225void Monitor::Lock(Thread* self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700226 MutexLock mu(self, monitor_lock_);
227 while (true) {
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700228 if (owner_ == nullptr) { // Unowned.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700229 owner_ = self;
230 CHECK_EQ(lock_count_, 0);
231 // When debugging, save the current monitor holder for future
232 // acquisition failures to use in sampled logging.
233 if (lock_profiling_threshold_ != 0) {
234 locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
235 }
236 return;
237 } else if (owner_ == self) { // Recursive.
238 lock_count_++;
239 return;
240 }
241 // Contended.
242 const bool log_contention = (lock_profiling_threshold_ != 0);
Xin Guanb894a192014-08-22 11:55:37 -0500243 uint64_t wait_start_ms = log_contention ? MilliTime() : 0;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800244 mirror::ArtMethod* owners_method = locking_method_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700245 uint32_t owners_dex_pc = locking_dex_pc_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700246 // Do this before releasing the lock so that we don't get deflated.
Mathieu Chartierb9001ab2014-10-03 13:28:46 -0700247 size_t num_waiters = num_waiters_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700248 ++num_waiters_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700249 monitor_lock_.Unlock(self); // Let go of locks in order.
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700250 self->SetMonitorEnterObject(GetObject());
Elliott Hughes5f791332011-09-15 17:45:30 -0700251 {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700252 ScopedThreadStateChange tsc(self, kBlocked); // Change to blocked and give up mutator_lock_.
253 MutexLock mu2(self, monitor_lock_); // Reacquire monitor_lock_ without mutator_lock_ for Wait.
254 if (owner_ != NULL) { // Did the owner_ give the lock up?
255 monitor_contenders_.Wait(self); // Still contended so wait.
256 // Woken from contention.
257 if (log_contention) {
258 uint64_t wait_ms = MilliTime() - wait_start_ms;
259 uint32_t sample_percent;
260 if (wait_ms >= lock_profiling_threshold_) {
261 sample_percent = 100;
262 } else {
263 sample_percent = 100 * wait_ms / lock_profiling_threshold_;
264 }
265 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
266 const char* owners_filename;
267 uint32_t owners_line_number;
268 TranslateLocation(owners_method, owners_dex_pc, &owners_filename, &owners_line_number);
Mathieu Chartierb9001ab2014-10-03 13:28:46 -0700269 if (wait_ms > kLongWaitMs && owners_method != nullptr) {
270 LOG(WARNING) << "Long monitor contention event with owner method="
271 << PrettyMethod(owners_method) << " from " << owners_filename << ":"
272 << owners_line_number << " waiters=" << num_waiters << " for "
273 << PrettyDuration(MsToNs(wait_ms));
274 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700275 LogContentionEvent(self, wait_ms, sample_percent, owners_filename, owners_line_number);
276 }
277 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700278 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700279 }
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700280 self->SetMonitorEnterObject(nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700281 monitor_lock_.Lock(self); // Reacquire locks in order.
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700282 --num_waiters_;
Elliott Hughesfc861622011-10-17 17:57:47 -0700283 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700284}
285
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800286static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
287 __attribute__((format(printf, 1, 2)));
288
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700289static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700290 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800291 va_list args;
292 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800293 Thread* self = Thread::Current();
294 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
295 self->ThrowNewExceptionV(throw_location, "Ljava/lang/IllegalMonitorStateException;", fmt, args);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700296 if (!Runtime::Current()->IsStarted() || VLOG_IS_ON(monitor)) {
Brian Carlstrom64277f32012-03-26 23:53:34 -0700297 std::ostringstream ss;
Ian Rogers62d6c772013-02-27 08:32:07 -0800298 self->Dump(ss);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700299 LOG(Runtime::Current()->IsStarted() ? INFO : ERROR)
300 << self->GetException(NULL)->Dump() << "\n" << ss.str();
Brian Carlstrom64277f32012-03-26 23:53:34 -0700301 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800302 va_end(args);
303}
304
Elliott Hughesd4237412012-02-21 11:24:45 -0800305static std::string ThreadToString(Thread* thread) {
306 if (thread == NULL) {
307 return "NULL";
308 }
309 std::ostringstream oss;
310 // TODO: alternatively, we could just return the thread's name.
311 oss << *thread;
312 return oss.str();
313}
314
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800315void Monitor::FailedUnlock(mirror::Object* o, Thread* expected_owner, Thread* found_owner,
Elliott Hughesffb465f2012-03-01 18:46:05 -0800316 Monitor* monitor) {
317 Thread* current_owner = NULL;
318 std::string current_owner_string;
319 std::string expected_owner_string;
320 std::string found_owner_string;
321 {
322 // TODO: isn't this too late to prevent threads from disappearing?
323 // Acquire thread list lock so threads won't disappear from under us.
Ian Rogers50b35e22012-10-04 10:09:15 -0700324 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Elliott Hughesffb465f2012-03-01 18:46:05 -0800325 // Re-read owner now that we hold lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700326 current_owner = (monitor != NULL) ? monitor->GetOwner() : NULL;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800327 // Get short descriptions of the threads involved.
328 current_owner_string = ThreadToString(current_owner);
329 expected_owner_string = ThreadToString(expected_owner);
330 found_owner_string = ThreadToString(found_owner);
331 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800332 if (current_owner == NULL) {
333 if (found_owner == NULL) {
334 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
335 " on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800336 PrettyTypeOf(o).c_str(),
337 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800338 } else {
339 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800340 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
341 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800342 found_owner_string.c_str(),
343 PrettyTypeOf(o).c_str(),
344 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800345 }
346 } else {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800347 if (found_owner == NULL) {
348 // Race: originally there was no owner, there is now
349 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
350 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800351 current_owner_string.c_str(),
352 PrettyTypeOf(o).c_str(),
353 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800354 } else {
355 if (found_owner != current_owner) {
356 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800357 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
358 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800359 found_owner_string.c_str(),
360 current_owner_string.c_str(),
361 PrettyTypeOf(o).c_str(),
362 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800363 } else {
364 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
365 " on thread '%s",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800366 current_owner_string.c_str(),
367 PrettyTypeOf(o).c_str(),
368 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800369 }
370 }
371 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700372}
373
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700374bool Monitor::Unlock(Thread* self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700375 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700376 MutexLock mu(self, monitor_lock_);
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800377 Thread* owner = owner_;
378 if (owner == self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700379 // We own the monitor, so nobody else can be in here.
380 if (lock_count_ == 0) {
381 owner_ = NULL;
jeffhao33dc7712011-11-09 17:54:24 -0800382 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700383 locking_dex_pc_ = 0;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700384 // Wake a contender.
385 monitor_contenders_.Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700386 } else {
387 --lock_count_;
388 }
389 } else {
390 // We don't own this, so we're not allowed to unlock it.
391 // The JNI spec says that we should throw IllegalMonitorStateException
392 // in this case.
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700393 FailedUnlock(GetObject(), self, owner, this);
Elliott Hughes5f791332011-09-15 17:45:30 -0700394 return false;
395 }
396 return true;
397}
398
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800399void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
400 bool interruptShouldThrow, ThreadState why) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700401 DCHECK(self != NULL);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800402 DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
Elliott Hughes5f791332011-09-15 17:45:30 -0700403
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700404 monitor_lock_.Lock(self);
405
Elliott Hughes5f791332011-09-15 17:45:30 -0700406 // Make sure that we hold the lock.
407 if (owner_ != self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700408 monitor_lock_.Unlock(self);
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700409 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700410 return;
411 }
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800412
Elliott Hughesdf42c482013-01-09 12:49:02 -0800413 // We need to turn a zero-length timed wait into a regular wait because
414 // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
415 if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
416 why = kWaiting;
417 }
418
Elliott Hughes5f791332011-09-15 17:45:30 -0700419 // Enforce the timeout range.
420 if (ms < 0 || ns < 0 || ns > 999999) {
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700421 monitor_lock_.Unlock(self);
Ian Rogers62d6c772013-02-27 08:32:07 -0800422 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
423 self->ThrowNewExceptionF(throw_location, "Ljava/lang/IllegalArgumentException;",
Ian Rogersef7d42f2014-01-06 12:55:46 -0800424 "timeout arguments out of range: ms=%" PRId64 " ns=%d", ms, ns);
Elliott Hughes5f791332011-09-15 17:45:30 -0700425 return;
426 }
427
Elliott Hughes5f791332011-09-15 17:45:30 -0700428 /*
429 * Add ourselves to the set of threads waiting on this monitor, and
430 * release our hold. We need to let it go even if we're a few levels
431 * deep in a recursive lock, and we need to restore that later.
432 *
433 * We append to the wait set ahead of clearing the count and owner
434 * fields so the subroutine can check that the calling thread owns
435 * the monitor. Aside from that, the order of member updates is
436 * not order sensitive as we hold the pthread mutex.
437 */
438 AppendToWaitSet(self);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700439 ++num_waiters_;
Ian Rogers0399dde2012-06-06 17:09:28 -0700440 int prev_lock_count = lock_count_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700441 lock_count_ = 0;
442 owner_ = NULL;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800443 mirror::ArtMethod* saved_method = locking_method_;
jeffhao33dc7712011-11-09 17:54:24 -0800444 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700445 uintptr_t saved_dex_pc = locking_dex_pc_;
446 locking_dex_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700447
448 /*
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800449 * Update thread state. If the GC wakes up, it'll ignore us, knowing
Elliott Hughes5f791332011-09-15 17:45:30 -0700450 * that we won't touch any references in this state, and we'll check
451 * our suspend mode before we transition out.
452 */
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800453 self->TransitionFromRunnableToSuspended(why);
Elliott Hughes5f791332011-09-15 17:45:30 -0700454
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800455 bool was_interrupted = false;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700456 {
457 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700458 MutexLock mu(self, *self->GetWaitMutex());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700459
460 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
461 // non-NULL a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
462 // up.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700463 DCHECK(self->GetWaitMonitor() == nullptr);
464 self->SetWaitMonitor(this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700465
466 // Release the monitor lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700467 monitor_contenders_.Signal(self);
468 monitor_lock_.Unlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700469
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800470 // Handle the case where the thread was interrupted before we called wait().
Ian Rogersdd7624d2014-03-14 17:43:00 -0700471 if (self->IsInterruptedLocked()) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800472 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700473 } else {
474 // Wait for a notification or a timeout to occur.
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800475 if (why == kWaiting) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700476 self->GetWaitConditionVariable()->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700477 } else {
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800478 DCHECK(why == kTimedWaiting || why == kSleeping) << why;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700479 self->GetWaitConditionVariable()->TimedWait(self, ms, ns);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700480 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700481 if (self->IsInterruptedLocked()) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800482 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700483 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700484 self->SetInterruptedLocked(false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700485 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700486 }
487
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700488 // Set self->status back to kRunnable, and self-suspend if needed.
489 self->TransitionFromSuspendedToRunnable();
Elliott Hughes5f791332011-09-15 17:45:30 -0700490
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800491 {
492 // We reset the thread's wait_monitor_ field after transitioning back to runnable so
493 // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
494 // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
495 // are waiting on "null".)
Ian Rogersdd7624d2014-03-14 17:43:00 -0700496 MutexLock mu(self, *self->GetWaitMutex());
497 DCHECK(self->GetWaitMonitor() != nullptr);
498 self->SetWaitMonitor(nullptr);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800499 }
500
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700501 // Re-acquire the monitor and lock.
Elliott Hughes5f791332011-09-15 17:45:30 -0700502 Lock(self);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700503 monitor_lock_.Lock(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700504 self->GetWaitMutex()->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700505
Elliott Hughes5f791332011-09-15 17:45:30 -0700506 /*
507 * We remove our thread from wait set after restoring the count
508 * and owner fields so the subroutine can check that the calling
509 * thread owns the monitor. Aside from that, the order of member
510 * updates is not order sensitive as we hold the pthread mutex.
511 */
512 owner_ = self;
Ian Rogers0399dde2012-06-06 17:09:28 -0700513 lock_count_ = prev_lock_count;
514 locking_method_ = saved_method;
515 locking_dex_pc_ = saved_dex_pc;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700516 --num_waiters_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700517 RemoveFromWaitSet(self);
518
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700519 monitor_lock_.Unlock(self);
520
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800521 if (was_interrupted) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700522 /*
523 * We were interrupted while waiting, or somebody interrupted an
524 * un-interruptible thread earlier and we're bailing out immediately.
525 *
526 * The doc sayeth: "The interrupted status of the current thread is
527 * cleared when this exception is thrown."
528 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700529 {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700530 MutexLock mu(self, *self->GetWaitMutex());
531 self->SetInterruptedLocked(false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700532 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700533 if (interruptShouldThrow) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800534 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
535 self->ThrowNewException(throw_location, "Ljava/lang/InterruptedException;", NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700536 }
537 }
538}
539
540void Monitor::Notify(Thread* self) {
541 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700542 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700543 // Make sure that we hold the lock.
544 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800545 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700546 return;
547 }
548 // Signal the first waiting thread in the wait set.
549 while (wait_set_ != NULL) {
550 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700551 wait_set_ = thread->GetWaitNext();
552 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700553
554 // Check to see if the thread is still waiting.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800555 MutexLock wait_mu(self, *thread->GetWaitMutex());
Ian Rogersdd7624d2014-03-14 17:43:00 -0700556 if (thread->GetWaitMonitor() != nullptr) {
557 thread->GetWaitConditionVariable()->Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700558 return;
559 }
560 }
561}
562
563void Monitor::NotifyAll(Thread* self) {
564 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700565 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700566 // Make sure that we hold the lock.
567 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800568 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700569 return;
570 }
571 // Signal all threads in the wait set.
572 while (wait_set_ != NULL) {
573 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700574 wait_set_ = thread->GetWaitNext();
575 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700576 thread->Notify();
577 }
578}
579
Mathieu Chartier590fee92013-09-13 13:46:47 -0700580bool Monitor::Deflate(Thread* self, mirror::Object* obj) {
581 DCHECK(obj != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700582 // Don't need volatile since we only deflate with mutators suspended.
583 LockWord lw(obj->GetLockWord(false));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700584 // If the lock isn't an inflated monitor, then we don't need to deflate anything.
585 if (lw.GetState() == LockWord::kFatLocked) {
586 Monitor* monitor = lw.FatLockMonitor();
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700587 DCHECK(monitor != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700588 MutexLock mu(self, monitor->monitor_lock_);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700589 // Can't deflate if we have anybody waiting on the CV.
590 if (monitor->num_waiters_ > 0) {
591 return false;
592 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700593 Thread* owner = monitor->owner_;
594 if (owner != nullptr) {
595 // Can't deflate if we are locked and have a hash code.
596 if (monitor->HasHashCode()) {
597 return false;
598 }
599 // Can't deflate if our lock count is too high.
600 if (monitor->lock_count_ > LockWord::kThinLockMaxCount) {
601 return false;
602 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700603 // Deflate to a thin lock.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700604 obj->SetLockWord(LockWord::FromThinLockId(owner->GetThreadId(), monitor->lock_count_), false);
605 VLOG(monitor) << "Deflated " << obj << " to thin lock " << owner->GetTid() << " / "
606 << monitor->lock_count_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700607 } else if (monitor->HasHashCode()) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700608 obj->SetLockWord(LockWord::FromHashCode(monitor->GetHashCode()), false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700609 VLOG(monitor) << "Deflated " << obj << " to hash monitor " << monitor->GetHashCode();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700610 } else {
611 // No lock and no hash, just put an empty lock word inside the object.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700612 obj->SetLockWord(LockWord(), false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700613 VLOG(monitor) << "Deflated" << obj << " to empty lock word";
Mathieu Chartier590fee92013-09-13 13:46:47 -0700614 }
615 // The monitor is deflated, mark the object as nullptr so that we know to delete it during the
616 // next GC.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700617 monitor->obj_ = GcRoot<mirror::Object>(nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700618 }
619 return true;
620}
621
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700622void Monitor::Inflate(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code) {
Andreas Gampe74240812014-04-17 10:35:09 -0700623 DCHECK(self != nullptr);
624 DCHECK(obj != nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700625 // Allocate and acquire a new monitor.
Andreas Gampe74240812014-04-17 10:35:09 -0700626 Monitor* m = MonitorPool::CreateMonitor(self, owner, obj, hash_code);
627 DCHECK(m != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700628 if (m->Install(self)) {
Haifeng Li86ab7912014-05-16 10:47:59 +0800629 if (owner != nullptr) {
630 VLOG(monitor) << "monitor: thread" << owner->GetThreadId()
Andreas Gampe74240812014-04-17 10:35:09 -0700631 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800632 } else {
633 VLOG(monitor) << "monitor: Inflate with hashcode " << hash_code
Andreas Gampe74240812014-04-17 10:35:09 -0700634 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800635 }
Andreas Gampe74240812014-04-17 10:35:09 -0700636 Runtime::Current()->GetMonitorList()->Add(m);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700637 CHECK_EQ(obj->GetLockWord(true).GetState(), LockWord::kFatLocked);
Andreas Gampe74240812014-04-17 10:35:09 -0700638 } else {
639 MonitorPool::ReleaseMonitor(self, m);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700640 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700641}
642
Mathieu Chartier0cd81352014-05-22 16:48:55 -0700643void Monitor::InflateThinLocked(Thread* self, Handle<mirror::Object> obj, LockWord lock_word,
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700644 uint32_t hash_code) {
645 DCHECK_EQ(lock_word.GetState(), LockWord::kThinLocked);
646 uint32_t owner_thread_id = lock_word.ThinLockOwner();
647 if (owner_thread_id == self->GetThreadId()) {
648 // We own the monitor, we can easily inflate it.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700649 Inflate(self, self, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700650 } else {
651 ThreadList* thread_list = Runtime::Current()->GetThreadList();
652 // Suspend the owner, inflate. First change to blocked and give up mutator_lock_.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700653 self->SetMonitorEnterObject(obj.Get());
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700654 bool timed_out;
655 Thread* owner;
656 {
657 ScopedThreadStateChange tsc(self, kBlocked);
658 owner = thread_list->SuspendThreadByThreadId(owner_thread_id, false, &timed_out);
659 }
660 if (owner != nullptr) {
661 // We succeeded in suspending the thread, check the lock's status didn't change.
662 lock_word = obj->GetLockWord(true);
663 if (lock_word.GetState() == LockWord::kThinLocked &&
664 lock_word.ThinLockOwner() == owner_thread_id) {
665 // Go ahead and inflate the lock.
666 Inflate(self, owner, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700667 }
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700668 thread_list->Resume(owner, false);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700669 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700670 self->SetMonitorEnterObject(nullptr);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700671 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700672}
673
Ian Rogers719d1a32014-03-06 12:13:39 -0800674// Fool annotalysis into thinking that the lock on obj is acquired.
675static mirror::Object* FakeLock(mirror::Object* obj)
676 EXCLUSIVE_LOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
677 return obj;
678}
679
680// Fool annotalysis into thinking that the lock on obj is release.
681static mirror::Object* FakeUnlock(mirror::Object* obj)
682 UNLOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
683 return obj;
684}
685
Mathieu Chartiere7e8a5f2014-02-14 16:59:41 -0800686mirror::Object* Monitor::MonitorEnter(Thread* self, mirror::Object* obj) {
Elliott Hughes4681c802011-09-25 18:04:37 -0700687 DCHECK(self != NULL);
688 DCHECK(obj != NULL);
Ian Rogers719d1a32014-03-06 12:13:39 -0800689 obj = FakeLock(obj);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700690 uint32_t thread_id = self->GetThreadId();
691 size_t contention_count = 0;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700692 StackHandleScope<1> hs(self);
693 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700694 while (true) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700695 LockWord lock_word = h_obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700696 switch (lock_word.GetState()) {
697 case LockWord::kUnlocked: {
698 LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0));
Ian Rogers228602f2014-07-10 02:07:54 -0700699 if (h_obj->CasLockWordWeakSequentiallyConsistent(lock_word, thin_locked)) {
Hans Boehm30359612014-05-21 17:46:23 -0700700 // CasLockWord enforces more than the acquire ordering we need here.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700701 return h_obj.Get(); // Success!
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700702 }
703 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -0700704 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700705 case LockWord::kThinLocked: {
706 uint32_t owner_thread_id = lock_word.ThinLockOwner();
707 if (owner_thread_id == thread_id) {
708 // We own the lock, increase the recursion count.
709 uint32_t new_count = lock_word.ThinLockCount() + 1;
710 if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
711 LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700712 h_obj->SetLockWord(thin_locked, true);
713 return h_obj.Get(); // Success!
Elliott Hughes5f791332011-09-15 17:45:30 -0700714 } else {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700715 // We'd overflow the recursion count, so inflate the monitor.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700716 InflateThinLocked(self, h_obj, lock_word, 0);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700717 }
718 } else {
719 // Contention.
720 contention_count++;
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700721 Runtime* runtime = Runtime::Current();
722 if (contention_count <= runtime->GetMaxSpinsBeforeThinkLockInflation()) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700723 // TODO: Consider switching the thread state to kBlocked when we are yielding.
Mathieu Chartier251755c2014-07-15 18:10:25 -0700724 // Use sched_yield instead of NanoSleep since NanoSleep can wait much longer than the
725 // parameter you pass in. This can cause thread suspension to take excessively long
Mathieu Chartierb363f662014-07-16 13:28:58 -0700726 // and make long pauses. See b/16307460.
Mathieu Chartier251755c2014-07-15 18:10:25 -0700727 sched_yield();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700728 } else {
729 contention_count = 0;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700730 InflateThinLocked(self, h_obj, lock_word, 0);
Elliott Hughes5f791332011-09-15 17:45:30 -0700731 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700732 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700733 continue; // Start from the beginning.
Elliott Hughes5f791332011-09-15 17:45:30 -0700734 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700735 case LockWord::kFatLocked: {
736 Monitor* mon = lock_word.FatLockMonitor();
737 mon->Lock(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700738 return h_obj.Get(); // Success!
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700739 }
Ian Rogers719d1a32014-03-06 12:13:39 -0800740 case LockWord::kHashCode:
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700741 // Inflate with the existing hashcode.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700742 Inflate(self, nullptr, h_obj.Get(), lock_word.GetHashCode());
Ian Rogers719d1a32014-03-06 12:13:39 -0800743 continue; // Start from the beginning.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700744 default: {
745 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700746 return h_obj.Get();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700747 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700748 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700749 }
750}
751
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800752bool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700753 DCHECK(self != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700754 DCHECK(obj != NULL);
Ian Rogers719d1a32014-03-06 12:13:39 -0800755 obj = FakeUnlock(obj);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700756 LockWord lock_word = obj->GetLockWord(true);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700757 StackHandleScope<1> hs(self);
758 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700759 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700760 case LockWord::kHashCode:
761 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700762 case LockWord::kUnlocked:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700763 FailedUnlock(h_obj.Get(), self, nullptr, nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700764 return false; // Failure.
765 case LockWord::kThinLocked: {
766 uint32_t thread_id = self->GetThreadId();
767 uint32_t owner_thread_id = lock_word.ThinLockOwner();
768 if (owner_thread_id != thread_id) {
769 // TODO: there's a race here with the owner dying while we unlock.
770 Thread* owner =
771 Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700772 FailedUnlock(h_obj.Get(), self, owner, nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700773 return false; // Failure.
774 } else {
775 // We own the lock, decrease the recursion count.
776 if (lock_word.ThinLockCount() != 0) {
777 uint32_t new_count = lock_word.ThinLockCount() - 1;
778 LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700779 h_obj->SetLockWord(thin_locked, true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700780 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700781 h_obj->SetLockWord(LockWord(), true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700782 }
783 return true; // Success!
784 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700785 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700786 case LockWord::kFatLocked: {
787 Monitor* mon = lock_word.FatLockMonitor();
788 return mon->Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700789 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700790 default: {
791 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700792 return false;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700793 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700794 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700795}
796
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800797void Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800798 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700799 DCHECK(self != nullptr);
800 DCHECK(obj != nullptr);
801 LockWord lock_word = obj->GetLockWord(true);
Ian Rogers43c69cc2014-08-15 11:09:28 -0700802 while (lock_word.GetState() != LockWord::kFatLocked) {
803 switch (lock_word.GetState()) {
804 case LockWord::kHashCode:
805 // Fall-through.
806 case LockWord::kUnlocked:
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700807 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
808 return; // Failure.
Ian Rogers43c69cc2014-08-15 11:09:28 -0700809 case LockWord::kThinLocked: {
810 uint32_t thread_id = self->GetThreadId();
811 uint32_t owner_thread_id = lock_word.ThinLockOwner();
812 if (owner_thread_id != thread_id) {
813 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
814 return; // Failure.
815 } else {
816 // We own the lock, inflate to enqueue ourself on the Monitor. May fail spuriously so
817 // re-load.
818 Inflate(self, self, obj, 0);
819 lock_word = obj->GetLockWord(true);
820 }
821 break;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700822 }
Ian Rogers43c69cc2014-08-15 11:09:28 -0700823 case LockWord::kFatLocked: // Unreachable given the loop condition above. Fall-through.
824 default: {
825 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
826 return;
827 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700828 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700829 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700830 Monitor* mon = lock_word.FatLockMonitor();
831 mon->Wait(self, ms, ns, interruptShouldThrow, why);
Elliott Hughes5f791332011-09-15 17:45:30 -0700832}
833
Ian Rogers13c479e2013-10-11 07:59:01 -0700834void Monitor::DoNotify(Thread* self, mirror::Object* obj, bool notify_all) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700835 DCHECK(self != nullptr);
836 DCHECK(obj != nullptr);
837 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700838 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700839 case LockWord::kHashCode:
840 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700841 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800842 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700843 return; // Failure.
844 case LockWord::kThinLocked: {
845 uint32_t thread_id = self->GetThreadId();
846 uint32_t owner_thread_id = lock_word.ThinLockOwner();
847 if (owner_thread_id != thread_id) {
848 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
849 return; // Failure.
850 } else {
851 // We own the lock but there's no Monitor and therefore no waiters.
852 return; // Success.
853 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700854 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700855 case LockWord::kFatLocked: {
856 Monitor* mon = lock_word.FatLockMonitor();
857 if (notify_all) {
858 mon->NotifyAll(self);
859 } else {
860 mon->Notify(self);
861 }
862 return; // Success.
863 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700864 default: {
865 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
866 return;
867 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700868 }
869}
870
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700871uint32_t Monitor::GetLockOwnerThreadId(mirror::Object* obj) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700872 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:
878 return ThreadList::kInvalidThreadId;
879 case LockWord::kThinLocked:
880 return lock_word.ThinLockOwner();
881 case LockWord::kFatLocked: {
882 Monitor* mon = lock_word.FatLockMonitor();
883 return mon->GetOwnerThreadId();
Elliott Hughes5f791332011-09-15 17:45:30 -0700884 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700885 default: {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700886 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -0700887 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700888 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700889 }
890}
891
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700892void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
Ian Rogersd803bc72014-04-01 15:33:03 -0700893 // Determine the wait message and object we're waiting or blocked upon.
894 mirror::Object* pretty_object = nullptr;
895 const char* wait_message = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700896 uint32_t lock_owner = ThreadList::kInvalidThreadId;
Ian Rogersd803bc72014-04-01 15:33:03 -0700897 ThreadState state = thread->GetState();
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800898 if (state == kWaiting || state == kTimedWaiting || state == kSleeping) {
Ian Rogersd803bc72014-04-01 15:33:03 -0700899 wait_message = (state == kSleeping) ? " - sleeping on " : " - waiting on ";
900 Thread* self = Thread::Current();
901 MutexLock mu(self, *thread->GetWaitMutex());
902 Monitor* monitor = thread->GetWaitMonitor();
903 if (monitor != nullptr) {
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700904 pretty_object = monitor->GetObject();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700905 }
Elliott Hughes34e06962012-04-09 13:55:55 -0700906 } else if (state == kBlocked) {
Ian Rogersd803bc72014-04-01 15:33:03 -0700907 wait_message = " - waiting to lock ";
908 pretty_object = thread->GetMonitorEnterObject();
909 if (pretty_object != nullptr) {
910 lock_owner = pretty_object->GetLockOwnerThreadId();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700911 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700912 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700913
Ian Rogersd803bc72014-04-01 15:33:03 -0700914 if (wait_message != nullptr) {
915 if (pretty_object == nullptr) {
916 os << wait_message << "an unknown object";
917 } else {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700918 if ((pretty_object->GetLockWord(true).GetState() == LockWord::kThinLocked) &&
Ian Rogersd803bc72014-04-01 15:33:03 -0700919 Locks::mutator_lock_->IsExclusiveHeld(Thread::Current())) {
920 // Getting the identity hashcode here would result in lock inflation and suspension of the
921 // current thread, which isn't safe if this is the only runnable thread.
922 os << wait_message << StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)",
923 reinterpret_cast<intptr_t>(pretty_object),
924 PrettyTypeOf(pretty_object).c_str());
925 } else {
926 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
927 os << wait_message << StringPrintf("<0x%08x> (a %s)", pretty_object->IdentityHashCode(),
928 PrettyTypeOf(pretty_object).c_str());
929 }
930 }
931 // - waiting to lock <0x613f83d8> (a java.lang.Object) held by thread 5
932 if (lock_owner != ThreadList::kInvalidThreadId) {
933 os << " held by thread " << lock_owner;
934 }
935 os << "\n";
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700936 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700937}
938
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800939mirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800940 // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
941 // definition of contended that includes a monitor a thread is trying to enter...
Ian Rogersdd7624d2014-03-14 17:43:00 -0700942 mirror::Object* result = thread->GetMonitorEnterObject();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700943 if (result == NULL) {
944 // ...but also a monitor that the thread is waiting on.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700945 MutexLock mu(Thread::Current(), *thread->GetWaitMutex());
946 Monitor* monitor = thread->GetWaitMonitor();
Elliott Hughesf9501702013-01-11 11:22:27 -0800947 if (monitor != NULL) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700948 result = monitor->GetObject();
Elliott Hughesf9501702013-01-11 11:22:27 -0800949 }
950 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700951 return result;
Elliott Hughesf9501702013-01-11 11:22:27 -0800952}
953
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800954void Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
Andreas Gampe760172c2014-08-16 13:41:10 -0700955 void* callback_context, bool abort_on_failure) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700956 mirror::ArtMethod* m = stack_visitor->GetMethod();
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700957 CHECK(m != NULL);
958
959 // Native methods are an easy special case.
960 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
961 if (m->IsNative()) {
962 if (m->IsSynchronized()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700963 mirror::Object* jni_this = stack_visitor->GetCurrentHandleScope()->GetReference(0);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800964 callback(jni_this, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700965 }
966 return;
967 }
968
jeffhao61f916c2012-10-25 17:48:51 -0700969 // Proxy methods should not be synchronized.
970 if (m->IsProxyMethod()) {
971 CHECK(!m->IsSynchronized());
972 return;
973 }
974
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700975 // Is there any reason to believe there's any synchronization in this method?
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700976 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -0700977 CHECK(code_item != NULL) << PrettyMethod(m);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700978 if (code_item->tries_size_ == 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700979 return; // No "tries" implies no synchronization, so no held locks to report.
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700980 }
981
Andreas Gampe760172c2014-08-16 13:41:10 -0700982 // Get the dex pc. If abort_on_failure is false, GetDexPc will not abort in the case it cannot
983 // find the dex pc, and instead return kDexNoIndex. Then bail out, as it indicates we have an
984 // inconsistent stack anyways.
985 uint32_t dex_pc = stack_visitor->GetDexPc(abort_on_failure);
986 if (!abort_on_failure && dex_pc == DexFile::kDexNoIndex) {
987 LOG(ERROR) << "Could not find dex_pc for " << PrettyMethod(m);
988 return;
989 }
990
Elliott Hughes80537bb2013-01-04 16:37:26 -0800991 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
992 // the locks held in this stack frame.
993 std::vector<uint32_t> monitor_enter_dex_pcs;
Andreas Gampe760172c2014-08-16 13:41:10 -0700994 verifier::MethodVerifier::FindLocksAtDexPc(m, dex_pc, &monitor_enter_dex_pcs);
Elliott Hughes80537bb2013-01-04 16:37:26 -0800995 if (monitor_enter_dex_pcs.empty()) {
996 return;
997 }
998
Elliott Hughes80537bb2013-01-04 16:37:26 -0800999 for (size_t i = 0; i < monitor_enter_dex_pcs.size(); ++i) {
1000 // The verifier works in terms of the dex pcs of the monitor-enter instructions.
1001 // We want the registers used by those instructions (so we can read the values out of them).
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001002 uint32_t monitor_dex_pc = monitor_enter_dex_pcs[i];
1003 uint16_t monitor_enter_instruction = code_item->insns_[monitor_dex_pc];
Elliott Hughes80537bb2013-01-04 16:37:26 -08001004
1005 // Quick sanity check.
1006 if ((monitor_enter_instruction & 0xff) != Instruction::MONITOR_ENTER) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001007 LOG(FATAL) << "expected monitor-enter @" << monitor_dex_pc << "; was "
Elliott Hughes80537bb2013-01-04 16:37:26 -08001008 << reinterpret_cast<void*>(monitor_enter_instruction);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001009 }
1010
Elliott Hughes80537bb2013-01-04 16:37:26 -08001011 uint16_t monitor_register = ((monitor_enter_instruction >> 8) & 0xff);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001012 mirror::Object* o = reinterpret_cast<mirror::Object*>(stack_visitor->GetVReg(m, monitor_register,
1013 kReferenceVReg));
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001014 callback(o, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001015 }
1016}
1017
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001018bool Monitor::IsValidLockWord(LockWord lock_word) {
1019 switch (lock_word.GetState()) {
1020 case LockWord::kUnlocked:
1021 // Nothing to check.
1022 return true;
1023 case LockWord::kThinLocked:
1024 // Basic sanity check of owner.
1025 return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
1026 case LockWord::kFatLocked: {
1027 // Check the monitor appears in the monitor list.
1028 Monitor* mon = lock_word.FatLockMonitor();
1029 MonitorList* list = Runtime::Current()->GetMonitorList();
1030 MutexLock mu(Thread::Current(), list->monitor_list_lock_);
1031 for (Monitor* list_mon : list->list_) {
1032 if (mon == list_mon) {
1033 return true; // Found our monitor.
1034 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001035 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001036 return false; // Fail - unowned monitor in an object.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001037 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001038 case LockWord::kHashCode:
1039 return true;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001040 default:
1041 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001042 UNREACHABLE();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001043 }
1044}
1045
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001046bool Monitor::IsLocked() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1047 MutexLock mu(Thread::Current(), monitor_lock_);
1048 return owner_ != nullptr;
1049}
1050
Ian Rogersef7d42f2014-01-06 12:55:46 -08001051void Monitor::TranslateLocation(mirror::ArtMethod* method, uint32_t dex_pc,
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001052 const char** source_file, uint32_t* line_number) const {
jeffhao33dc7712011-11-09 17:54:24 -08001053 // If method is null, location is unknown
1054 if (method == NULL) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001055 *source_file = "";
1056 *line_number = 0;
jeffhao33dc7712011-11-09 17:54:24 -08001057 return;
1058 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001059 *source_file = method->GetDeclaringClassSourceFile();
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001060 if (*source_file == NULL) {
1061 *source_file = "";
Elliott Hughes12c51e32012-01-17 20:25:05 -08001062 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001063 *line_number = method->GetLineNumFromDexPC(dex_pc);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001064}
1065
1066uint32_t Monitor::GetOwnerThreadId() {
1067 MutexLock mu(Thread::Current(), monitor_lock_);
1068 Thread* owner = owner_;
1069 if (owner != NULL) {
1070 return owner->GetThreadId();
1071 } else {
1072 return ThreadList::kInvalidThreadId;
1073 }
jeffhao33dc7712011-11-09 17:54:24 -08001074}
1075
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001076MonitorList::MonitorList()
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001077 : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock", kMonitorListLock),
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001078 monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001079}
1080
1081MonitorList::~MonitorList() {
Andreas Gampe74240812014-04-17 10:35:09 -07001082 Thread* self = Thread::Current();
1083 MutexLock mu(self, monitor_list_lock_);
1084 // Release all monitors to the pool.
1085 // TODO: Is it an invariant that *all* open monitors are in the list? Then we could
1086 // clear faster in the pool.
1087 MonitorPool::ReleaseMonitors(self, &list_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001088}
1089
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001090void MonitorList::DisallowNewMonitors() {
Ian Rogers50b35e22012-10-04 10:09:15 -07001091 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001092 allow_new_monitors_ = false;
1093}
1094
1095void MonitorList::AllowNewMonitors() {
1096 Thread* self = Thread::Current();
1097 MutexLock mu(self, monitor_list_lock_);
1098 allow_new_monitors_ = true;
1099 monitor_add_condition_.Broadcast(self);
1100}
1101
1102void MonitorList::Add(Monitor* m) {
1103 Thread* self = Thread::Current();
1104 MutexLock mu(self, monitor_list_lock_);
1105 while (UNLIKELY(!allow_new_monitors_)) {
1106 monitor_add_condition_.WaitHoldingLocks(self);
1107 }
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001108 list_.push_front(m);
1109}
1110
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08001111void MonitorList::SweepMonitorList(IsMarkedCallback* callback, void* arg) {
Andreas Gampe74240812014-04-17 10:35:09 -07001112 Thread* self = Thread::Current();
1113 MutexLock mu(self, monitor_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001114 for (auto it = list_.begin(); it != list_.end(); ) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001115 Monitor* m = *it;
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001116 // Disable the read barrier in GetObject() as this is called by GC.
1117 mirror::Object* obj = m->GetObject<kWithoutReadBarrier>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001118 // The object of a monitor can be null if we have deflated it.
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08001119 mirror::Object* new_obj = obj != nullptr ? callback(obj, arg) : nullptr;
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001120 if (new_obj == nullptr) {
1121 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001122 << obj;
Andreas Gampe74240812014-04-17 10:35:09 -07001123 MonitorPool::ReleaseMonitor(self, m);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001124 it = list_.erase(it);
1125 } else {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001126 m->SetObject(new_obj);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001127 ++it;
1128 }
1129 }
1130}
1131
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001132struct MonitorDeflateArgs {
1133 MonitorDeflateArgs() : self(Thread::Current()), deflate_count(0) {}
1134 Thread* const self;
1135 size_t deflate_count;
1136};
1137
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001138static mirror::Object* MonitorDeflateCallback(mirror::Object* object, void* arg)
1139 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001140 MonitorDeflateArgs* args = reinterpret_cast<MonitorDeflateArgs*>(arg);
1141 if (Monitor::Deflate(args->self, object)) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001142 DCHECK_NE(object->GetLockWord(true).GetState(), LockWord::kFatLocked);
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001143 ++args->deflate_count;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001144 // If we deflated, return nullptr so that the monitor gets removed from the array.
1145 return nullptr;
1146 }
1147 return object; // Monitor was not deflated.
1148}
1149
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001150size_t MonitorList::DeflateMonitors() {
1151 MonitorDeflateArgs args;
1152 Locks::mutator_lock_->AssertExclusiveHeld(args.self);
1153 SweepMonitorList(MonitorDeflateCallback, &args);
1154 return args.deflate_count;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001155}
1156
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001157MonitorInfo::MonitorInfo(mirror::Object* obj) : owner_(NULL), entry_count_(0) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001158 DCHECK(obj != nullptr);
1159 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001160 switch (lock_word.GetState()) {
1161 case LockWord::kUnlocked:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001162 // Fall-through.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001163 case LockWord::kForwardingAddress:
1164 // Fall-through.
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001165 case LockWord::kHashCode:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001166 break;
1167 case LockWord::kThinLocked:
1168 owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
1169 entry_count_ = 1 + lock_word.ThinLockCount();
1170 // Thin locks have no waiters.
1171 break;
1172 case LockWord::kFatLocked: {
1173 Monitor* mon = lock_word.FatLockMonitor();
1174 owner_ = mon->owner_;
1175 entry_count_ = 1 + mon->lock_count_;
Ian Rogersdd7624d2014-03-14 17:43:00 -07001176 for (Thread* waiter = mon->wait_set_; waiter != NULL; waiter = waiter->GetWaitNext()) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001177 waiters_.push_back(waiter);
1178 }
1179 break;
Elliott Hughesf327e072013-01-09 16:01:26 -08001180 }
1181 }
1182}
1183
Elliott Hughes5f791332011-09-15 17:45:30 -07001184} // namespace art