blob: a262c7a8f3f4df404ecb8148422df3cd2dca02e2 [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
Mathieu Chartiere401d142015-04-22 13:56:20 -070021#include "art_method-inl.h"
Elliott Hughes76b61672012-12-12 17:47:30 -080022#include "base/mutex.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080023#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080024#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010025#include "base/time_utils.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"
Sebastien Hertz0f7c9332015-11-05 15:57:30 +010028#include "dex_instruction-inl.h"
Ian Rogersd9c4fc92013-10-01 19:45:43 -070029#include "lock_word-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070030#include "mirror/class-inl.h"
Ian Rogers05f30572013-02-20 12:13:11 -080031#include "mirror/object-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080032#include "mirror/object_array-inl.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070033#include "scoped_thread_state_change.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070034#include "thread.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070035#include "thread_list.h"
Elliott Hughes08fc03a2012-06-26 17:34:00 -070036#include "verifier/method_verifier.h"
Elliott Hughes044288f2012-06-25 14:46:39 -070037#include "well_known_classes.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070038
39namespace art {
40
Mathieu Chartierb9001ab2014-10-03 13:28:46 -070041static constexpr uint64_t kLongWaitMs = 100;
42
Elliott Hughes5f791332011-09-15 17:45:30 -070043/*
Ian Rogersd9c4fc92013-10-01 19:45:43 -070044 * Every Object has a monitor associated with it, but not every Object is actually locked. Even
45 * the ones that are locked do not need a full-fledged monitor until a) there is actual contention
46 * or b) wait() is called on the Object.
Elliott Hughes5f791332011-09-15 17:45:30 -070047 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070048 * For Android, we have implemented a scheme similar to the one described in Bacon et al.'s
49 * "Thin locks: featherweight synchronization for Java" (ACM 1998). Things are even easier for us,
50 * though, because we have a full 32 bits to work with.
Elliott Hughes5f791332011-09-15 17:45:30 -070051 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070052 * The two states of an Object's lock are referred to as "thin" and "fat". A lock may transition
53 * from the "thin" state to the "fat" state and this transition is referred to as inflation. Once
54 * a lock has been inflated it remains in the "fat" state indefinitely.
Elliott Hughes5f791332011-09-15 17:45:30 -070055 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070056 * The lock value itself is stored in mirror::Object::monitor_ and the representation is described
57 * in the LockWord value type.
Elliott Hughes54e7df12011-09-16 11:47:04 -070058 *
Elliott Hughes5f791332011-09-15 17:45:30 -070059 * Monitors provide:
60 * - mutually exclusive access to resources
61 * - a way for multiple threads to wait for notification
62 *
63 * In effect, they fill the role of both mutexes and condition variables.
64 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070065 * Only one thread can own the monitor at any time. There may be several threads waiting on it
66 * (the wait call unlocks it). One or more waiting threads may be getting interrupted or notified
67 * at any given time.
Elliott Hughes5f791332011-09-15 17:45:30 -070068 */
Elliott Hughes54e7df12011-09-16 11:47:04 -070069
Mathieu Chartier2cebb242015-04-21 16:50:40 -070070bool (*Monitor::is_sensitive_thread_hook_)() = nullptr;
Elliott Hughesfc861622011-10-17 17:57:47 -070071uint32_t Monitor::lock_profiling_threshold_ = 0;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070072
Elliott Hughesfc861622011-10-17 17:57:47 -070073bool Monitor::IsSensitiveThread() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -070074 if (is_sensitive_thread_hook_ != nullptr) {
Elliott Hughesfc861622011-10-17 17:57:47 -070075 return (*is_sensitive_thread_hook_)();
76 }
77 return false;
78}
79
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -080080void Monitor::Init(uint32_t lock_profiling_threshold, bool (*is_sensitive_thread_hook)()) {
Elliott Hughesfc861622011-10-17 17:57:47 -070081 lock_profiling_threshold_ = lock_profiling_threshold;
82 is_sensitive_thread_hook_ = is_sensitive_thread_hook;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070083}
84
Ian Rogersef7d42f2014-01-06 12:55:46 -080085Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code)
Ian Rogers00f7d0e2012-07-19 15:28:27 -070086 : monitor_lock_("a monitor lock", kMonitorLock),
Ian Rogersd9c4fc92013-10-01 19:45:43 -070087 monitor_contenders_("monitor contenders", monitor_lock_),
Mathieu Chartier46bc7782013-11-12 17:03:02 -080088 num_waiters_(0),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070089 owner_(owner),
Elliott Hughes5f791332011-09-15 17:45:30 -070090 lock_count_(0),
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070091 obj_(GcRoot<mirror::Object>(obj)),
Mathieu Chartier2cebb242015-04-21 16:50:40 -070092 wait_set_(nullptr),
Mathieu Chartierad2541a2013-10-25 10:05:23 -070093 hash_code_(hash_code),
Mathieu Chartier2cebb242015-04-21 16:50:40 -070094 locking_method_(nullptr),
Ian Rogersef7d42f2014-01-06 12:55:46 -080095 locking_dex_pc_(0),
Andreas Gampe74240812014-04-17 10:35:09 -070096 monitor_id_(MonitorPool::ComputeMonitorId(this, self)) {
97#ifdef __LP64__
98 DCHECK(false) << "Should not be reached in 64b";
99 next_free_ = nullptr;
100#endif
101 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
102 // with the owner unlocking the thin-lock.
103 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
104 // The identity hash code is set for the life time of the monitor.
105}
106
107Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code,
108 MonitorId id)
109 : monitor_lock_("a monitor lock", kMonitorLock),
110 monitor_contenders_("monitor contenders", monitor_lock_),
111 num_waiters_(0),
112 owner_(owner),
113 lock_count_(0),
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700114 obj_(GcRoot<mirror::Object>(obj)),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700115 wait_set_(nullptr),
Andreas Gampe74240812014-04-17 10:35:09 -0700116 hash_code_(hash_code),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700117 locking_method_(nullptr),
Andreas Gampe74240812014-04-17 10:35:09 -0700118 locking_dex_pc_(0),
119 monitor_id_(id) {
120#ifdef __LP64__
121 next_free_ = nullptr;
122#endif
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700123 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
124 // with the owner unlocking the thin-lock.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800125 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700126 // The identity hash code is set for the life time of the monitor.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700127}
128
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700129int32_t Monitor::GetHashCode() {
130 while (!HasHashCode()) {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700131 if (hash_code_.CompareExchangeWeakRelaxed(0, mirror::Object::GenerateIdentityHashCode())) {
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700132 break;
133 }
134 }
135 DCHECK(HasHashCode());
Ian Rogers3e5cf302014-05-20 16:40:37 -0700136 return hash_code_.LoadRelaxed();
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700137}
138
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700139bool Monitor::Install(Thread* self) {
140 MutexLock mu(self, monitor_lock_); // Uncontended mutex acquisition as monitor isn't yet public.
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700141 CHECK(owner_ == nullptr || owner_ == self || owner_->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700142 // Propagate the lock state.
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700143 LockWord lw(GetObject()->GetLockWord(false));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700144 switch (lw.GetState()) {
145 case LockWord::kThinLocked: {
146 CHECK_EQ(owner_->GetThreadId(), lw.ThinLockOwner());
147 lock_count_ = lw.ThinLockCount();
148 break;
149 }
150 case LockWord::kHashCode: {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700151 CHECK_EQ(hash_code_.LoadRelaxed(), static_cast<int32_t>(lw.GetHashCode()));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700152 break;
153 }
154 case LockWord::kFatLocked: {
155 // The owner_ is suspended but another thread beat us to install a monitor.
156 return false;
157 }
158 case LockWord::kUnlocked: {
159 LOG(FATAL) << "Inflating unlocked lock word";
160 break;
161 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700162 default: {
163 LOG(FATAL) << "Invalid monitor state " << lw.GetState();
164 return false;
165 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700166 }
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800167 LockWord fat(this, lw.ReadBarrierState());
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700168 // Publish the updated lock word, which may race with other threads.
Ian Rogers228602f2014-07-10 02:07:54 -0700169 bool success = GetObject()->CasLockWordWeakSequentiallyConsistent(lw, fat);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700170 // Lock profiling.
Mathieu Chartier9728f912013-10-30 09:45:13 -0700171 if (success && owner_ != nullptr && lock_profiling_threshold_ != 0) {
Andreas Gampe6ec8ebd2014-07-25 13:36:56 -0700172 // Do not abort on dex pc errors. This can easily happen when we want to dump a stack trace on
173 // abort.
174 locking_method_ = owner_->GetCurrentMethod(&locking_dex_pc_, false);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700175 }
176 return success;
Elliott Hughes5f791332011-09-15 17:45:30 -0700177}
178
179Monitor::~Monitor() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700180 // Deflated monitors have a null object.
Elliott Hughes5f791332011-09-15 17:45:30 -0700181}
182
Elliott Hughes5f791332011-09-15 17:45:30 -0700183void Monitor::AppendToWaitSet(Thread* thread) {
184 DCHECK(owner_ == Thread::Current());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700185 DCHECK(thread != nullptr);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700186 DCHECK(thread->GetWaitNext() == nullptr) << thread->GetWaitNext();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700187 if (wait_set_ == nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700188 wait_set_ = thread;
189 return;
190 }
191
192 // push_back.
193 Thread* t = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700194 while (t->GetWaitNext() != nullptr) {
195 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700196 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700197 t->SetWaitNext(thread);
Elliott Hughes5f791332011-09-15 17:45:30 -0700198}
199
Elliott Hughes5f791332011-09-15 17:45:30 -0700200void Monitor::RemoveFromWaitSet(Thread *thread) {
201 DCHECK(owner_ == Thread::Current());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700202 DCHECK(thread != nullptr);
203 if (wait_set_ == nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700204 return;
205 }
206 if (wait_set_ == thread) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700207 wait_set_ = thread->GetWaitNext();
208 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700209 return;
210 }
211
212 Thread* t = wait_set_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700213 while (t->GetWaitNext() != nullptr) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700214 if (t->GetWaitNext() == thread) {
215 t->SetWaitNext(thread->GetWaitNext());
216 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700217 return;
218 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700219 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700220 }
221}
222
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700223void Monitor::SetObject(mirror::Object* object) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700224 obj_ = GcRoot<mirror::Object>(object);
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700225}
226
Elliott Hughes5f791332011-09-15 17:45:30 -0700227void Monitor::Lock(Thread* self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700228 MutexLock mu(self, monitor_lock_);
229 while (true) {
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700230 if (owner_ == nullptr) { // Unowned.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700231 owner_ = self;
232 CHECK_EQ(lock_count_, 0);
233 // When debugging, save the current monitor holder for future
234 // acquisition failures to use in sampled logging.
235 if (lock_profiling_threshold_ != 0) {
236 locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
237 }
238 return;
239 } else if (owner_ == self) { // Recursive.
240 lock_count_++;
241 return;
242 }
243 // Contended.
244 const bool log_contention = (lock_profiling_threshold_ != 0);
Xin Guanb894a192014-08-22 11:55:37 -0500245 uint64_t wait_start_ms = log_contention ? MilliTime() : 0;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700246 ArtMethod* owners_method = locking_method_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700247 uint32_t owners_dex_pc = locking_dex_pc_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700248 // Do this before releasing the lock so that we don't get deflated.
Mathieu Chartierb9001ab2014-10-03 13:28:46 -0700249 size_t num_waiters = num_waiters_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700250 ++num_waiters_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700251 monitor_lock_.Unlock(self); // Let go of locks in order.
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700252 self->SetMonitorEnterObject(GetObject());
Elliott Hughes5f791332011-09-15 17:45:30 -0700253 {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700254 ScopedThreadStateChange tsc(self, kBlocked); // Change to blocked and give up mutator_lock_.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700255 // Reacquire monitor_lock_ without mutator_lock_ for Wait.
256 MutexLock mu2(self, monitor_lock_);
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800257 if (owner_ != nullptr) { // Did the owner_ give the lock up?
258 if (ATRACE_ENABLED()) {
259 std::string name;
260 owner_->GetThreadName(name);
261 ATRACE_BEGIN(("Contended on monitor with owner " + name).c_str());
262 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700263 monitor_contenders_.Wait(self); // Still contended so wait.
264 // Woken from contention.
265 if (log_contention) {
266 uint64_t wait_ms = MilliTime() - wait_start_ms;
267 uint32_t sample_percent;
268 if (wait_ms >= lock_profiling_threshold_) {
269 sample_percent = 100;
270 } else {
271 sample_percent = 100 * wait_ms / lock_profiling_threshold_;
272 }
273 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
274 const char* owners_filename;
Brian Carlstromeaa46092015-10-07 21:29:28 -0700275 int32_t owners_line_number;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700276 TranslateLocation(owners_method, owners_dex_pc, &owners_filename, &owners_line_number);
Mathieu Chartierb9001ab2014-10-03 13:28:46 -0700277 if (wait_ms > kLongWaitMs && owners_method != nullptr) {
278 LOG(WARNING) << "Long monitor contention event with owner method="
279 << PrettyMethod(owners_method) << " from " << owners_filename << ":"
280 << owners_line_number << " waiters=" << num_waiters << " for "
281 << PrettyDuration(MsToNs(wait_ms));
282 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700283 LogContentionEvent(self, wait_ms, sample_percent, owners_filename, owners_line_number);
284 }
285 }
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800286 ATRACE_END();
Elliott Hughesfc861622011-10-17 17:57:47 -0700287 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700288 }
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700289 self->SetMonitorEnterObject(nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700290 monitor_lock_.Lock(self); // Reacquire locks in order.
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700291 --num_waiters_;
Elliott Hughesfc861622011-10-17 17:57:47 -0700292 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700293}
294
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800295static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
296 __attribute__((format(printf, 1, 2)));
297
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700298static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
Mathieu Chartier90443472015-07-16 20:32:27 -0700299 SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800300 va_list args;
301 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800302 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000303 self->ThrowNewExceptionV("Ljava/lang/IllegalMonitorStateException;", fmt, args);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700304 if (!Runtime::Current()->IsStarted() || VLOG_IS_ON(monitor)) {
Brian Carlstrom64277f32012-03-26 23:53:34 -0700305 std::ostringstream ss;
Ian Rogers62d6c772013-02-27 08:32:07 -0800306 self->Dump(ss);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700307 LOG(Runtime::Current()->IsStarted() ? INFO : ERROR)
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000308 << self->GetException()->Dump() << "\n" << ss.str();
Brian Carlstrom64277f32012-03-26 23:53:34 -0700309 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800310 va_end(args);
311}
312
Elliott Hughesd4237412012-02-21 11:24:45 -0800313static std::string ThreadToString(Thread* thread) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700314 if (thread == nullptr) {
315 return "nullptr";
Elliott Hughesd4237412012-02-21 11:24:45 -0800316 }
317 std::ostringstream oss;
318 // TODO: alternatively, we could just return the thread's name.
319 oss << *thread;
320 return oss.str();
321}
322
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800323void Monitor::FailedUnlock(mirror::Object* o, Thread* expected_owner, Thread* found_owner,
Elliott Hughesffb465f2012-03-01 18:46:05 -0800324 Monitor* monitor) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700325 Thread* current_owner = nullptr;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800326 std::string current_owner_string;
327 std::string expected_owner_string;
328 std::string found_owner_string;
329 {
330 // TODO: isn't this too late to prevent threads from disappearing?
331 // Acquire thread list lock so threads won't disappear from under us.
Ian Rogers50b35e22012-10-04 10:09:15 -0700332 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Elliott Hughesffb465f2012-03-01 18:46:05 -0800333 // Re-read owner now that we hold lock.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700334 current_owner = (monitor != nullptr) ? monitor->GetOwner() : nullptr;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800335 // Get short descriptions of the threads involved.
336 current_owner_string = ThreadToString(current_owner);
337 expected_owner_string = ThreadToString(expected_owner);
338 found_owner_string = ThreadToString(found_owner);
339 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700340 if (current_owner == nullptr) {
341 if (found_owner == nullptr) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800342 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
343 " on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800344 PrettyTypeOf(o).c_str(),
345 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800346 } else {
347 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800348 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
349 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800350 found_owner_string.c_str(),
351 PrettyTypeOf(o).c_str(),
352 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800353 }
354 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700355 if (found_owner == nullptr) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800356 // Race: originally there was no owner, there is now
357 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
358 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800359 current_owner_string.c_str(),
360 PrettyTypeOf(o).c_str(),
361 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800362 } else {
363 if (found_owner != current_owner) {
364 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800365 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
366 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800367 found_owner_string.c_str(),
368 current_owner_string.c_str(),
369 PrettyTypeOf(o).c_str(),
370 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800371 } else {
372 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
373 " on thread '%s",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800374 current_owner_string.c_str(),
375 PrettyTypeOf(o).c_str(),
376 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800377 }
378 }
379 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700380}
381
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700382bool Monitor::Unlock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700383 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700384 MutexLock mu(self, monitor_lock_);
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800385 Thread* owner = owner_;
386 if (owner == self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700387 // We own the monitor, so nobody else can be in here.
388 if (lock_count_ == 0) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700389 owner_ = nullptr;
390 locking_method_ = nullptr;
Ian Rogers0399dde2012-06-06 17:09:28 -0700391 locking_dex_pc_ = 0;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700392 // Wake a contender.
393 monitor_contenders_.Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700394 } else {
395 --lock_count_;
396 }
397 } else {
398 // We don't own this, so we're not allowed to unlock it.
399 // The JNI spec says that we should throw IllegalMonitorStateException
400 // in this case.
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700401 FailedUnlock(GetObject(), self, owner, this);
Elliott Hughes5f791332011-09-15 17:45:30 -0700402 return false;
403 }
404 return true;
405}
406
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800407void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
408 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700409 DCHECK(self != nullptr);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800410 DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
Elliott Hughes5f791332011-09-15 17:45:30 -0700411
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700412 monitor_lock_.Lock(self);
413
Elliott Hughes5f791332011-09-15 17:45:30 -0700414 // Make sure that we hold the lock.
415 if (owner_ != self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700416 monitor_lock_.Unlock(self);
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700417 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700418 return;
419 }
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800420
Elliott Hughesdf42c482013-01-09 12:49:02 -0800421 // We need to turn a zero-length timed wait into a regular wait because
422 // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
423 if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
424 why = kWaiting;
425 }
426
Elliott Hughes5f791332011-09-15 17:45:30 -0700427 // Enforce the timeout range.
428 if (ms < 0 || ns < 0 || ns > 999999) {
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700429 monitor_lock_.Unlock(self);
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000430 self->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
Ian Rogersef7d42f2014-01-06 12:55:46 -0800431 "timeout arguments out of range: ms=%" PRId64 " ns=%d", ms, ns);
Elliott Hughes5f791332011-09-15 17:45:30 -0700432 return;
433 }
434
Elliott Hughes5f791332011-09-15 17:45:30 -0700435 /*
436 * Add ourselves to the set of threads waiting on this monitor, and
437 * release our hold. We need to let it go even if we're a few levels
438 * deep in a recursive lock, and we need to restore that later.
439 *
440 * We append to the wait set ahead of clearing the count and owner
441 * fields so the subroutine can check that the calling thread owns
442 * the monitor. Aside from that, the order of member updates is
443 * not order sensitive as we hold the pthread mutex.
444 */
445 AppendToWaitSet(self);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700446 ++num_waiters_;
Ian Rogers0399dde2012-06-06 17:09:28 -0700447 int prev_lock_count = lock_count_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700448 lock_count_ = 0;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700449 owner_ = nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700450 ArtMethod* saved_method = locking_method_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700451 locking_method_ = nullptr;
Ian Rogers0399dde2012-06-06 17:09:28 -0700452 uintptr_t saved_dex_pc = locking_dex_pc_;
453 locking_dex_pc_ = 0;
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 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700457 // Update thread state. If the GC wakes up, it'll ignore us, knowing
458 // that we won't touch any references in this state, and we'll check
459 // our suspend mode before we transition out.
460 ScopedThreadSuspension sts(self, why);
461
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700462 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700463 MutexLock mu(self, *self->GetWaitMutex());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700464
465 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700466 // non-null a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700467 // up.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700468 DCHECK(self->GetWaitMonitor() == nullptr);
469 self->SetWaitMonitor(this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700470
471 // Release the monitor lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700472 monitor_contenders_.Signal(self);
473 monitor_lock_.Unlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700474
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800475 // Handle the case where the thread was interrupted before we called wait().
Ian Rogersdd7624d2014-03-14 17:43:00 -0700476 if (self->IsInterruptedLocked()) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800477 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700478 } else {
479 // Wait for a notification or a timeout to occur.
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800480 if (why == kWaiting) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700481 self->GetWaitConditionVariable()->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700482 } else {
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800483 DCHECK(why == kTimedWaiting || why == kSleeping) << why;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700484 self->GetWaitConditionVariable()->TimedWait(self, ms, ns);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700485 }
Hans Boehm328c5dc2015-11-11 16:13:57 -0800486 was_interrupted = self->IsInterruptedLocked();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700487 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700488 }
489
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800490 {
491 // We reset the thread's wait_monitor_ field after transitioning back to runnable so
492 // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
493 // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
494 // are waiting on "null".)
Ian Rogersdd7624d2014-03-14 17:43:00 -0700495 MutexLock mu(self, *self->GetWaitMutex());
496 DCHECK(self->GetWaitMonitor() != nullptr);
497 self->SetWaitMonitor(nullptr);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800498 }
499
Mathieu Chartierdaed5d82016-03-10 10:49:35 -0800500 // Allocate the interrupted exception not holding the monitor lock since it may cause a GC.
501 // If the GC requires acquiring the monitor for enqueuing cleared references, this would
502 // cause a deadlock if the monitor is held.
503 if (was_interrupted && interruptShouldThrow) {
504 /*
505 * We were interrupted while waiting, or somebody interrupted an
506 * un-interruptible thread earlier and we're bailing out immediately.
507 *
508 * The doc sayeth: "The interrupted status of the current thread is
509 * cleared when this exception is thrown."
510 */
511 {
512 MutexLock mu(self, *self->GetWaitMutex());
513 self->SetInterruptedLocked(false);
514 }
515 self->ThrowNewException("Ljava/lang/InterruptedException;", nullptr);
516 }
517
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700518 // Re-acquire the monitor and lock.
Elliott Hughes5f791332011-09-15 17:45:30 -0700519 Lock(self);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700520 monitor_lock_.Lock(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700521 self->GetWaitMutex()->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700522
Elliott Hughes5f791332011-09-15 17:45:30 -0700523 /*
524 * We remove our thread from wait set after restoring the count
525 * and owner fields so the subroutine can check that the calling
526 * thread owns the monitor. Aside from that, the order of member
527 * updates is not order sensitive as we hold the pthread mutex.
528 */
529 owner_ = self;
Ian Rogers0399dde2012-06-06 17:09:28 -0700530 lock_count_ = prev_lock_count;
531 locking_method_ = saved_method;
532 locking_dex_pc_ = saved_dex_pc;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700533 --num_waiters_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700534 RemoveFromWaitSet(self);
535
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700536 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700537}
538
539void Monitor::Notify(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700540 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700541 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700542 // Make sure that we hold the lock.
543 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800544 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700545 return;
546 }
547 // Signal the first waiting thread in the wait set.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700548 while (wait_set_ != nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700549 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700550 wait_set_ = thread->GetWaitNext();
551 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700552
553 // Check to see if the thread is still waiting.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800554 MutexLock wait_mu(self, *thread->GetWaitMutex());
Ian Rogersdd7624d2014-03-14 17:43:00 -0700555 if (thread->GetWaitMonitor() != nullptr) {
556 thread->GetWaitConditionVariable()->Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700557 return;
558 }
559 }
560}
561
562void Monitor::NotifyAll(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700563 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700564 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700565 // Make sure that we hold the lock.
566 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800567 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700568 return;
569 }
570 // Signal all threads in the wait set.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700571 while (wait_set_ != nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700572 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700573 wait_set_ = thread->GetWaitNext();
574 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700575 thread->Notify();
576 }
577}
578
Mathieu Chartier590fee92013-09-13 13:46:47 -0700579bool Monitor::Deflate(Thread* self, mirror::Object* obj) {
580 DCHECK(obj != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700581 // Don't need volatile since we only deflate with mutators suspended.
582 LockWord lw(obj->GetLockWord(false));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700583 // If the lock isn't an inflated monitor, then we don't need to deflate anything.
584 if (lw.GetState() == LockWord::kFatLocked) {
585 Monitor* monitor = lw.FatLockMonitor();
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700586 DCHECK(monitor != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700587 MutexLock mu(self, monitor->monitor_lock_);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700588 // Can't deflate if we have anybody waiting on the CV.
589 if (monitor->num_waiters_ > 0) {
590 return false;
591 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700592 Thread* owner = monitor->owner_;
593 if (owner != nullptr) {
594 // Can't deflate if we are locked and have a hash code.
595 if (monitor->HasHashCode()) {
596 return false;
597 }
598 // Can't deflate if our lock count is too high.
599 if (monitor->lock_count_ > LockWord::kThinLockMaxCount) {
600 return false;
601 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700602 // Deflate to a thin lock.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800603 LockWord new_lw = LockWord::FromThinLockId(owner->GetThreadId(), monitor->lock_count_,
604 lw.ReadBarrierState());
605 // Assume no concurrent read barrier state changes as mutators are suspended.
606 obj->SetLockWord(new_lw, false);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700607 VLOG(monitor) << "Deflated " << obj << " to thin lock " << owner->GetTid() << " / "
608 << monitor->lock_count_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700609 } else if (monitor->HasHashCode()) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800610 LockWord new_lw = LockWord::FromHashCode(monitor->GetHashCode(), lw.ReadBarrierState());
611 // Assume no concurrent read barrier state changes as mutators are suspended.
612 obj->SetLockWord(new_lw, false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700613 VLOG(monitor) << "Deflated " << obj << " to hash monitor " << monitor->GetHashCode();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700614 } else {
615 // No lock and no hash, just put an empty lock word inside the object.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800616 LockWord new_lw = LockWord::FromDefault(lw.ReadBarrierState());
617 // Assume no concurrent read barrier state changes as mutators are suspended.
618 obj->SetLockWord(new_lw, false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700619 VLOG(monitor) << "Deflated" << obj << " to empty lock word";
Mathieu Chartier590fee92013-09-13 13:46:47 -0700620 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700621 // 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 -0700622 // next GC.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700623 monitor->obj_ = GcRoot<mirror::Object>(nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700624 }
625 return true;
626}
627
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700628void Monitor::Inflate(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code) {
Andreas Gampe74240812014-04-17 10:35:09 -0700629 DCHECK(self != nullptr);
630 DCHECK(obj != nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700631 // Allocate and acquire a new monitor.
Andreas Gampe74240812014-04-17 10:35:09 -0700632 Monitor* m = MonitorPool::CreateMonitor(self, owner, obj, hash_code);
633 DCHECK(m != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700634 if (m->Install(self)) {
Haifeng Li86ab7912014-05-16 10:47:59 +0800635 if (owner != nullptr) {
636 VLOG(monitor) << "monitor: thread" << owner->GetThreadId()
Andreas Gampe74240812014-04-17 10:35:09 -0700637 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800638 } else {
639 VLOG(monitor) << "monitor: Inflate with hashcode " << hash_code
Andreas Gampe74240812014-04-17 10:35:09 -0700640 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800641 }
Andreas Gampe74240812014-04-17 10:35:09 -0700642 Runtime::Current()->GetMonitorList()->Add(m);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700643 CHECK_EQ(obj->GetLockWord(true).GetState(), LockWord::kFatLocked);
Andreas Gampe74240812014-04-17 10:35:09 -0700644 } else {
645 MonitorPool::ReleaseMonitor(self, m);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700646 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700647}
648
Mathieu Chartier0cd81352014-05-22 16:48:55 -0700649void Monitor::InflateThinLocked(Thread* self, Handle<mirror::Object> obj, LockWord lock_word,
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700650 uint32_t hash_code) {
651 DCHECK_EQ(lock_word.GetState(), LockWord::kThinLocked);
652 uint32_t owner_thread_id = lock_word.ThinLockOwner();
653 if (owner_thread_id == self->GetThreadId()) {
654 // We own the monitor, we can easily inflate it.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700655 Inflate(self, self, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700656 } else {
657 ThreadList* thread_list = Runtime::Current()->GetThreadList();
658 // Suspend the owner, inflate. First change to blocked and give up mutator_lock_.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700659 self->SetMonitorEnterObject(obj.Get());
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700660 bool timed_out;
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700661 Thread* owner;
662 {
663 ScopedThreadSuspension sts(self, kBlocked);
664 owner = thread_list->SuspendThreadByThreadId(owner_thread_id, false, &timed_out);
665 }
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700666 if (owner != nullptr) {
667 // We succeeded in suspending the thread, check the lock's status didn't change.
668 lock_word = obj->GetLockWord(true);
669 if (lock_word.GetState() == LockWord::kThinLocked &&
670 lock_word.ThinLockOwner() == owner_thread_id) {
671 // Go ahead and inflate the lock.
672 Inflate(self, owner, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700673 }
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700674 thread_list->Resume(owner, false);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700675 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700676 self->SetMonitorEnterObject(nullptr);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700677 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700678}
679
Ian Rogers719d1a32014-03-06 12:13:39 -0800680// Fool annotalysis into thinking that the lock on obj is acquired.
681static mirror::Object* FakeLock(mirror::Object* obj)
682 EXCLUSIVE_LOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
683 return obj;
684}
685
686// Fool annotalysis into thinking that the lock on obj is release.
687static mirror::Object* FakeUnlock(mirror::Object* obj)
688 UNLOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
689 return obj;
690}
691
Mathieu Chartiere7e8a5f2014-02-14 16:59:41 -0800692mirror::Object* Monitor::MonitorEnter(Thread* self, mirror::Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700693 DCHECK(self != nullptr);
694 DCHECK(obj != nullptr);
Mathieu Chartier2d096c92015-10-12 16:18:20 -0700695 self->AssertThreadSuspensionIsAllowable();
Ian Rogers719d1a32014-03-06 12:13:39 -0800696 obj = FakeLock(obj);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700697 uint32_t thread_id = self->GetThreadId();
698 size_t contention_count = 0;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700699 StackHandleScope<1> hs(self);
700 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700701 while (true) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700702 LockWord lock_word = h_obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700703 switch (lock_word.GetState()) {
704 case LockWord::kUnlocked: {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800705 LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0, lock_word.ReadBarrierState()));
Ian Rogers228602f2014-07-10 02:07:54 -0700706 if (h_obj->CasLockWordWeakSequentiallyConsistent(lock_word, thin_locked)) {
Hans Boehm30359612014-05-21 17:46:23 -0700707 // CasLockWord enforces more than the acquire ordering we need here.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700708 return h_obj.Get(); // Success!
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700709 }
710 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -0700711 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700712 case LockWord::kThinLocked: {
713 uint32_t owner_thread_id = lock_word.ThinLockOwner();
714 if (owner_thread_id == thread_id) {
715 // We own the lock, increase the recursion count.
716 uint32_t new_count = lock_word.ThinLockCount() + 1;
717 if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800718 LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count,
719 lock_word.ReadBarrierState()));
720 if (!kUseReadBarrier) {
721 h_obj->SetLockWord(thin_locked, true);
722 return h_obj.Get(); // Success!
723 } else {
724 // Use CAS to preserve the read barrier state.
725 if (h_obj->CasLockWordWeakSequentiallyConsistent(lock_word, thin_locked)) {
726 return h_obj.Get(); // Success!
727 }
728 }
729 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -0700730 } else {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700731 // We'd overflow the recursion count, so inflate the monitor.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700732 InflateThinLocked(self, h_obj, lock_word, 0);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700733 }
734 } else {
735 // Contention.
736 contention_count++;
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700737 Runtime* runtime = Runtime::Current();
738 if (contention_count <= runtime->GetMaxSpinsBeforeThinkLockInflation()) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700739 // TODO: Consider switching the thread state to kBlocked when we are yielding.
Mathieu Chartier251755c2014-07-15 18:10:25 -0700740 // Use sched_yield instead of NanoSleep since NanoSleep can wait much longer than the
741 // parameter you pass in. This can cause thread suspension to take excessively long
Mathieu Chartierb363f662014-07-16 13:28:58 -0700742 // and make long pauses. See b/16307460.
Mathieu Chartier251755c2014-07-15 18:10:25 -0700743 sched_yield();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700744 } else {
745 contention_count = 0;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700746 InflateThinLocked(self, h_obj, lock_word, 0);
Elliott Hughes5f791332011-09-15 17:45:30 -0700747 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700748 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700749 continue; // Start from the beginning.
Elliott Hughes5f791332011-09-15 17:45:30 -0700750 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700751 case LockWord::kFatLocked: {
752 Monitor* mon = lock_word.FatLockMonitor();
753 mon->Lock(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700754 return h_obj.Get(); // Success!
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700755 }
Ian Rogers719d1a32014-03-06 12:13:39 -0800756 case LockWord::kHashCode:
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700757 // Inflate with the existing hashcode.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700758 Inflate(self, nullptr, h_obj.Get(), lock_word.GetHashCode());
Ian Rogers719d1a32014-03-06 12:13:39 -0800759 continue; // Start from the beginning.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700760 default: {
761 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700762 return h_obj.Get();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700763 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700764 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700765 }
766}
767
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800768bool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700769 DCHECK(self != nullptr);
770 DCHECK(obj != nullptr);
Mathieu Chartier2d096c92015-10-12 16:18:20 -0700771 self->AssertThreadSuspensionIsAllowable();
Ian Rogers719d1a32014-03-06 12:13:39 -0800772 obj = FakeUnlock(obj);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700773 StackHandleScope<1> hs(self);
774 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800775 while (true) {
776 LockWord lock_word = obj->GetLockWord(true);
777 switch (lock_word.GetState()) {
778 case LockWord::kHashCode:
779 // Fall-through.
780 case LockWord::kUnlocked:
781 FailedUnlock(h_obj.Get(), self, nullptr, nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700782 return false; // Failure.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800783 case LockWord::kThinLocked: {
784 uint32_t thread_id = self->GetThreadId();
785 uint32_t owner_thread_id = lock_word.ThinLockOwner();
786 if (owner_thread_id != thread_id) {
787 // TODO: there's a race here with the owner dying while we unlock.
788 Thread* owner =
789 Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
790 FailedUnlock(h_obj.Get(), self, owner, nullptr);
791 return false; // Failure.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700792 } else {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800793 // We own the lock, decrease the recursion count.
794 LockWord new_lw = LockWord::Default();
795 if (lock_word.ThinLockCount() != 0) {
796 uint32_t new_count = lock_word.ThinLockCount() - 1;
797 new_lw = LockWord::FromThinLockId(thread_id, new_count, lock_word.ReadBarrierState());
798 } else {
799 new_lw = LockWord::FromDefault(lock_word.ReadBarrierState());
800 }
801 if (!kUseReadBarrier) {
802 DCHECK_EQ(new_lw.ReadBarrierState(), 0U);
803 h_obj->SetLockWord(new_lw, true);
804 // Success!
805 return true;
806 } else {
807 // Use CAS to preserve the read barrier state.
808 if (h_obj->CasLockWordWeakSequentiallyConsistent(lock_word, new_lw)) {
809 // Success!
810 return true;
811 }
812 }
813 continue; // Go again.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700814 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700815 }
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800816 case LockWord::kFatLocked: {
817 Monitor* mon = lock_word.FatLockMonitor();
818 return mon->Unlock(self);
819 }
820 default: {
821 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
822 return false;
823 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700824 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700825 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700826}
827
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800828void Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800829 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700830 DCHECK(self != nullptr);
831 DCHECK(obj != nullptr);
832 LockWord lock_word = obj->GetLockWord(true);
Ian Rogers43c69cc2014-08-15 11:09:28 -0700833 while (lock_word.GetState() != LockWord::kFatLocked) {
834 switch (lock_word.GetState()) {
835 case LockWord::kHashCode:
836 // Fall-through.
837 case LockWord::kUnlocked:
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700838 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
839 return; // Failure.
Ian Rogers43c69cc2014-08-15 11:09:28 -0700840 case LockWord::kThinLocked: {
841 uint32_t thread_id = self->GetThreadId();
842 uint32_t owner_thread_id = lock_word.ThinLockOwner();
843 if (owner_thread_id != thread_id) {
844 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
845 return; // Failure.
846 } else {
847 // We own the lock, inflate to enqueue ourself on the Monitor. May fail spuriously so
848 // re-load.
849 Inflate(self, self, obj, 0);
850 lock_word = obj->GetLockWord(true);
851 }
852 break;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700853 }
Ian Rogers43c69cc2014-08-15 11:09:28 -0700854 case LockWord::kFatLocked: // Unreachable given the loop condition above. Fall-through.
855 default: {
856 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
857 return;
858 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700859 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700860 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700861 Monitor* mon = lock_word.FatLockMonitor();
862 mon->Wait(self, ms, ns, interruptShouldThrow, why);
Elliott Hughes5f791332011-09-15 17:45:30 -0700863}
864
Ian Rogers13c479e2013-10-11 07:59:01 -0700865void Monitor::DoNotify(Thread* self, mirror::Object* obj, bool notify_all) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700866 DCHECK(self != nullptr);
867 DCHECK(obj != nullptr);
868 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700869 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700870 case LockWord::kHashCode:
871 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700872 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800873 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700874 return; // Failure.
875 case LockWord::kThinLocked: {
876 uint32_t thread_id = self->GetThreadId();
877 uint32_t owner_thread_id = lock_word.ThinLockOwner();
878 if (owner_thread_id != thread_id) {
879 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
880 return; // Failure.
881 } else {
882 // We own the lock but there's no Monitor and therefore no waiters.
883 return; // Success.
884 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700885 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700886 case LockWord::kFatLocked: {
887 Monitor* mon = lock_word.FatLockMonitor();
888 if (notify_all) {
889 mon->NotifyAll(self);
890 } else {
891 mon->Notify(self);
892 }
893 return; // Success.
894 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700895 default: {
896 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
897 return;
898 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700899 }
900}
901
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700902uint32_t Monitor::GetLockOwnerThreadId(mirror::Object* obj) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700903 DCHECK(obj != nullptr);
904 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700905 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700906 case LockWord::kHashCode:
907 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700908 case LockWord::kUnlocked:
909 return ThreadList::kInvalidThreadId;
910 case LockWord::kThinLocked:
911 return lock_word.ThinLockOwner();
912 case LockWord::kFatLocked: {
913 Monitor* mon = lock_word.FatLockMonitor();
914 return mon->GetOwnerThreadId();
Elliott Hughes5f791332011-09-15 17:45:30 -0700915 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700916 default: {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700917 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -0700918 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700919 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700920 }
921}
922
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700923void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
Ian Rogersd803bc72014-04-01 15:33:03 -0700924 // Determine the wait message and object we're waiting or blocked upon.
925 mirror::Object* pretty_object = nullptr;
926 const char* wait_message = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700927 uint32_t lock_owner = ThreadList::kInvalidThreadId;
Ian Rogersd803bc72014-04-01 15:33:03 -0700928 ThreadState state = thread->GetState();
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800929 if (state == kWaiting || state == kTimedWaiting || state == kSleeping) {
Ian Rogersd803bc72014-04-01 15:33:03 -0700930 wait_message = (state == kSleeping) ? " - sleeping on " : " - waiting on ";
931 Thread* self = Thread::Current();
932 MutexLock mu(self, *thread->GetWaitMutex());
933 Monitor* monitor = thread->GetWaitMonitor();
934 if (monitor != nullptr) {
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700935 pretty_object = monitor->GetObject();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700936 }
Elliott Hughes34e06962012-04-09 13:55:55 -0700937 } else if (state == kBlocked) {
Ian Rogersd803bc72014-04-01 15:33:03 -0700938 wait_message = " - waiting to lock ";
939 pretty_object = thread->GetMonitorEnterObject();
940 if (pretty_object != nullptr) {
941 lock_owner = pretty_object->GetLockOwnerThreadId();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700942 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700943 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700944
Ian Rogersd803bc72014-04-01 15:33:03 -0700945 if (wait_message != nullptr) {
946 if (pretty_object == nullptr) {
947 os << wait_message << "an unknown object";
948 } else {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700949 if ((pretty_object->GetLockWord(true).GetState() == LockWord::kThinLocked) &&
Ian Rogersd803bc72014-04-01 15:33:03 -0700950 Locks::mutator_lock_->IsExclusiveHeld(Thread::Current())) {
951 // Getting the identity hashcode here would result in lock inflation and suspension of the
952 // current thread, which isn't safe if this is the only runnable thread.
953 os << wait_message << StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)",
954 reinterpret_cast<intptr_t>(pretty_object),
955 PrettyTypeOf(pretty_object).c_str());
956 } else {
957 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
Mathieu Chartier49361592015-01-22 16:36:10 -0800958 // Call PrettyTypeOf before IdentityHashCode since IdentityHashCode can cause thread
959 // suspension and move pretty_object.
960 const std::string pretty_type(PrettyTypeOf(pretty_object));
Ian Rogersd803bc72014-04-01 15:33:03 -0700961 os << wait_message << StringPrintf("<0x%08x> (a %s)", pretty_object->IdentityHashCode(),
Mathieu Chartier49361592015-01-22 16:36:10 -0800962 pretty_type.c_str());
Ian Rogersd803bc72014-04-01 15:33:03 -0700963 }
964 }
965 // - waiting to lock <0x613f83d8> (a java.lang.Object) held by thread 5
966 if (lock_owner != ThreadList::kInvalidThreadId) {
967 os << " held by thread " << lock_owner;
968 }
969 os << "\n";
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700970 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700971}
972
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800973mirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800974 // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
975 // definition of contended that includes a monitor a thread is trying to enter...
Ian Rogersdd7624d2014-03-14 17:43:00 -0700976 mirror::Object* result = thread->GetMonitorEnterObject();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700977 if (result == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700978 // ...but also a monitor that the thread is waiting on.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700979 MutexLock mu(Thread::Current(), *thread->GetWaitMutex());
980 Monitor* monitor = thread->GetWaitMonitor();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700981 if (monitor != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700982 result = monitor->GetObject();
Elliott Hughesf9501702013-01-11 11:22:27 -0800983 }
984 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700985 return result;
Elliott Hughesf9501702013-01-11 11:22:27 -0800986}
987
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800988void Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
Andreas Gampe760172c2014-08-16 13:41:10 -0700989 void* callback_context, bool abort_on_failure) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700990 ArtMethod* m = stack_visitor->GetMethod();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700991 CHECK(m != nullptr);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700992
993 // Native methods are an easy special case.
994 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
995 if (m->IsNative()) {
996 if (m->IsSynchronized()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700997 mirror::Object* jni_this =
998 stack_visitor->GetCurrentHandleScope(sizeof(void*))->GetReference(0);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800999 callback(jni_this, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001000 }
1001 return;
1002 }
1003
jeffhao61f916c2012-10-25 17:48:51 -07001004 // Proxy methods should not be synchronized.
1005 if (m->IsProxyMethod()) {
1006 CHECK(!m->IsSynchronized());
1007 return;
1008 }
1009
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001010 // Is there any reason to believe there's any synchronization in this method?
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001011 const DexFile::CodeItem* code_item = m->GetCodeItem();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001012 CHECK(code_item != nullptr) << PrettyMethod(m);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001013 if (code_item->tries_size_ == 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001014 return; // No "tries" implies no synchronization, so no held locks to report.
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001015 }
1016
Andreas Gampe760172c2014-08-16 13:41:10 -07001017 // Get the dex pc. If abort_on_failure is false, GetDexPc will not abort in the case it cannot
1018 // find the dex pc, and instead return kDexNoIndex. Then bail out, as it indicates we have an
1019 // inconsistent stack anyways.
1020 uint32_t dex_pc = stack_visitor->GetDexPc(abort_on_failure);
1021 if (!abort_on_failure && dex_pc == DexFile::kDexNoIndex) {
1022 LOG(ERROR) << "Could not find dex_pc for " << PrettyMethod(m);
1023 return;
1024 }
1025
Elliott Hughes80537bb2013-01-04 16:37:26 -08001026 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
1027 // the locks held in this stack frame.
1028 std::vector<uint32_t> monitor_enter_dex_pcs;
Andreas Gampe760172c2014-08-16 13:41:10 -07001029 verifier::MethodVerifier::FindLocksAtDexPc(m, dex_pc, &monitor_enter_dex_pcs);
Mathieu Chartiere6a8eec2015-01-06 14:17:57 -08001030 for (uint32_t monitor_dex_pc : monitor_enter_dex_pcs) {
Elliott Hughes80537bb2013-01-04 16:37:26 -08001031 // The verifier works in terms of the dex pcs of the monitor-enter instructions.
1032 // We want the registers used by those instructions (so we can read the values out of them).
Sebastien Hertz0f7c9332015-11-05 15:57:30 +01001033 const Instruction* monitor_enter_instruction =
1034 Instruction::At(&code_item->insns_[monitor_dex_pc]);
Elliott Hughes80537bb2013-01-04 16:37:26 -08001035
1036 // Quick sanity check.
Sebastien Hertz0f7c9332015-11-05 15:57:30 +01001037 CHECK_EQ(monitor_enter_instruction->Opcode(), Instruction::MONITOR_ENTER)
1038 << "expected monitor-enter @" << monitor_dex_pc << "; was "
1039 << reinterpret_cast<const void*>(monitor_enter_instruction);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001040
Sebastien Hertz0f7c9332015-11-05 15:57:30 +01001041 uint16_t monitor_register = monitor_enter_instruction->VRegA();
Nicolas Geoffray15b9d522015-03-12 15:05:13 +00001042 uint32_t value;
1043 bool success = stack_visitor->GetVReg(m, monitor_register, kReferenceVReg, &value);
1044 CHECK(success) << "Failed to read v" << monitor_register << " of kind "
1045 << kReferenceVReg << " in method " << PrettyMethod(m);
1046 mirror::Object* o = reinterpret_cast<mirror::Object*>(value);
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001047 callback(o, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001048 }
1049}
1050
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001051bool Monitor::IsValidLockWord(LockWord lock_word) {
1052 switch (lock_word.GetState()) {
1053 case LockWord::kUnlocked:
1054 // Nothing to check.
1055 return true;
1056 case LockWord::kThinLocked:
1057 // Basic sanity check of owner.
1058 return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
1059 case LockWord::kFatLocked: {
1060 // Check the monitor appears in the monitor list.
1061 Monitor* mon = lock_word.FatLockMonitor();
1062 MonitorList* list = Runtime::Current()->GetMonitorList();
1063 MutexLock mu(Thread::Current(), list->monitor_list_lock_);
1064 for (Monitor* list_mon : list->list_) {
1065 if (mon == list_mon) {
1066 return true; // Found our monitor.
1067 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001068 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001069 return false; // Fail - unowned monitor in an object.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001070 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001071 case LockWord::kHashCode:
1072 return true;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001073 default:
1074 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001075 UNREACHABLE();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001076 }
1077}
1078
Mathieu Chartier90443472015-07-16 20:32:27 -07001079bool Monitor::IsLocked() SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001080 MutexLock mu(Thread::Current(), monitor_lock_);
1081 return owner_ != nullptr;
1082}
1083
Mathieu Chartiere401d142015-04-22 13:56:20 -07001084void Monitor::TranslateLocation(ArtMethod* method, uint32_t dex_pc,
Brian Carlstromeaa46092015-10-07 21:29:28 -07001085 const char** source_file, int32_t* line_number) const {
jeffhao33dc7712011-11-09 17:54:24 -08001086 // If method is null, location is unknown
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001087 if (method == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001088 *source_file = "";
1089 *line_number = 0;
jeffhao33dc7712011-11-09 17:54:24 -08001090 return;
1091 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001092 *source_file = method->GetDeclaringClassSourceFile();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001093 if (*source_file == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001094 *source_file = "";
Elliott Hughes12c51e32012-01-17 20:25:05 -08001095 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001096 *line_number = method->GetLineNumFromDexPC(dex_pc);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001097}
1098
1099uint32_t Monitor::GetOwnerThreadId() {
1100 MutexLock mu(Thread::Current(), monitor_lock_);
1101 Thread* owner = owner_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001102 if (owner != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001103 return owner->GetThreadId();
1104 } else {
1105 return ThreadList::kInvalidThreadId;
1106 }
jeffhao33dc7712011-11-09 17:54:24 -08001107}
1108
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001109MonitorList::MonitorList()
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001110 : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock", kMonitorListLock),
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001111 monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001112}
1113
1114MonitorList::~MonitorList() {
Andreas Gampe74240812014-04-17 10:35:09 -07001115 Thread* self = Thread::Current();
1116 MutexLock mu(self, monitor_list_lock_);
1117 // Release all monitors to the pool.
1118 // TODO: Is it an invariant that *all* open monitors are in the list? Then we could
1119 // clear faster in the pool.
1120 MonitorPool::ReleaseMonitors(self, &list_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001121}
1122
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001123void MonitorList::DisallowNewMonitors() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001124 CHECK(!kUseReadBarrier);
Ian Rogers50b35e22012-10-04 10:09:15 -07001125 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001126 allow_new_monitors_ = false;
1127}
1128
1129void MonitorList::AllowNewMonitors() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001130 CHECK(!kUseReadBarrier);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001131 Thread* self = Thread::Current();
1132 MutexLock mu(self, monitor_list_lock_);
1133 allow_new_monitors_ = true;
1134 monitor_add_condition_.Broadcast(self);
1135}
1136
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001137void MonitorList::BroadcastForNewMonitors() {
1138 CHECK(kUseReadBarrier);
1139 Thread* self = Thread::Current();
1140 MutexLock mu(self, monitor_list_lock_);
1141 monitor_add_condition_.Broadcast(self);
1142}
1143
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001144void MonitorList::Add(Monitor* m) {
1145 Thread* self = Thread::Current();
1146 MutexLock mu(self, monitor_list_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001147 while (UNLIKELY((!kUseReadBarrier && !allow_new_monitors_) ||
1148 (kUseReadBarrier && !self->GetWeakRefAccessEnabled()))) {
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001149 monitor_add_condition_.WaitHoldingLocks(self);
1150 }
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001151 list_.push_front(m);
1152}
1153
Mathieu Chartier97509952015-07-13 14:35:43 -07001154void MonitorList::SweepMonitorList(IsMarkedVisitor* visitor) {
Andreas Gampe74240812014-04-17 10:35:09 -07001155 Thread* self = Thread::Current();
1156 MutexLock mu(self, monitor_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001157 for (auto it = list_.begin(); it != list_.end(); ) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001158 Monitor* m = *it;
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001159 // Disable the read barrier in GetObject() as this is called by GC.
1160 mirror::Object* obj = m->GetObject<kWithoutReadBarrier>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001161 // The object of a monitor can be null if we have deflated it.
Mathieu Chartier97509952015-07-13 14:35:43 -07001162 mirror::Object* new_obj = obj != nullptr ? visitor->IsMarked(obj) : nullptr;
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001163 if (new_obj == nullptr) {
1164 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001165 << obj;
Andreas Gampe74240812014-04-17 10:35:09 -07001166 MonitorPool::ReleaseMonitor(self, m);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001167 it = list_.erase(it);
1168 } else {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001169 m->SetObject(new_obj);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001170 ++it;
1171 }
1172 }
1173}
1174
Mathieu Chartier97509952015-07-13 14:35:43 -07001175class MonitorDeflateVisitor : public IsMarkedVisitor {
1176 public:
1177 MonitorDeflateVisitor() : self_(Thread::Current()), deflate_count_(0) {}
1178
1179 virtual mirror::Object* IsMarked(mirror::Object* object) OVERRIDE
Mathieu Chartier90443472015-07-16 20:32:27 -07001180 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001181 if (Monitor::Deflate(self_, object)) {
1182 DCHECK_NE(object->GetLockWord(true).GetState(), LockWord::kFatLocked);
1183 ++deflate_count_;
1184 // If we deflated, return null so that the monitor gets removed from the array.
1185 return nullptr;
1186 }
1187 return object; // Monitor was not deflated.
1188 }
1189
1190 Thread* const self_;
1191 size_t deflate_count_;
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001192};
1193
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001194size_t MonitorList::DeflateMonitors() {
Mathieu Chartier97509952015-07-13 14:35:43 -07001195 MonitorDeflateVisitor visitor;
1196 Locks::mutator_lock_->AssertExclusiveHeld(visitor.self_);
1197 SweepMonitorList(&visitor);
1198 return visitor.deflate_count_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001199}
1200
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001201MonitorInfo::MonitorInfo(mirror::Object* obj) : owner_(nullptr), entry_count_(0) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001202 DCHECK(obj != nullptr);
1203 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001204 switch (lock_word.GetState()) {
1205 case LockWord::kUnlocked:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001206 // Fall-through.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001207 case LockWord::kForwardingAddress:
1208 // Fall-through.
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001209 case LockWord::kHashCode:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001210 break;
1211 case LockWord::kThinLocked:
1212 owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
1213 entry_count_ = 1 + lock_word.ThinLockCount();
1214 // Thin locks have no waiters.
1215 break;
1216 case LockWord::kFatLocked: {
1217 Monitor* mon = lock_word.FatLockMonitor();
1218 owner_ = mon->owner_;
1219 entry_count_ = 1 + mon->lock_count_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001220 for (Thread* waiter = mon->wait_set_; waiter != nullptr; waiter = waiter->GetWaitNext()) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001221 waiters_.push_back(waiter);
1222 }
1223 break;
Elliott Hughesf327e072013-01-09 16:01:26 -08001224 }
1225 }
1226}
1227
Elliott Hughes5f791332011-09-15 17:45:30 -07001228} // namespace art