blob: 4b412253f3b6563bc9725fa87cd467ee401310ea [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
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -080019#define ATRACE_TAG ATRACE_TAG_DALVIK
20
21#include <cutils/trace.h>
Elliott Hughes08fc03a2012-06-26 17:34:00 -070022#include <vector>
23
Elliott Hughes76b61672012-12-12 17:47:30 -080024#include "base/mutex.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080025#include "base/stl_util.h"
jeffhao33dc7712011-11-09 17:54:24 -080026#include "class_linker.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070027#include "dex_file-inl.h"
Elliott Hughes08fc03a2012-06-26 17:34:00 -070028#include "dex_instruction.h"
Ian Rogersd9c4fc92013-10-01 19:45:43 -070029#include "lock_word-inl.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070030#include "mirror/art_method-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070031#include "mirror/class-inl.h"
Ian Rogers05f30572013-02-20 12:13:11 -080032#include "mirror/object-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080033#include "mirror/object_array-inl.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070034#include "scoped_thread_state_change.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070035#include "thread.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070036#include "thread_list.h"
Elliott Hughes08fc03a2012-06-26 17:34:00 -070037#include "verifier/method_verifier.h"
Elliott Hughes044288f2012-06-25 14:46:39 -070038#include "well_known_classes.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070039
40namespace art {
41
Mathieu Chartierb9001ab2014-10-03 13:28:46 -070042static constexpr uint64_t kLongWaitMs = 100;
43
Elliott Hughes5f791332011-09-15 17:45:30 -070044/*
Ian Rogersd9c4fc92013-10-01 19:45:43 -070045 * Every Object has a monitor associated with it, but not every Object is actually locked. Even
46 * the ones that are locked do not need a full-fledged monitor until a) there is actual contention
47 * or b) wait() is called on the Object.
Elliott Hughes5f791332011-09-15 17:45:30 -070048 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070049 * For Android, we have implemented a scheme similar to the one described in Bacon et al.'s
50 * "Thin locks: featherweight synchronization for Java" (ACM 1998). Things are even easier for us,
51 * though, because we have a full 32 bits to work with.
Elliott Hughes5f791332011-09-15 17:45:30 -070052 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070053 * The two states of an Object's lock are referred to as "thin" and "fat". A lock may transition
54 * from the "thin" state to the "fat" state and this transition is referred to as inflation. Once
55 * a lock has been inflated it remains in the "fat" state indefinitely.
Elliott Hughes5f791332011-09-15 17:45:30 -070056 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070057 * The lock value itself is stored in mirror::Object::monitor_ and the representation is described
58 * in the LockWord value type.
Elliott Hughes54e7df12011-09-16 11:47:04 -070059 *
Elliott Hughes5f791332011-09-15 17:45:30 -070060 * Monitors provide:
61 * - mutually exclusive access to resources
62 * - a way for multiple threads to wait for notification
63 *
64 * In effect, they fill the role of both mutexes and condition variables.
65 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070066 * Only one thread can own the monitor at any time. There may be several threads waiting on it
67 * (the wait call unlocks it). One or more waiting threads may be getting interrupted or notified
68 * at any given time.
Elliott Hughes5f791332011-09-15 17:45:30 -070069 */
Elliott Hughes54e7df12011-09-16 11:47:04 -070070
Mathieu Chartier2cebb242015-04-21 16:50:40 -070071bool (*Monitor::is_sensitive_thread_hook_)() = nullptr;
Elliott Hughesfc861622011-10-17 17:57:47 -070072uint32_t Monitor::lock_profiling_threshold_ = 0;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070073
Elliott Hughesfc861622011-10-17 17:57:47 -070074bool Monitor::IsSensitiveThread() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070075 if (is_sensitive_thread_hook_ != nullptr) {
Elliott Hughesfc861622011-10-17 17:57:47 -070076 return (*is_sensitive_thread_hook_)();
77 }
78 return false;
79}
80
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -080081void Monitor::Init(uint32_t lock_profiling_threshold, bool (*is_sensitive_thread_hook)()) {
Elliott Hughesfc861622011-10-17 17:57:47 -070082 lock_profiling_threshold_ = lock_profiling_threshold;
83 is_sensitive_thread_hook_ = is_sensitive_thread_hook;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070084}
85
Ian Rogersef7d42f2014-01-06 12:55:46 -080086Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code)
Ian Rogers00f7d0e2012-07-19 15:28:27 -070087 : monitor_lock_("a monitor lock", kMonitorLock),
Ian Rogersd9c4fc92013-10-01 19:45:43 -070088 monitor_contenders_("monitor contenders", monitor_lock_),
Mathieu Chartier46bc7782013-11-12 17:03:02 -080089 num_waiters_(0),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070090 owner_(owner),
Elliott Hughes5f791332011-09-15 17:45:30 -070091 lock_count_(0),
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070092 obj_(GcRoot<mirror::Object>(obj)),
Mathieu Chartier2cebb242015-04-21 16:50:40 -070093 wait_set_(nullptr),
Mathieu Chartierad2541a2013-10-25 10:05:23 -070094 hash_code_(hash_code),
Mathieu Chartier2cebb242015-04-21 16:50:40 -070095 locking_method_(nullptr),
Ian Rogersef7d42f2014-01-06 12:55:46 -080096 locking_dex_pc_(0),
Andreas Gampe74240812014-04-17 10:35:09 -070097 monitor_id_(MonitorPool::ComputeMonitorId(this, self)) {
98#ifdef __LP64__
99 DCHECK(false) << "Should not be reached in 64b";
100 next_free_ = nullptr;
101#endif
102 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
103 // with the owner unlocking the thin-lock.
104 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
105 // The identity hash code is set for the life time of the monitor.
106}
107
108Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code,
109 MonitorId id)
110 : monitor_lock_("a monitor lock", kMonitorLock),
111 monitor_contenders_("monitor contenders", monitor_lock_),
112 num_waiters_(0),
113 owner_(owner),
114 lock_count_(0),
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700115 obj_(GcRoot<mirror::Object>(obj)),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700116 wait_set_(nullptr),
Andreas Gampe74240812014-04-17 10:35:09 -0700117 hash_code_(hash_code),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700118 locking_method_(nullptr),
Andreas Gampe74240812014-04-17 10:35:09 -0700119 locking_dex_pc_(0),
120 monitor_id_(id) {
121#ifdef __LP64__
122 next_free_ = nullptr;
123#endif
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700124 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
125 // with the owner unlocking the thin-lock.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800126 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700127 // The identity hash code is set for the life time of the monitor.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700128}
129
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700130int32_t Monitor::GetHashCode() {
131 while (!HasHashCode()) {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700132 if (hash_code_.CompareExchangeWeakRelaxed(0, mirror::Object::GenerateIdentityHashCode())) {
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700133 break;
134 }
135 }
136 DCHECK(HasHashCode());
Ian Rogers3e5cf302014-05-20 16:40:37 -0700137 return hash_code_.LoadRelaxed();
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700138}
139
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700140bool Monitor::Install(Thread* self) {
141 MutexLock mu(self, monitor_lock_); // Uncontended mutex acquisition as monitor isn't yet public.
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700142 CHECK(owner_ == nullptr || owner_ == self || owner_->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700143 // Propagate the lock state.
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700144 LockWord lw(GetObject()->GetLockWord(false));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700145 switch (lw.GetState()) {
146 case LockWord::kThinLocked: {
147 CHECK_EQ(owner_->GetThreadId(), lw.ThinLockOwner());
148 lock_count_ = lw.ThinLockCount();
149 break;
150 }
151 case LockWord::kHashCode: {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700152 CHECK_EQ(hash_code_.LoadRelaxed(), static_cast<int32_t>(lw.GetHashCode()));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700153 break;
154 }
155 case LockWord::kFatLocked: {
156 // The owner_ is suspended but another thread beat us to install a monitor.
157 return false;
158 }
159 case LockWord::kUnlocked: {
160 LOG(FATAL) << "Inflating unlocked lock word";
161 break;
162 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700163 default: {
164 LOG(FATAL) << "Invalid monitor state " << lw.GetState();
165 return false;
166 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700167 }
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800168 LockWord fat(this, lw.ReadBarrierState());
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700169 // Publish the updated lock word, which may race with other threads.
Ian Rogers228602f2014-07-10 02:07:54 -0700170 bool success = GetObject()->CasLockWordWeakSequentiallyConsistent(lw, fat);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700171 // Lock profiling.
Mathieu Chartier9728f912013-10-30 09:45:13 -0700172 if (success && owner_ != nullptr && lock_profiling_threshold_ != 0) {
Andreas Gampe6ec8ebd2014-07-25 13:36:56 -0700173 // Do not abort on dex pc errors. This can easily happen when we want to dump a stack trace on
174 // abort.
175 locking_method_ = owner_->GetCurrentMethod(&locking_dex_pc_, false);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700176 }
177 return success;
Elliott Hughes5f791332011-09-15 17:45:30 -0700178}
179
180Monitor::~Monitor() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700181 // Deflated monitors have a null object.
Elliott Hughes5f791332011-09-15 17:45:30 -0700182}
183
Elliott Hughes5f791332011-09-15 17:45:30 -0700184void Monitor::AppendToWaitSet(Thread* thread) {
185 DCHECK(owner_ == Thread::Current());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700186 DCHECK(thread != nullptr);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700187 DCHECK(thread->GetWaitNext() == nullptr) << thread->GetWaitNext();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700188 if (wait_set_ == nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700189 wait_set_ = thread;
190 return;
191 }
192
193 // push_back.
194 Thread* t = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700195 while (t->GetWaitNext() != nullptr) {
196 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700197 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700198 t->SetWaitNext(thread);
Elliott Hughes5f791332011-09-15 17:45:30 -0700199}
200
Elliott Hughes5f791332011-09-15 17:45:30 -0700201void Monitor::RemoveFromWaitSet(Thread *thread) {
202 DCHECK(owner_ == Thread::Current());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700203 DCHECK(thread != nullptr);
204 if (wait_set_ == nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700205 return;
206 }
207 if (wait_set_ == thread) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700208 wait_set_ = thread->GetWaitNext();
209 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700210 return;
211 }
212
213 Thread* t = wait_set_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700214 while (t->GetWaitNext() != nullptr) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700215 if (t->GetWaitNext() == thread) {
216 t->SetWaitNext(thread->GetWaitNext());
217 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700218 return;
219 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700220 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700221 }
222}
223
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700224void Monitor::SetObject(mirror::Object* object) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700225 obj_ = GcRoot<mirror::Object>(object);
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700226}
227
Elliott Hughes5f791332011-09-15 17:45:30 -0700228void Monitor::Lock(Thread* self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700229 MutexLock mu(self, monitor_lock_);
230 while (true) {
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700231 if (owner_ == nullptr) { // Unowned.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700232 owner_ = self;
233 CHECK_EQ(lock_count_, 0);
234 // When debugging, save the current monitor holder for future
235 // acquisition failures to use in sampled logging.
236 if (lock_profiling_threshold_ != 0) {
237 locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
238 }
239 return;
240 } else if (owner_ == self) { // Recursive.
241 lock_count_++;
242 return;
243 }
244 // Contended.
245 const bool log_contention = (lock_profiling_threshold_ != 0);
Xin Guanb894a192014-08-22 11:55:37 -0500246 uint64_t wait_start_ms = log_contention ? MilliTime() : 0;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800247 mirror::ArtMethod* owners_method = locking_method_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700248 uint32_t owners_dex_pc = locking_dex_pc_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700249 // Do this before releasing the lock so that we don't get deflated.
Mathieu Chartierb9001ab2014-10-03 13:28:46 -0700250 size_t num_waiters = num_waiters_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700251 ++num_waiters_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700252 monitor_lock_.Unlock(self); // Let go of locks in order.
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700253 self->SetMonitorEnterObject(GetObject());
Elliott Hughes5f791332011-09-15 17:45:30 -0700254 {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700255 ScopedThreadStateChange tsc(self, kBlocked); // Change to blocked and give up mutator_lock_.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700256 // Reacquire monitor_lock_ without mutator_lock_ for Wait.
257 MutexLock mu2(self, monitor_lock_);
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800258 if (owner_ != nullptr) { // Did the owner_ give the lock up?
259 if (ATRACE_ENABLED()) {
260 std::string name;
261 owner_->GetThreadName(name);
262 ATRACE_BEGIN(("Contended on monitor with owner " + name).c_str());
263 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700264 monitor_contenders_.Wait(self); // Still contended so wait.
265 // Woken from contention.
266 if (log_contention) {
267 uint64_t wait_ms = MilliTime() - wait_start_ms;
268 uint32_t sample_percent;
269 if (wait_ms >= lock_profiling_threshold_) {
270 sample_percent = 100;
271 } else {
272 sample_percent = 100 * wait_ms / lock_profiling_threshold_;
273 }
274 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
275 const char* owners_filename;
276 uint32_t owners_line_number;
277 TranslateLocation(owners_method, owners_dex_pc, &owners_filename, &owners_line_number);
Mathieu Chartierb9001ab2014-10-03 13:28:46 -0700278 if (wait_ms > kLongWaitMs && owners_method != nullptr) {
279 LOG(WARNING) << "Long monitor contention event with owner method="
280 << PrettyMethod(owners_method) << " from " << owners_filename << ":"
281 << owners_line_number << " waiters=" << num_waiters << " for "
282 << PrettyDuration(MsToNs(wait_ms));
283 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700284 LogContentionEvent(self, wait_ms, sample_percent, owners_filename, owners_line_number);
285 }
286 }
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800287 ATRACE_END();
Elliott Hughesfc861622011-10-17 17:57:47 -0700288 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700289 }
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700290 self->SetMonitorEnterObject(nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700291 monitor_lock_.Lock(self); // Reacquire locks in order.
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700292 --num_waiters_;
Elliott Hughesfc861622011-10-17 17:57:47 -0700293 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700294}
295
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800296static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
297 __attribute__((format(printf, 1, 2)));
298
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700299static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700300 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800301 va_list args;
302 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800303 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000304 self->ThrowNewExceptionV("Ljava/lang/IllegalMonitorStateException;", fmt, args);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700305 if (!Runtime::Current()->IsStarted() || VLOG_IS_ON(monitor)) {
Brian Carlstrom64277f32012-03-26 23:53:34 -0700306 std::ostringstream ss;
Ian Rogers62d6c772013-02-27 08:32:07 -0800307 self->Dump(ss);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700308 LOG(Runtime::Current()->IsStarted() ? INFO : ERROR)
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000309 << self->GetException()->Dump() << "\n" << ss.str();
Brian Carlstrom64277f32012-03-26 23:53:34 -0700310 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800311 va_end(args);
312}
313
Elliott Hughesd4237412012-02-21 11:24:45 -0800314static std::string ThreadToString(Thread* thread) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700315 if (thread == nullptr) {
316 return "nullptr";
Elliott Hughesd4237412012-02-21 11:24:45 -0800317 }
318 std::ostringstream oss;
319 // TODO: alternatively, we could just return the thread's name.
320 oss << *thread;
321 return oss.str();
322}
323
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800324void Monitor::FailedUnlock(mirror::Object* o, Thread* expected_owner, Thread* found_owner,
Elliott Hughesffb465f2012-03-01 18:46:05 -0800325 Monitor* monitor) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700326 Thread* current_owner = nullptr;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800327 std::string current_owner_string;
328 std::string expected_owner_string;
329 std::string found_owner_string;
330 {
331 // TODO: isn't this too late to prevent threads from disappearing?
332 // Acquire thread list lock so threads won't disappear from under us.
Ian Rogers50b35e22012-10-04 10:09:15 -0700333 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Elliott Hughesffb465f2012-03-01 18:46:05 -0800334 // Re-read owner now that we hold lock.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700335 current_owner = (monitor != nullptr) ? monitor->GetOwner() : nullptr;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800336 // Get short descriptions of the threads involved.
337 current_owner_string = ThreadToString(current_owner);
338 expected_owner_string = ThreadToString(expected_owner);
339 found_owner_string = ThreadToString(found_owner);
340 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700341 if (current_owner == nullptr) {
342 if (found_owner == nullptr) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800343 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
344 " on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800345 PrettyTypeOf(o).c_str(),
346 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800347 } else {
348 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800349 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
350 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800351 found_owner_string.c_str(),
352 PrettyTypeOf(o).c_str(),
353 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800354 }
355 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700356 if (found_owner == nullptr) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800357 // Race: originally there was no owner, there is now
358 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
359 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800360 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 if (found_owner != current_owner) {
365 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800366 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
367 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800368 found_owner_string.c_str(),
369 current_owner_string.c_str(),
370 PrettyTypeOf(o).c_str(),
371 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800372 } else {
373 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
374 " on thread '%s",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800375 current_owner_string.c_str(),
376 PrettyTypeOf(o).c_str(),
377 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800378 }
379 }
380 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700381}
382
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700383bool Monitor::Unlock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700384 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700385 MutexLock mu(self, monitor_lock_);
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800386 Thread* owner = owner_;
387 if (owner == self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700388 // We own the monitor, so nobody else can be in here.
389 if (lock_count_ == 0) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700390 owner_ = nullptr;
391 locking_method_ = nullptr;
Ian Rogers0399dde2012-06-06 17:09:28 -0700392 locking_dex_pc_ = 0;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700393 // Wake a contender.
394 monitor_contenders_.Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700395 } else {
396 --lock_count_;
397 }
398 } else {
399 // We don't own this, so we're not allowed to unlock it.
400 // The JNI spec says that we should throw IllegalMonitorStateException
401 // in this case.
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700402 FailedUnlock(GetObject(), self, owner, this);
Elliott Hughes5f791332011-09-15 17:45:30 -0700403 return false;
404 }
405 return true;
406}
407
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800408void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
409 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700410 DCHECK(self != nullptr);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800411 DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
Elliott Hughes5f791332011-09-15 17:45:30 -0700412
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700413 monitor_lock_.Lock(self);
414
Elliott Hughes5f791332011-09-15 17:45:30 -0700415 // Make sure that we hold the lock.
416 if (owner_ != self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700417 monitor_lock_.Unlock(self);
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700418 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700419 return;
420 }
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800421
Elliott Hughesdf42c482013-01-09 12:49:02 -0800422 // We need to turn a zero-length timed wait into a regular wait because
423 // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
424 if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
425 why = kWaiting;
426 }
427
Elliott Hughes5f791332011-09-15 17:45:30 -0700428 // Enforce the timeout range.
429 if (ms < 0 || ns < 0 || ns > 999999) {
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700430 monitor_lock_.Unlock(self);
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000431 self->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
Ian Rogersef7d42f2014-01-06 12:55:46 -0800432 "timeout arguments out of range: ms=%" PRId64 " ns=%d", ms, ns);
Elliott Hughes5f791332011-09-15 17:45:30 -0700433 return;
434 }
435
Elliott Hughes5f791332011-09-15 17:45:30 -0700436 /*
437 * Add ourselves to the set of threads waiting on this monitor, and
438 * release our hold. We need to let it go even if we're a few levels
439 * deep in a recursive lock, and we need to restore that later.
440 *
441 * We append to the wait set ahead of clearing the count and owner
442 * fields so the subroutine can check that the calling thread owns
443 * the monitor. Aside from that, the order of member updates is
444 * not order sensitive as we hold the pthread mutex.
445 */
446 AppendToWaitSet(self);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700447 ++num_waiters_;
Ian Rogers0399dde2012-06-06 17:09:28 -0700448 int prev_lock_count = lock_count_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700449 lock_count_ = 0;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700450 owner_ = nullptr;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800451 mirror::ArtMethod* saved_method = locking_method_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700452 locking_method_ = nullptr;
Ian Rogers0399dde2012-06-06 17:09:28 -0700453 uintptr_t saved_dex_pc = locking_dex_pc_;
454 locking_dex_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700455
456 /*
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800457 * Update thread state. If the GC wakes up, it'll ignore us, knowing
Elliott Hughes5f791332011-09-15 17:45:30 -0700458 * that we won't touch any references in this state, and we'll check
459 * our suspend mode before we transition out.
460 */
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800461 self->TransitionFromRunnableToSuspended(why);
Elliott Hughes5f791332011-09-15 17:45:30 -0700462
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800463 bool was_interrupted = false;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700464 {
465 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700466 MutexLock mu(self, *self->GetWaitMutex());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700467
468 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700469 // non-null a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700470 // up.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700471 DCHECK(self->GetWaitMonitor() == nullptr);
472 self->SetWaitMonitor(this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700473
474 // Release the monitor lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700475 monitor_contenders_.Signal(self);
476 monitor_lock_.Unlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700477
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800478 // Handle the case where the thread was interrupted before we called wait().
Ian Rogersdd7624d2014-03-14 17:43:00 -0700479 if (self->IsInterruptedLocked()) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800480 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700481 } else {
482 // Wait for a notification or a timeout to occur.
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800483 if (why == kWaiting) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700484 self->GetWaitConditionVariable()->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700485 } else {
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800486 DCHECK(why == kTimedWaiting || why == kSleeping) << why;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700487 self->GetWaitConditionVariable()->TimedWait(self, ms, ns);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700488 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700489 if (self->IsInterruptedLocked()) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800490 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700491 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700492 self->SetInterruptedLocked(false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700493 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700494 }
495
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700496 // Set self->status back to kRunnable, and self-suspend if needed.
497 self->TransitionFromSuspendedToRunnable();
Elliott Hughes5f791332011-09-15 17:45:30 -0700498
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800499 {
500 // We reset the thread's wait_monitor_ field after transitioning back to runnable so
501 // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
502 // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
503 // are waiting on "null".)
Ian Rogersdd7624d2014-03-14 17:43:00 -0700504 MutexLock mu(self, *self->GetWaitMutex());
505 DCHECK(self->GetWaitMonitor() != nullptr);
506 self->SetWaitMonitor(nullptr);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800507 }
508
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700509 // Re-acquire the monitor and lock.
Elliott Hughes5f791332011-09-15 17:45:30 -0700510 Lock(self);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700511 monitor_lock_.Lock(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700512 self->GetWaitMutex()->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700513
Elliott Hughes5f791332011-09-15 17:45:30 -0700514 /*
515 * We remove our thread from wait set after restoring the count
516 * and owner fields so the subroutine can check that the calling
517 * thread owns the monitor. Aside from that, the order of member
518 * updates is not order sensitive as we hold the pthread mutex.
519 */
520 owner_ = self;
Ian Rogers0399dde2012-06-06 17:09:28 -0700521 lock_count_ = prev_lock_count;
522 locking_method_ = saved_method;
523 locking_dex_pc_ = saved_dex_pc;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700524 --num_waiters_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700525 RemoveFromWaitSet(self);
526
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700527 monitor_lock_.Unlock(self);
528
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800529 if (was_interrupted) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700530 /*
531 * We were interrupted while waiting, or somebody interrupted an
532 * un-interruptible thread earlier and we're bailing out immediately.
533 *
534 * The doc sayeth: "The interrupted status of the current thread is
535 * cleared when this exception is thrown."
536 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700537 {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700538 MutexLock mu(self, *self->GetWaitMutex());
539 self->SetInterruptedLocked(false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700540 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700541 if (interruptShouldThrow) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700542 self->ThrowNewException("Ljava/lang/InterruptedException;", nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700543 }
544 }
545}
546
547void Monitor::Notify(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700548 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700549 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700550 // Make sure that we hold the lock.
551 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800552 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700553 return;
554 }
555 // Signal the first waiting thread in the wait set.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700556 while (wait_set_ != nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700557 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700558 wait_set_ = thread->GetWaitNext();
559 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700560
561 // Check to see if the thread is still waiting.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800562 MutexLock wait_mu(self, *thread->GetWaitMutex());
Ian Rogersdd7624d2014-03-14 17:43:00 -0700563 if (thread->GetWaitMonitor() != nullptr) {
564 thread->GetWaitConditionVariable()->Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700565 return;
566 }
567 }
568}
569
570void Monitor::NotifyAll(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700571 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700572 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700573 // Make sure that we hold the lock.
574 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800575 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700576 return;
577 }
578 // Signal all threads in the wait set.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700579 while (wait_set_ != nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700580 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700581 wait_set_ = thread->GetWaitNext();
582 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700583 thread->Notify();
584 }
585}
586
Mathieu Chartier590fee92013-09-13 13:46:47 -0700587bool Monitor::Deflate(Thread* self, mirror::Object* obj) {
588 DCHECK(obj != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700589 // Don't need volatile since we only deflate with mutators suspended.
590 LockWord lw(obj->GetLockWord(false));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700591 // If the lock isn't an inflated monitor, then we don't need to deflate anything.
592 if (lw.GetState() == LockWord::kFatLocked) {
593 Monitor* monitor = lw.FatLockMonitor();
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700594 DCHECK(monitor != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700595 MutexLock mu(self, monitor->monitor_lock_);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700596 // Can't deflate if we have anybody waiting on the CV.
597 if (monitor->num_waiters_ > 0) {
598 return false;
599 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700600 Thread* owner = monitor->owner_;
601 if (owner != nullptr) {
602 // Can't deflate if we are locked and have a hash code.
603 if (monitor->HasHashCode()) {
604 return false;
605 }
606 // Can't deflate if our lock count is too high.
607 if (monitor->lock_count_ > LockWord::kThinLockMaxCount) {
608 return false;
609 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700610 // Deflate to a thin lock.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800611 LockWord new_lw = LockWord::FromThinLockId(owner->GetThreadId(), monitor->lock_count_,
612 lw.ReadBarrierState());
613 // Assume no concurrent read barrier state changes as mutators are suspended.
614 obj->SetLockWord(new_lw, false);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700615 VLOG(monitor) << "Deflated " << obj << " to thin lock " << owner->GetTid() << " / "
616 << monitor->lock_count_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700617 } else if (monitor->HasHashCode()) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800618 LockWord new_lw = LockWord::FromHashCode(monitor->GetHashCode(), lw.ReadBarrierState());
619 // Assume no concurrent read barrier state changes as mutators are suspended.
620 obj->SetLockWord(new_lw, false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700621 VLOG(monitor) << "Deflated " << obj << " to hash monitor " << monitor->GetHashCode();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700622 } else {
623 // No lock and no hash, just put an empty lock word inside the object.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800624 LockWord new_lw = LockWord::FromDefault(lw.ReadBarrierState());
625 // Assume no concurrent read barrier state changes as mutators are suspended.
626 obj->SetLockWord(new_lw, false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700627 VLOG(monitor) << "Deflated" << obj << " to empty lock word";
Mathieu Chartier590fee92013-09-13 13:46:47 -0700628 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700629 // The monitor is deflated, mark the object as null so that we know to delete it during the
Mathieu Chartier590fee92013-09-13 13:46:47 -0700630 // next GC.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700631 monitor->obj_ = GcRoot<mirror::Object>(nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700632 }
633 return true;
634}
635
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700636void Monitor::Inflate(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code) {
Andreas Gampe74240812014-04-17 10:35:09 -0700637 DCHECK(self != nullptr);
638 DCHECK(obj != nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700639 // Allocate and acquire a new monitor.
Andreas Gampe74240812014-04-17 10:35:09 -0700640 Monitor* m = MonitorPool::CreateMonitor(self, owner, obj, hash_code);
641 DCHECK(m != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700642 if (m->Install(self)) {
Haifeng Li86ab7912014-05-16 10:47:59 +0800643 if (owner != nullptr) {
644 VLOG(monitor) << "monitor: thread" << owner->GetThreadId()
Andreas Gampe74240812014-04-17 10:35:09 -0700645 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800646 } else {
647 VLOG(monitor) << "monitor: Inflate with hashcode " << hash_code
Andreas Gampe74240812014-04-17 10:35:09 -0700648 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800649 }
Andreas Gampe74240812014-04-17 10:35:09 -0700650 Runtime::Current()->GetMonitorList()->Add(m);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700651 CHECK_EQ(obj->GetLockWord(true).GetState(), LockWord::kFatLocked);
Andreas Gampe74240812014-04-17 10:35:09 -0700652 } else {
653 MonitorPool::ReleaseMonitor(self, m);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700654 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700655}
656
Mathieu Chartier0cd81352014-05-22 16:48:55 -0700657void Monitor::InflateThinLocked(Thread* self, Handle<mirror::Object> obj, LockWord lock_word,
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700658 uint32_t hash_code) {
659 DCHECK_EQ(lock_word.GetState(), LockWord::kThinLocked);
660 uint32_t owner_thread_id = lock_word.ThinLockOwner();
661 if (owner_thread_id == self->GetThreadId()) {
662 // We own the monitor, we can easily inflate it.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700663 Inflate(self, self, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700664 } else {
665 ThreadList* thread_list = Runtime::Current()->GetThreadList();
666 // Suspend the owner, inflate. First change to blocked and give up mutator_lock_.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700667 self->SetMonitorEnterObject(obj.Get());
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700668 bool timed_out;
669 Thread* owner;
670 {
671 ScopedThreadStateChange tsc(self, kBlocked);
672 owner = thread_list->SuspendThreadByThreadId(owner_thread_id, false, &timed_out);
673 }
674 if (owner != nullptr) {
675 // We succeeded in suspending the thread, check the lock's status didn't change.
676 lock_word = obj->GetLockWord(true);
677 if (lock_word.GetState() == LockWord::kThinLocked &&
678 lock_word.ThinLockOwner() == owner_thread_id) {
679 // Go ahead and inflate the lock.
680 Inflate(self, owner, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700681 }
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700682 thread_list->Resume(owner, false);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700683 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700684 self->SetMonitorEnterObject(nullptr);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700685 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700686}
687
Ian Rogers719d1a32014-03-06 12:13:39 -0800688// Fool annotalysis into thinking that the lock on obj is acquired.
689static mirror::Object* FakeLock(mirror::Object* obj)
690 EXCLUSIVE_LOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
691 return obj;
692}
693
694// Fool annotalysis into thinking that the lock on obj is release.
695static mirror::Object* FakeUnlock(mirror::Object* obj)
696 UNLOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
697 return obj;
698}
699
Mathieu Chartiere7e8a5f2014-02-14 16:59:41 -0800700mirror::Object* Monitor::MonitorEnter(Thread* self, mirror::Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700701 DCHECK(self != nullptr);
702 DCHECK(obj != nullptr);
Ian Rogers719d1a32014-03-06 12:13:39 -0800703 obj = FakeLock(obj);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700704 uint32_t thread_id = self->GetThreadId();
705 size_t contention_count = 0;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700706 StackHandleScope<1> hs(self);
707 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700708 while (true) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700709 LockWord lock_word = h_obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700710 switch (lock_word.GetState()) {
711 case LockWord::kUnlocked: {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800712 LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0, lock_word.ReadBarrierState()));
Ian Rogers228602f2014-07-10 02:07:54 -0700713 if (h_obj->CasLockWordWeakSequentiallyConsistent(lock_word, thin_locked)) {
Hans Boehm30359612014-05-21 17:46:23 -0700714 // CasLockWord enforces more than the acquire ordering we need here.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700715 return h_obj.Get(); // Success!
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700716 }
717 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -0700718 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700719 case LockWord::kThinLocked: {
720 uint32_t owner_thread_id = lock_word.ThinLockOwner();
721 if (owner_thread_id == thread_id) {
722 // We own the lock, increase the recursion count.
723 uint32_t new_count = lock_word.ThinLockCount() + 1;
724 if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800725 LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count,
726 lock_word.ReadBarrierState()));
727 if (!kUseReadBarrier) {
728 h_obj->SetLockWord(thin_locked, true);
729 return h_obj.Get(); // Success!
730 } else {
731 // Use CAS to preserve the read barrier state.
732 if (h_obj->CasLockWordWeakSequentiallyConsistent(lock_word, thin_locked)) {
733 return h_obj.Get(); // Success!
734 }
735 }
736 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -0700737 } else {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700738 // We'd overflow the recursion count, so inflate the monitor.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700739 InflateThinLocked(self, h_obj, lock_word, 0);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700740 }
741 } else {
742 // Contention.
743 contention_count++;
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700744 Runtime* runtime = Runtime::Current();
745 if (contention_count <= runtime->GetMaxSpinsBeforeThinkLockInflation()) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700746 // TODO: Consider switching the thread state to kBlocked when we are yielding.
Mathieu Chartier251755c2014-07-15 18:10:25 -0700747 // Use sched_yield instead of NanoSleep since NanoSleep can wait much longer than the
748 // parameter you pass in. This can cause thread suspension to take excessively long
Mathieu Chartierb363f662014-07-16 13:28:58 -0700749 // and make long pauses. See b/16307460.
Mathieu Chartier251755c2014-07-15 18:10:25 -0700750 sched_yield();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700751 } else {
752 contention_count = 0;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700753 InflateThinLocked(self, h_obj, lock_word, 0);
Elliott Hughes5f791332011-09-15 17:45:30 -0700754 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700755 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700756 continue; // Start from the beginning.
Elliott Hughes5f791332011-09-15 17:45:30 -0700757 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700758 case LockWord::kFatLocked: {
759 Monitor* mon = lock_word.FatLockMonitor();
760 mon->Lock(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700761 return h_obj.Get(); // Success!
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700762 }
Ian Rogers719d1a32014-03-06 12:13:39 -0800763 case LockWord::kHashCode:
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700764 // Inflate with the existing hashcode.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700765 Inflate(self, nullptr, h_obj.Get(), lock_word.GetHashCode());
Ian Rogers719d1a32014-03-06 12:13:39 -0800766 continue; // Start from the beginning.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700767 default: {
768 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700769 return h_obj.Get();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700770 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700771 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700772 }
773}
774
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800775bool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700776 DCHECK(self != nullptr);
777 DCHECK(obj != nullptr);
Ian Rogers719d1a32014-03-06 12:13:39 -0800778 obj = FakeUnlock(obj);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700779 StackHandleScope<1> hs(self);
780 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800781 while (true) {
782 LockWord lock_word = obj->GetLockWord(true);
783 switch (lock_word.GetState()) {
784 case LockWord::kHashCode:
785 // Fall-through.
786 case LockWord::kUnlocked:
787 FailedUnlock(h_obj.Get(), self, nullptr, nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700788 return false; // Failure.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800789 case LockWord::kThinLocked: {
790 uint32_t thread_id = self->GetThreadId();
791 uint32_t owner_thread_id = lock_word.ThinLockOwner();
792 if (owner_thread_id != thread_id) {
793 // TODO: there's a race here with the owner dying while we unlock.
794 Thread* owner =
795 Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
796 FailedUnlock(h_obj.Get(), self, owner, nullptr);
797 return false; // Failure.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700798 } else {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800799 // We own the lock, decrease the recursion count.
800 LockWord new_lw = LockWord::Default();
801 if (lock_word.ThinLockCount() != 0) {
802 uint32_t new_count = lock_word.ThinLockCount() - 1;
803 new_lw = LockWord::FromThinLockId(thread_id, new_count, lock_word.ReadBarrierState());
804 } else {
805 new_lw = LockWord::FromDefault(lock_word.ReadBarrierState());
806 }
807 if (!kUseReadBarrier) {
808 DCHECK_EQ(new_lw.ReadBarrierState(), 0U);
809 h_obj->SetLockWord(new_lw, true);
810 // Success!
811 return true;
812 } else {
813 // Use CAS to preserve the read barrier state.
814 if (h_obj->CasLockWordWeakSequentiallyConsistent(lock_word, new_lw)) {
815 // Success!
816 return true;
817 }
818 }
819 continue; // Go again.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700820 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700821 }
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800822 case LockWord::kFatLocked: {
823 Monitor* mon = lock_word.FatLockMonitor();
824 return mon->Unlock(self);
825 }
826 default: {
827 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
828 return false;
829 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700830 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700831 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700832}
833
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800834void Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800835 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700836 DCHECK(self != nullptr);
837 DCHECK(obj != nullptr);
838 LockWord lock_word = obj->GetLockWord(true);
Ian Rogers43c69cc2014-08-15 11:09:28 -0700839 while (lock_word.GetState() != LockWord::kFatLocked) {
840 switch (lock_word.GetState()) {
841 case LockWord::kHashCode:
842 // Fall-through.
843 case LockWord::kUnlocked:
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700844 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
845 return; // Failure.
Ian Rogers43c69cc2014-08-15 11:09:28 -0700846 case LockWord::kThinLocked: {
847 uint32_t thread_id = self->GetThreadId();
848 uint32_t owner_thread_id = lock_word.ThinLockOwner();
849 if (owner_thread_id != thread_id) {
850 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
851 return; // Failure.
852 } else {
853 // We own the lock, inflate to enqueue ourself on the Monitor. May fail spuriously so
854 // re-load.
855 Inflate(self, self, obj, 0);
856 lock_word = obj->GetLockWord(true);
857 }
858 break;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700859 }
Ian Rogers43c69cc2014-08-15 11:09:28 -0700860 case LockWord::kFatLocked: // Unreachable given the loop condition above. Fall-through.
861 default: {
862 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
863 return;
864 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700865 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700866 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700867 Monitor* mon = lock_word.FatLockMonitor();
868 mon->Wait(self, ms, ns, interruptShouldThrow, why);
Elliott Hughes5f791332011-09-15 17:45:30 -0700869}
870
Ian Rogers13c479e2013-10-11 07:59:01 -0700871void Monitor::DoNotify(Thread* self, mirror::Object* obj, bool notify_all) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700872 DCHECK(self != nullptr);
873 DCHECK(obj != nullptr);
874 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700875 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700876 case LockWord::kHashCode:
877 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700878 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800879 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700880 return; // Failure.
881 case LockWord::kThinLocked: {
882 uint32_t thread_id = self->GetThreadId();
883 uint32_t owner_thread_id = lock_word.ThinLockOwner();
884 if (owner_thread_id != thread_id) {
885 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
886 return; // Failure.
887 } else {
888 // We own the lock but there's no Monitor and therefore no waiters.
889 return; // Success.
890 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700891 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700892 case LockWord::kFatLocked: {
893 Monitor* mon = lock_word.FatLockMonitor();
894 if (notify_all) {
895 mon->NotifyAll(self);
896 } else {
897 mon->Notify(self);
898 }
899 return; // Success.
900 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700901 default: {
902 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
903 return;
904 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700905 }
906}
907
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700908uint32_t Monitor::GetLockOwnerThreadId(mirror::Object* obj) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700909 DCHECK(obj != nullptr);
910 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700911 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700912 case LockWord::kHashCode:
913 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700914 case LockWord::kUnlocked:
915 return ThreadList::kInvalidThreadId;
916 case LockWord::kThinLocked:
917 return lock_word.ThinLockOwner();
918 case LockWord::kFatLocked: {
919 Monitor* mon = lock_word.FatLockMonitor();
920 return mon->GetOwnerThreadId();
Elliott Hughes5f791332011-09-15 17:45:30 -0700921 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700922 default: {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700923 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -0700924 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700925 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700926 }
927}
928
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700929void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
Ian Rogersd803bc72014-04-01 15:33:03 -0700930 // Determine the wait message and object we're waiting or blocked upon.
931 mirror::Object* pretty_object = nullptr;
932 const char* wait_message = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700933 uint32_t lock_owner = ThreadList::kInvalidThreadId;
Ian Rogersd803bc72014-04-01 15:33:03 -0700934 ThreadState state = thread->GetState();
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800935 if (state == kWaiting || state == kTimedWaiting || state == kSleeping) {
Ian Rogersd803bc72014-04-01 15:33:03 -0700936 wait_message = (state == kSleeping) ? " - sleeping on " : " - waiting on ";
937 Thread* self = Thread::Current();
938 MutexLock mu(self, *thread->GetWaitMutex());
939 Monitor* monitor = thread->GetWaitMonitor();
940 if (monitor != nullptr) {
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700941 pretty_object = monitor->GetObject();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700942 }
Elliott Hughes34e06962012-04-09 13:55:55 -0700943 } else if (state == kBlocked) {
Ian Rogersd803bc72014-04-01 15:33:03 -0700944 wait_message = " - waiting to lock ";
945 pretty_object = thread->GetMonitorEnterObject();
946 if (pretty_object != nullptr) {
947 lock_owner = pretty_object->GetLockOwnerThreadId();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700948 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700949 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700950
Ian Rogersd803bc72014-04-01 15:33:03 -0700951 if (wait_message != nullptr) {
952 if (pretty_object == nullptr) {
953 os << wait_message << "an unknown object";
954 } else {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700955 if ((pretty_object->GetLockWord(true).GetState() == LockWord::kThinLocked) &&
Ian Rogersd803bc72014-04-01 15:33:03 -0700956 Locks::mutator_lock_->IsExclusiveHeld(Thread::Current())) {
957 // Getting the identity hashcode here would result in lock inflation and suspension of the
958 // current thread, which isn't safe if this is the only runnable thread.
959 os << wait_message << StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)",
960 reinterpret_cast<intptr_t>(pretty_object),
961 PrettyTypeOf(pretty_object).c_str());
962 } else {
963 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
Mathieu Chartier49361592015-01-22 16:36:10 -0800964 // Call PrettyTypeOf before IdentityHashCode since IdentityHashCode can cause thread
965 // suspension and move pretty_object.
966 const std::string pretty_type(PrettyTypeOf(pretty_object));
Ian Rogersd803bc72014-04-01 15:33:03 -0700967 os << wait_message << StringPrintf("<0x%08x> (a %s)", pretty_object->IdentityHashCode(),
Mathieu Chartier49361592015-01-22 16:36:10 -0800968 pretty_type.c_str());
Ian Rogersd803bc72014-04-01 15:33:03 -0700969 }
970 }
971 // - waiting to lock <0x613f83d8> (a java.lang.Object) held by thread 5
972 if (lock_owner != ThreadList::kInvalidThreadId) {
973 os << " held by thread " << lock_owner;
974 }
975 os << "\n";
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700976 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700977}
978
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800979mirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800980 // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
981 // definition of contended that includes a monitor a thread is trying to enter...
Ian Rogersdd7624d2014-03-14 17:43:00 -0700982 mirror::Object* result = thread->GetMonitorEnterObject();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700983 if (result == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700984 // ...but also a monitor that the thread is waiting on.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700985 MutexLock mu(Thread::Current(), *thread->GetWaitMutex());
986 Monitor* monitor = thread->GetWaitMonitor();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700987 if (monitor != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700988 result = monitor->GetObject();
Elliott Hughesf9501702013-01-11 11:22:27 -0800989 }
990 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700991 return result;
Elliott Hughesf9501702013-01-11 11:22:27 -0800992}
993
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800994void Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
Andreas Gampe760172c2014-08-16 13:41:10 -0700995 void* callback_context, bool abort_on_failure) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700996 mirror::ArtMethod* m = stack_visitor->GetMethod();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700997 CHECK(m != nullptr);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700998
999 // Native methods are an easy special case.
1000 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
1001 if (m->IsNative()) {
1002 if (m->IsSynchronized()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001003 mirror::Object* jni_this = stack_visitor->GetCurrentHandleScope()->GetReference(0);
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001004 callback(jni_this, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001005 }
1006 return;
1007 }
1008
jeffhao61f916c2012-10-25 17:48:51 -07001009 // Proxy methods should not be synchronized.
1010 if (m->IsProxyMethod()) {
1011 CHECK(!m->IsSynchronized());
1012 return;
1013 }
1014
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001015 // Is there any reason to believe there's any synchronization in this method?
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001016 const DexFile::CodeItem* code_item = m->GetCodeItem();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001017 CHECK(code_item != nullptr) << PrettyMethod(m);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001018 if (code_item->tries_size_ == 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001019 return; // No "tries" implies no synchronization, so no held locks to report.
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001020 }
1021
Andreas Gampe760172c2014-08-16 13:41:10 -07001022 // Get the dex pc. If abort_on_failure is false, GetDexPc will not abort in the case it cannot
1023 // find the dex pc, and instead return kDexNoIndex. Then bail out, as it indicates we have an
1024 // inconsistent stack anyways.
1025 uint32_t dex_pc = stack_visitor->GetDexPc(abort_on_failure);
1026 if (!abort_on_failure && dex_pc == DexFile::kDexNoIndex) {
1027 LOG(ERROR) << "Could not find dex_pc for " << PrettyMethod(m);
1028 return;
1029 }
1030
Elliott Hughes80537bb2013-01-04 16:37:26 -08001031 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
1032 // the locks held in this stack frame.
1033 std::vector<uint32_t> monitor_enter_dex_pcs;
Andreas Gampe760172c2014-08-16 13:41:10 -07001034 verifier::MethodVerifier::FindLocksAtDexPc(m, dex_pc, &monitor_enter_dex_pcs);
Mathieu Chartiere6a8eec2015-01-06 14:17:57 -08001035 for (uint32_t monitor_dex_pc : monitor_enter_dex_pcs) {
Elliott Hughes80537bb2013-01-04 16:37:26 -08001036 // 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).
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001038 uint16_t monitor_enter_instruction = code_item->insns_[monitor_dex_pc];
Elliott Hughes80537bb2013-01-04 16:37:26 -08001039
1040 // Quick sanity check.
1041 if ((monitor_enter_instruction & 0xff) != Instruction::MONITOR_ENTER) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001042 LOG(FATAL) << "expected monitor-enter @" << monitor_dex_pc << "; was "
Elliott Hughes80537bb2013-01-04 16:37:26 -08001043 << reinterpret_cast<void*>(monitor_enter_instruction);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001044 }
1045
Elliott Hughes80537bb2013-01-04 16:37:26 -08001046 uint16_t monitor_register = ((monitor_enter_instruction >> 8) & 0xff);
Nicolas Geoffray15b9d522015-03-12 15:05:13 +00001047 uint32_t value;
1048 bool success = stack_visitor->GetVReg(m, monitor_register, kReferenceVReg, &value);
1049 CHECK(success) << "Failed to read v" << monitor_register << " of kind "
1050 << kReferenceVReg << " in method " << PrettyMethod(m);
1051 mirror::Object* o = reinterpret_cast<mirror::Object*>(value);
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001052 callback(o, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001053 }
1054}
1055
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001056bool Monitor::IsValidLockWord(LockWord lock_word) {
1057 switch (lock_word.GetState()) {
1058 case LockWord::kUnlocked:
1059 // Nothing to check.
1060 return true;
1061 case LockWord::kThinLocked:
1062 // Basic sanity check of owner.
1063 return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
1064 case LockWord::kFatLocked: {
1065 // Check the monitor appears in the monitor list.
1066 Monitor* mon = lock_word.FatLockMonitor();
1067 MonitorList* list = Runtime::Current()->GetMonitorList();
1068 MutexLock mu(Thread::Current(), list->monitor_list_lock_);
1069 for (Monitor* list_mon : list->list_) {
1070 if (mon == list_mon) {
1071 return true; // Found our monitor.
1072 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001073 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001074 return false; // Fail - unowned monitor in an object.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001075 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001076 case LockWord::kHashCode:
1077 return true;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001078 default:
1079 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001080 UNREACHABLE();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001081 }
1082}
1083
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001084bool Monitor::IsLocked() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1085 MutexLock mu(Thread::Current(), monitor_lock_);
1086 return owner_ != nullptr;
1087}
1088
Ian Rogersef7d42f2014-01-06 12:55:46 -08001089void Monitor::TranslateLocation(mirror::ArtMethod* method, uint32_t dex_pc,
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001090 const char** source_file, uint32_t* line_number) const {
jeffhao33dc7712011-11-09 17:54:24 -08001091 // If method is null, location is unknown
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001092 if (method == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001093 *source_file = "";
1094 *line_number = 0;
jeffhao33dc7712011-11-09 17:54:24 -08001095 return;
1096 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001097 *source_file = method->GetDeclaringClassSourceFile();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001098 if (*source_file == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001099 *source_file = "";
Elliott Hughes12c51e32012-01-17 20:25:05 -08001100 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001101 *line_number = method->GetLineNumFromDexPC(dex_pc);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001102}
1103
1104uint32_t Monitor::GetOwnerThreadId() {
1105 MutexLock mu(Thread::Current(), monitor_lock_);
1106 Thread* owner = owner_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001107 if (owner != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001108 return owner->GetThreadId();
1109 } else {
1110 return ThreadList::kInvalidThreadId;
1111 }
jeffhao33dc7712011-11-09 17:54:24 -08001112}
1113
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001114MonitorList::MonitorList()
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001115 : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock", kMonitorListLock),
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001116 monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001117}
1118
1119MonitorList::~MonitorList() {
Andreas Gampe74240812014-04-17 10:35:09 -07001120 Thread* self = Thread::Current();
1121 MutexLock mu(self, monitor_list_lock_);
1122 // Release all monitors to the pool.
1123 // TODO: Is it an invariant that *all* open monitors are in the list? Then we could
1124 // clear faster in the pool.
1125 MonitorPool::ReleaseMonitors(self, &list_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001126}
1127
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001128void MonitorList::DisallowNewMonitors() {
Ian Rogers50b35e22012-10-04 10:09:15 -07001129 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001130 allow_new_monitors_ = false;
1131}
1132
1133void MonitorList::AllowNewMonitors() {
1134 Thread* self = Thread::Current();
1135 MutexLock mu(self, monitor_list_lock_);
1136 allow_new_monitors_ = true;
1137 monitor_add_condition_.Broadcast(self);
1138}
1139
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -08001140void MonitorList::EnsureNewMonitorsDisallowed() {
1141 // Lock and unlock once to ensure that no threads are still in the
1142 // middle of adding new monitors.
1143 MutexLock mu(Thread::Current(), monitor_list_lock_);
1144 CHECK(!allow_new_monitors_);
1145}
1146
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001147void MonitorList::Add(Monitor* m) {
1148 Thread* self = Thread::Current();
1149 MutexLock mu(self, monitor_list_lock_);
1150 while (UNLIKELY(!allow_new_monitors_)) {
1151 monitor_add_condition_.WaitHoldingLocks(self);
1152 }
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001153 list_.push_front(m);
1154}
1155
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08001156void MonitorList::SweepMonitorList(IsMarkedCallback* callback, void* arg) {
Andreas Gampe74240812014-04-17 10:35:09 -07001157 Thread* self = Thread::Current();
1158 MutexLock mu(self, monitor_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001159 for (auto it = list_.begin(); it != list_.end(); ) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001160 Monitor* m = *it;
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001161 // Disable the read barrier in GetObject() as this is called by GC.
1162 mirror::Object* obj = m->GetObject<kWithoutReadBarrier>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001163 // The object of a monitor can be null if we have deflated it.
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08001164 mirror::Object* new_obj = obj != nullptr ? callback(obj, arg) : nullptr;
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001165 if (new_obj == nullptr) {
1166 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001167 << obj;
Andreas Gampe74240812014-04-17 10:35:09 -07001168 MonitorPool::ReleaseMonitor(self, m);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001169 it = list_.erase(it);
1170 } else {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001171 m->SetObject(new_obj);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001172 ++it;
1173 }
1174 }
1175}
1176
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001177struct MonitorDeflateArgs {
1178 MonitorDeflateArgs() : self(Thread::Current()), deflate_count(0) {}
1179 Thread* const self;
1180 size_t deflate_count;
1181};
1182
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001183static mirror::Object* MonitorDeflateCallback(mirror::Object* object, void* arg)
1184 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001185 MonitorDeflateArgs* args = reinterpret_cast<MonitorDeflateArgs*>(arg);
1186 if (Monitor::Deflate(args->self, object)) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001187 DCHECK_NE(object->GetLockWord(true).GetState(), LockWord::kFatLocked);
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001188 ++args->deflate_count;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001189 // If we deflated, return null so that the monitor gets removed from the array.
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001190 return nullptr;
1191 }
1192 return object; // Monitor was not deflated.
1193}
1194
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001195size_t MonitorList::DeflateMonitors() {
1196 MonitorDeflateArgs args;
1197 Locks::mutator_lock_->AssertExclusiveHeld(args.self);
1198 SweepMonitorList(MonitorDeflateCallback, &args);
1199 return args.deflate_count;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001200}
1201
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001202MonitorInfo::MonitorInfo(mirror::Object* obj) : owner_(nullptr), entry_count_(0) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001203 DCHECK(obj != nullptr);
1204 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001205 switch (lock_word.GetState()) {
1206 case LockWord::kUnlocked:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001207 // Fall-through.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001208 case LockWord::kForwardingAddress:
1209 // Fall-through.
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001210 case LockWord::kHashCode:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001211 break;
1212 case LockWord::kThinLocked:
1213 owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
1214 entry_count_ = 1 + lock_word.ThinLockCount();
1215 // Thin locks have no waiters.
1216 break;
1217 case LockWord::kFatLocked: {
1218 Monitor* mon = lock_word.FatLockMonitor();
1219 owner_ = mon->owner_;
1220 entry_count_ = 1 + mon->lock_count_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001221 for (Thread* waiter = mon->wait_set_; waiter != nullptr; waiter = waiter->GetWaitNext()) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001222 waiters_.push_back(waiter);
1223 }
1224 break;
Elliott Hughesf327e072013-01-09 16:01:26 -08001225 }
1226 }
1227}
1228
Elliott Hughes5f791332011-09-15 17:45:30 -07001229} // namespace art