blob: 6290cb2ff72fcfd89f342dc928756e542171687f [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
Elliott Hughesfc861622011-10-17 17:57:47 -070070uint32_t Monitor::lock_profiling_threshold_ = 0;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070071
Calin Juravleb2771b42016-04-07 17:09:25 +010072void Monitor::Init(uint32_t lock_profiling_threshold) {
Elliott Hughesfc861622011-10-17 17:57:47 -070073 lock_profiling_threshold_ = lock_profiling_threshold;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070074}
75
Ian Rogersef7d42f2014-01-06 12:55:46 -080076Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code)
Ian Rogers00f7d0e2012-07-19 15:28:27 -070077 : monitor_lock_("a monitor lock", kMonitorLock),
Ian Rogersd9c4fc92013-10-01 19:45:43 -070078 monitor_contenders_("monitor contenders", monitor_lock_),
Mathieu Chartier46bc7782013-11-12 17:03:02 -080079 num_waiters_(0),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070080 owner_(owner),
Elliott Hughes5f791332011-09-15 17:45:30 -070081 lock_count_(0),
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070082 obj_(GcRoot<mirror::Object>(obj)),
Mathieu Chartier2cebb242015-04-21 16:50:40 -070083 wait_set_(nullptr),
Mathieu Chartierad2541a2013-10-25 10:05:23 -070084 hash_code_(hash_code),
Mathieu Chartier2cebb242015-04-21 16:50:40 -070085 locking_method_(nullptr),
Ian Rogersef7d42f2014-01-06 12:55:46 -080086 locking_dex_pc_(0),
Andreas Gampe74240812014-04-17 10:35:09 -070087 monitor_id_(MonitorPool::ComputeMonitorId(this, self)) {
88#ifdef __LP64__
89 DCHECK(false) << "Should not be reached in 64b";
90 next_free_ = nullptr;
91#endif
92 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
93 // with the owner unlocking the thin-lock.
94 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
95 // The identity hash code is set for the life time of the monitor.
96}
97
98Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code,
99 MonitorId id)
100 : monitor_lock_("a monitor lock", kMonitorLock),
101 monitor_contenders_("monitor contenders", monitor_lock_),
102 num_waiters_(0),
103 owner_(owner),
104 lock_count_(0),
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700105 obj_(GcRoot<mirror::Object>(obj)),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700106 wait_set_(nullptr),
Andreas Gampe74240812014-04-17 10:35:09 -0700107 hash_code_(hash_code),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700108 locking_method_(nullptr),
Andreas Gampe74240812014-04-17 10:35:09 -0700109 locking_dex_pc_(0),
110 monitor_id_(id) {
111#ifdef __LP64__
112 next_free_ = nullptr;
113#endif
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700114 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
115 // with the owner unlocking the thin-lock.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800116 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700117 // The identity hash code is set for the life time of the monitor.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700118}
119
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700120int32_t Monitor::GetHashCode() {
121 while (!HasHashCode()) {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700122 if (hash_code_.CompareExchangeWeakRelaxed(0, mirror::Object::GenerateIdentityHashCode())) {
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700123 break;
124 }
125 }
126 DCHECK(HasHashCode());
Ian Rogers3e5cf302014-05-20 16:40:37 -0700127 return hash_code_.LoadRelaxed();
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700128}
129
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700130bool Monitor::Install(Thread* self) {
131 MutexLock mu(self, monitor_lock_); // Uncontended mutex acquisition as monitor isn't yet public.
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700132 CHECK(owner_ == nullptr || owner_ == self || owner_->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700133 // Propagate the lock state.
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700134 LockWord lw(GetObject()->GetLockWord(false));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700135 switch (lw.GetState()) {
136 case LockWord::kThinLocked: {
137 CHECK_EQ(owner_->GetThreadId(), lw.ThinLockOwner());
138 lock_count_ = lw.ThinLockCount();
139 break;
140 }
141 case LockWord::kHashCode: {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700142 CHECK_EQ(hash_code_.LoadRelaxed(), static_cast<int32_t>(lw.GetHashCode()));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700143 break;
144 }
145 case LockWord::kFatLocked: {
146 // The owner_ is suspended but another thread beat us to install a monitor.
147 return false;
148 }
149 case LockWord::kUnlocked: {
150 LOG(FATAL) << "Inflating unlocked lock word";
151 break;
152 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700153 default: {
154 LOG(FATAL) << "Invalid monitor state " << lw.GetState();
155 return false;
156 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700157 }
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800158 LockWord fat(this, lw.ReadBarrierState());
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700159 // Publish the updated lock word, which may race with other threads.
Ian Rogers228602f2014-07-10 02:07:54 -0700160 bool success = GetObject()->CasLockWordWeakSequentiallyConsistent(lw, fat);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700161 // Lock profiling.
Mathieu Chartier9728f912013-10-30 09:45:13 -0700162 if (success && owner_ != nullptr && lock_profiling_threshold_ != 0) {
Andreas Gampe6ec8ebd2014-07-25 13:36:56 -0700163 // Do not abort on dex pc errors. This can easily happen when we want to dump a stack trace on
164 // abort.
165 locking_method_ = owner_->GetCurrentMethod(&locking_dex_pc_, false);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700166 }
167 return success;
Elliott Hughes5f791332011-09-15 17:45:30 -0700168}
169
170Monitor::~Monitor() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700171 // Deflated monitors have a null object.
Elliott Hughes5f791332011-09-15 17:45:30 -0700172}
173
Elliott Hughes5f791332011-09-15 17:45:30 -0700174void Monitor::AppendToWaitSet(Thread* thread) {
175 DCHECK(owner_ == Thread::Current());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700176 DCHECK(thread != nullptr);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700177 DCHECK(thread->GetWaitNext() == nullptr) << thread->GetWaitNext();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700178 if (wait_set_ == nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700179 wait_set_ = thread;
180 return;
181 }
182
183 // push_back.
184 Thread* t = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700185 while (t->GetWaitNext() != nullptr) {
186 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700187 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700188 t->SetWaitNext(thread);
Elliott Hughes5f791332011-09-15 17:45:30 -0700189}
190
Elliott Hughes5f791332011-09-15 17:45:30 -0700191void Monitor::RemoveFromWaitSet(Thread *thread) {
192 DCHECK(owner_ == Thread::Current());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700193 DCHECK(thread != nullptr);
194 if (wait_set_ == nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700195 return;
196 }
197 if (wait_set_ == thread) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700198 wait_set_ = thread->GetWaitNext();
199 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700200 return;
201 }
202
203 Thread* t = wait_set_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700204 while (t->GetWaitNext() != nullptr) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700205 if (t->GetWaitNext() == thread) {
206 t->SetWaitNext(thread->GetWaitNext());
207 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700208 return;
209 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700210 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700211 }
212}
213
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700214void Monitor::SetObject(mirror::Object* object) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700215 obj_ = GcRoot<mirror::Object>(object);
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700216}
217
Elliott Hughes5f791332011-09-15 17:45:30 -0700218void Monitor::Lock(Thread* self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700219 MutexLock mu(self, monitor_lock_);
220 while (true) {
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700221 if (owner_ == nullptr) { // Unowned.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700222 owner_ = self;
223 CHECK_EQ(lock_count_, 0);
224 // When debugging, save the current monitor holder for future
225 // acquisition failures to use in sampled logging.
226 if (lock_profiling_threshold_ != 0) {
227 locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
228 }
229 return;
230 } else if (owner_ == self) { // Recursive.
231 lock_count_++;
232 return;
233 }
234 // Contended.
235 const bool log_contention = (lock_profiling_threshold_ != 0);
Xin Guanb894a192014-08-22 11:55:37 -0500236 uint64_t wait_start_ms = log_contention ? MilliTime() : 0;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700237 ArtMethod* owners_method = locking_method_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700238 uint32_t owners_dex_pc = locking_dex_pc_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700239 // Do this before releasing the lock so that we don't get deflated.
Mathieu Chartierb9001ab2014-10-03 13:28:46 -0700240 size_t num_waiters = num_waiters_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700241 ++num_waiters_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700242 monitor_lock_.Unlock(self); // Let go of locks in order.
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700243 self->SetMonitorEnterObject(GetObject());
Elliott Hughes5f791332011-09-15 17:45:30 -0700244 {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700245 ScopedThreadStateChange tsc(self, kBlocked); // Change to blocked and give up mutator_lock_.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700246 // Reacquire monitor_lock_ without mutator_lock_ for Wait.
247 MutexLock mu2(self, monitor_lock_);
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800248 if (owner_ != nullptr) { // Did the owner_ give the lock up?
249 if (ATRACE_ENABLED()) {
250 std::string name;
251 owner_->GetThreadName(name);
252 ATRACE_BEGIN(("Contended on monitor with owner " + name).c_str());
253 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700254 monitor_contenders_.Wait(self); // Still contended so wait.
255 // Woken from contention.
256 if (log_contention) {
257 uint64_t wait_ms = MilliTime() - wait_start_ms;
258 uint32_t sample_percent;
259 if (wait_ms >= lock_profiling_threshold_) {
260 sample_percent = 100;
261 } else {
262 sample_percent = 100 * wait_ms / lock_profiling_threshold_;
263 }
264 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
265 const char* owners_filename;
Brian Carlstromeaa46092015-10-07 21:29:28 -0700266 int32_t owners_line_number;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700267 TranslateLocation(owners_method, owners_dex_pc, &owners_filename, &owners_line_number);
Mathieu Chartierb9001ab2014-10-03 13:28:46 -0700268 if (wait_ms > kLongWaitMs && owners_method != nullptr) {
269 LOG(WARNING) << "Long monitor contention event with owner method="
270 << PrettyMethod(owners_method) << " from " << owners_filename << ":"
271 << owners_line_number << " waiters=" << num_waiters << " for "
272 << PrettyDuration(MsToNs(wait_ms));
273 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700274 LogContentionEvent(self, wait_ms, sample_percent, owners_filename, owners_line_number);
275 }
276 }
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800277 ATRACE_END();
Elliott Hughesfc861622011-10-17 17:57:47 -0700278 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700279 }
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700280 self->SetMonitorEnterObject(nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700281 monitor_lock_.Lock(self); // Reacquire locks in order.
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700282 --num_waiters_;
Elliott Hughesfc861622011-10-17 17:57:47 -0700283 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700284}
285
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800286static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
287 __attribute__((format(printf, 1, 2)));
288
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700289static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
Mathieu Chartier90443472015-07-16 20:32:27 -0700290 SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800291 va_list args;
292 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800293 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000294 self->ThrowNewExceptionV("Ljava/lang/IllegalMonitorStateException;", fmt, args);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700295 if (!Runtime::Current()->IsStarted() || VLOG_IS_ON(monitor)) {
Brian Carlstrom64277f32012-03-26 23:53:34 -0700296 std::ostringstream ss;
Ian Rogers62d6c772013-02-27 08:32:07 -0800297 self->Dump(ss);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700298 LOG(Runtime::Current()->IsStarted() ? INFO : ERROR)
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000299 << self->GetException()->Dump() << "\n" << ss.str();
Brian Carlstrom64277f32012-03-26 23:53:34 -0700300 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800301 va_end(args);
302}
303
Elliott Hughesd4237412012-02-21 11:24:45 -0800304static std::string ThreadToString(Thread* thread) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700305 if (thread == nullptr) {
306 return "nullptr";
Elliott Hughesd4237412012-02-21 11:24:45 -0800307 }
308 std::ostringstream oss;
309 // TODO: alternatively, we could just return the thread's name.
310 oss << *thread;
311 return oss.str();
312}
313
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800314void Monitor::FailedUnlock(mirror::Object* o, Thread* expected_owner, Thread* found_owner,
Elliott Hughesffb465f2012-03-01 18:46:05 -0800315 Monitor* monitor) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700316 Thread* current_owner = nullptr;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800317 std::string current_owner_string;
318 std::string expected_owner_string;
319 std::string found_owner_string;
320 {
321 // TODO: isn't this too late to prevent threads from disappearing?
322 // Acquire thread list lock so threads won't disappear from under us.
Ian Rogers50b35e22012-10-04 10:09:15 -0700323 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Elliott Hughesffb465f2012-03-01 18:46:05 -0800324 // Re-read owner now that we hold lock.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700325 current_owner = (monitor != nullptr) ? monitor->GetOwner() : nullptr;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800326 // Get short descriptions of the threads involved.
327 current_owner_string = ThreadToString(current_owner);
328 expected_owner_string = ThreadToString(expected_owner);
329 found_owner_string = ThreadToString(found_owner);
330 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700331 if (current_owner == nullptr) {
332 if (found_owner == nullptr) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800333 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
334 " on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800335 PrettyTypeOf(o).c_str(),
336 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800337 } else {
338 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800339 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
340 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800341 found_owner_string.c_str(),
342 PrettyTypeOf(o).c_str(),
343 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800344 }
345 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700346 if (found_owner == nullptr) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800347 // Race: originally there was no owner, there is now
348 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
349 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800350 current_owner_string.c_str(),
351 PrettyTypeOf(o).c_str(),
352 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800353 } else {
354 if (found_owner != current_owner) {
355 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800356 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
357 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800358 found_owner_string.c_str(),
359 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 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
364 " on thread '%s",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800365 current_owner_string.c_str(),
366 PrettyTypeOf(o).c_str(),
367 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800368 }
369 }
370 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700371}
372
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700373bool Monitor::Unlock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700374 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700375 MutexLock mu(self, monitor_lock_);
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800376 Thread* owner = owner_;
377 if (owner == self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700378 // We own the monitor, so nobody else can be in here.
379 if (lock_count_ == 0) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700380 owner_ = nullptr;
381 locking_method_ = nullptr;
Ian Rogers0399dde2012-06-06 17:09:28 -0700382 locking_dex_pc_ = 0;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700383 // Wake a contender.
384 monitor_contenders_.Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700385 } else {
386 --lock_count_;
387 }
388 } else {
389 // We don't own this, so we're not allowed to unlock it.
390 // The JNI spec says that we should throw IllegalMonitorStateException
391 // in this case.
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700392 FailedUnlock(GetObject(), self, owner, this);
Elliott Hughes5f791332011-09-15 17:45:30 -0700393 return false;
394 }
395 return true;
396}
397
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800398void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
399 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700400 DCHECK(self != nullptr);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800401 DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
Elliott Hughes5f791332011-09-15 17:45:30 -0700402
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700403 monitor_lock_.Lock(self);
404
Elliott Hughes5f791332011-09-15 17:45:30 -0700405 // Make sure that we hold the lock.
406 if (owner_ != self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700407 monitor_lock_.Unlock(self);
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700408 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700409 return;
410 }
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800411
Elliott Hughesdf42c482013-01-09 12:49:02 -0800412 // We need to turn a zero-length timed wait into a regular wait because
413 // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
414 if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
415 why = kWaiting;
416 }
417
Elliott Hughes5f791332011-09-15 17:45:30 -0700418 // Enforce the timeout range.
419 if (ms < 0 || ns < 0 || ns > 999999) {
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700420 monitor_lock_.Unlock(self);
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000421 self->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
Ian Rogersef7d42f2014-01-06 12:55:46 -0800422 "timeout arguments out of range: ms=%" PRId64 " ns=%d", ms, ns);
Elliott Hughes5f791332011-09-15 17:45:30 -0700423 return;
424 }
425
Elliott Hughes5f791332011-09-15 17:45:30 -0700426 /*
427 * Add ourselves to the set of threads waiting on this monitor, and
428 * release our hold. We need to let it go even if we're a few levels
429 * deep in a recursive lock, and we need to restore that later.
430 *
431 * We append to the wait set ahead of clearing the count and owner
432 * fields so the subroutine can check that the calling thread owns
433 * the monitor. Aside from that, the order of member updates is
434 * not order sensitive as we hold the pthread mutex.
435 */
436 AppendToWaitSet(self);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700437 ++num_waiters_;
Ian Rogers0399dde2012-06-06 17:09:28 -0700438 int prev_lock_count = lock_count_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700439 lock_count_ = 0;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700440 owner_ = nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700441 ArtMethod* saved_method = locking_method_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700442 locking_method_ = nullptr;
Ian Rogers0399dde2012-06-06 17:09:28 -0700443 uintptr_t saved_dex_pc = locking_dex_pc_;
444 locking_dex_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700445
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800446 bool was_interrupted = false;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700447 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700448 // Update thread state. If the GC wakes up, it'll ignore us, knowing
449 // that we won't touch any references in this state, and we'll check
450 // our suspend mode before we transition out.
451 ScopedThreadSuspension sts(self, why);
452
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700453 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700454 MutexLock mu(self, *self->GetWaitMutex());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700455
456 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700457 // non-null a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700458 // up.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700459 DCHECK(self->GetWaitMonitor() == nullptr);
460 self->SetWaitMonitor(this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700461
462 // Release the monitor lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700463 monitor_contenders_.Signal(self);
464 monitor_lock_.Unlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700465
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800466 // Handle the case where the thread was interrupted before we called wait().
Ian Rogersdd7624d2014-03-14 17:43:00 -0700467 if (self->IsInterruptedLocked()) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800468 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700469 } else {
470 // Wait for a notification or a timeout to occur.
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800471 if (why == kWaiting) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700472 self->GetWaitConditionVariable()->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700473 } else {
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800474 DCHECK(why == kTimedWaiting || why == kSleeping) << why;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700475 self->GetWaitConditionVariable()->TimedWait(self, ms, ns);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700476 }
Hans Boehm328c5dc2015-11-11 16:13:57 -0800477 was_interrupted = self->IsInterruptedLocked();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700478 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700479 }
480
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800481 {
482 // We reset the thread's wait_monitor_ field after transitioning back to runnable so
483 // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
484 // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
485 // are waiting on "null".)
Ian Rogersdd7624d2014-03-14 17:43:00 -0700486 MutexLock mu(self, *self->GetWaitMutex());
487 DCHECK(self->GetWaitMonitor() != nullptr);
488 self->SetWaitMonitor(nullptr);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800489 }
490
Mathieu Chartierdaed5d82016-03-10 10:49:35 -0800491 // Allocate the interrupted exception not holding the monitor lock since it may cause a GC.
492 // If the GC requires acquiring the monitor for enqueuing cleared references, this would
493 // cause a deadlock if the monitor is held.
494 if (was_interrupted && interruptShouldThrow) {
495 /*
496 * We were interrupted while waiting, or somebody interrupted an
497 * un-interruptible thread earlier and we're bailing out immediately.
498 *
499 * The doc sayeth: "The interrupted status of the current thread is
500 * cleared when this exception is thrown."
501 */
502 {
503 MutexLock mu(self, *self->GetWaitMutex());
504 self->SetInterruptedLocked(false);
505 }
506 self->ThrowNewException("Ljava/lang/InterruptedException;", nullptr);
507 }
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);
Elliott Hughes5f791332011-09-15 17:45:30 -0700528}
529
530void Monitor::Notify(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700531 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700532 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700533 // Make sure that we hold the lock.
534 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800535 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700536 return;
537 }
538 // Signal the first waiting thread in the wait set.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700539 while (wait_set_ != nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700540 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700541 wait_set_ = thread->GetWaitNext();
542 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700543
544 // Check to see if the thread is still waiting.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800545 MutexLock wait_mu(self, *thread->GetWaitMutex());
Ian Rogersdd7624d2014-03-14 17:43:00 -0700546 if (thread->GetWaitMonitor() != nullptr) {
547 thread->GetWaitConditionVariable()->Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700548 return;
549 }
550 }
551}
552
553void Monitor::NotifyAll(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700554 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700555 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700556 // Make sure that we hold the lock.
557 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800558 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700559 return;
560 }
561 // Signal all threads in the wait set.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700562 while (wait_set_ != nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700563 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700564 wait_set_ = thread->GetWaitNext();
565 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700566 thread->Notify();
567 }
568}
569
Mathieu Chartier590fee92013-09-13 13:46:47 -0700570bool Monitor::Deflate(Thread* self, mirror::Object* obj) {
571 DCHECK(obj != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700572 // Don't need volatile since we only deflate with mutators suspended.
573 LockWord lw(obj->GetLockWord(false));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700574 // If the lock isn't an inflated monitor, then we don't need to deflate anything.
575 if (lw.GetState() == LockWord::kFatLocked) {
576 Monitor* monitor = lw.FatLockMonitor();
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700577 DCHECK(monitor != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700578 MutexLock mu(self, monitor->monitor_lock_);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700579 // Can't deflate if we have anybody waiting on the CV.
580 if (monitor->num_waiters_ > 0) {
581 return false;
582 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700583 Thread* owner = monitor->owner_;
584 if (owner != nullptr) {
585 // Can't deflate if we are locked and have a hash code.
586 if (monitor->HasHashCode()) {
587 return false;
588 }
589 // Can't deflate if our lock count is too high.
590 if (monitor->lock_count_ > LockWord::kThinLockMaxCount) {
591 return false;
592 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700593 // Deflate to a thin lock.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800594 LockWord new_lw = LockWord::FromThinLockId(owner->GetThreadId(), monitor->lock_count_,
595 lw.ReadBarrierState());
596 // Assume no concurrent read barrier state changes as mutators are suspended.
597 obj->SetLockWord(new_lw, false);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700598 VLOG(monitor) << "Deflated " << obj << " to thin lock " << owner->GetTid() << " / "
599 << monitor->lock_count_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700600 } else if (monitor->HasHashCode()) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800601 LockWord new_lw = LockWord::FromHashCode(monitor->GetHashCode(), lw.ReadBarrierState());
602 // Assume no concurrent read barrier state changes as mutators are suspended.
603 obj->SetLockWord(new_lw, false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700604 VLOG(monitor) << "Deflated " << obj << " to hash monitor " << monitor->GetHashCode();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700605 } else {
606 // No lock and no hash, just put an empty lock word inside the object.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800607 LockWord new_lw = LockWord::FromDefault(lw.ReadBarrierState());
608 // Assume no concurrent read barrier state changes as mutators are suspended.
609 obj->SetLockWord(new_lw, false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700610 VLOG(monitor) << "Deflated" << obj << " to empty lock word";
Mathieu Chartier590fee92013-09-13 13:46:47 -0700611 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700612 // 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 -0700613 // next GC.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700614 monitor->obj_ = GcRoot<mirror::Object>(nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700615 }
616 return true;
617}
618
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700619void Monitor::Inflate(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code) {
Andreas Gampe74240812014-04-17 10:35:09 -0700620 DCHECK(self != nullptr);
621 DCHECK(obj != nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700622 // Allocate and acquire a new monitor.
Andreas Gampe74240812014-04-17 10:35:09 -0700623 Monitor* m = MonitorPool::CreateMonitor(self, owner, obj, hash_code);
624 DCHECK(m != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700625 if (m->Install(self)) {
Haifeng Li86ab7912014-05-16 10:47:59 +0800626 if (owner != nullptr) {
627 VLOG(monitor) << "monitor: thread" << owner->GetThreadId()
Andreas Gampe74240812014-04-17 10:35:09 -0700628 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800629 } else {
630 VLOG(monitor) << "monitor: Inflate with hashcode " << hash_code
Andreas Gampe74240812014-04-17 10:35:09 -0700631 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800632 }
Andreas Gampe74240812014-04-17 10:35:09 -0700633 Runtime::Current()->GetMonitorList()->Add(m);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700634 CHECK_EQ(obj->GetLockWord(true).GetState(), LockWord::kFatLocked);
Andreas Gampe74240812014-04-17 10:35:09 -0700635 } else {
636 MonitorPool::ReleaseMonitor(self, m);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700637 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700638}
639
Mathieu Chartier0cd81352014-05-22 16:48:55 -0700640void Monitor::InflateThinLocked(Thread* self, Handle<mirror::Object> obj, LockWord lock_word,
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700641 uint32_t hash_code) {
642 DCHECK_EQ(lock_word.GetState(), LockWord::kThinLocked);
643 uint32_t owner_thread_id = lock_word.ThinLockOwner();
644 if (owner_thread_id == self->GetThreadId()) {
645 // We own the monitor, we can easily inflate it.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700646 Inflate(self, self, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700647 } else {
648 ThreadList* thread_list = Runtime::Current()->GetThreadList();
649 // Suspend the owner, inflate. First change to blocked and give up mutator_lock_.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700650 self->SetMonitorEnterObject(obj.Get());
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700651 bool timed_out;
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700652 Thread* owner;
653 {
654 ScopedThreadSuspension sts(self, kBlocked);
655 owner = thread_list->SuspendThreadByThreadId(owner_thread_id, false, &timed_out);
656 }
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700657 if (owner != nullptr) {
658 // We succeeded in suspending the thread, check the lock's status didn't change.
659 lock_word = obj->GetLockWord(true);
660 if (lock_word.GetState() == LockWord::kThinLocked &&
661 lock_word.ThinLockOwner() == owner_thread_id) {
662 // Go ahead and inflate the lock.
663 Inflate(self, owner, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700664 }
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700665 thread_list->Resume(owner, false);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700666 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700667 self->SetMonitorEnterObject(nullptr);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700668 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700669}
670
Ian Rogers719d1a32014-03-06 12:13:39 -0800671// Fool annotalysis into thinking that the lock on obj is acquired.
672static mirror::Object* FakeLock(mirror::Object* obj)
673 EXCLUSIVE_LOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
674 return obj;
675}
676
677// Fool annotalysis into thinking that the lock on obj is release.
678static mirror::Object* FakeUnlock(mirror::Object* obj)
679 UNLOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
680 return obj;
681}
682
Mathieu Chartiere7e8a5f2014-02-14 16:59:41 -0800683mirror::Object* Monitor::MonitorEnter(Thread* self, mirror::Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700684 DCHECK(self != nullptr);
685 DCHECK(obj != nullptr);
Mathieu Chartier2d096c92015-10-12 16:18:20 -0700686 self->AssertThreadSuspensionIsAllowable();
Ian Rogers719d1a32014-03-06 12:13:39 -0800687 obj = FakeLock(obj);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700688 uint32_t thread_id = self->GetThreadId();
689 size_t contention_count = 0;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700690 StackHandleScope<1> hs(self);
691 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700692 while (true) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700693 LockWord lock_word = h_obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700694 switch (lock_word.GetState()) {
695 case LockWord::kUnlocked: {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800696 LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0, lock_word.ReadBarrierState()));
Ian Rogers228602f2014-07-10 02:07:54 -0700697 if (h_obj->CasLockWordWeakSequentiallyConsistent(lock_word, thin_locked)) {
Hans Boehm30359612014-05-21 17:46:23 -0700698 // CasLockWord enforces more than the acquire ordering we need here.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700699 return h_obj.Get(); // Success!
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700700 }
701 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -0700702 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700703 case LockWord::kThinLocked: {
704 uint32_t owner_thread_id = lock_word.ThinLockOwner();
705 if (owner_thread_id == thread_id) {
706 // We own the lock, increase the recursion count.
707 uint32_t new_count = lock_word.ThinLockCount() + 1;
708 if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800709 LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count,
710 lock_word.ReadBarrierState()));
711 if (!kUseReadBarrier) {
712 h_obj->SetLockWord(thin_locked, true);
713 return h_obj.Get(); // Success!
714 } else {
715 // Use CAS to preserve the read barrier state.
716 if (h_obj->CasLockWordWeakSequentiallyConsistent(lock_word, thin_locked)) {
717 return h_obj.Get(); // Success!
718 }
719 }
720 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -0700721 } else {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700722 // We'd overflow the recursion count, so inflate the monitor.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700723 InflateThinLocked(self, h_obj, lock_word, 0);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700724 }
725 } else {
726 // Contention.
727 contention_count++;
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700728 Runtime* runtime = Runtime::Current();
729 if (contention_count <= runtime->GetMaxSpinsBeforeThinkLockInflation()) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700730 // TODO: Consider switching the thread state to kBlocked when we are yielding.
Mathieu Chartier251755c2014-07-15 18:10:25 -0700731 // Use sched_yield instead of NanoSleep since NanoSleep can wait much longer than the
732 // parameter you pass in. This can cause thread suspension to take excessively long
Mathieu Chartierb363f662014-07-16 13:28:58 -0700733 // and make long pauses. See b/16307460.
Mathieu Chartier251755c2014-07-15 18:10:25 -0700734 sched_yield();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700735 } else {
736 contention_count = 0;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700737 InflateThinLocked(self, h_obj, lock_word, 0);
Elliott Hughes5f791332011-09-15 17:45:30 -0700738 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700739 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700740 continue; // Start from the beginning.
Elliott Hughes5f791332011-09-15 17:45:30 -0700741 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700742 case LockWord::kFatLocked: {
743 Monitor* mon = lock_word.FatLockMonitor();
744 mon->Lock(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700745 return h_obj.Get(); // Success!
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700746 }
Ian Rogers719d1a32014-03-06 12:13:39 -0800747 case LockWord::kHashCode:
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700748 // Inflate with the existing hashcode.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700749 Inflate(self, nullptr, h_obj.Get(), lock_word.GetHashCode());
Ian Rogers719d1a32014-03-06 12:13:39 -0800750 continue; // Start from the beginning.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700751 default: {
752 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700753 return h_obj.Get();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700754 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700755 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700756 }
757}
758
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800759bool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700760 DCHECK(self != nullptr);
761 DCHECK(obj != nullptr);
Mathieu Chartier2d096c92015-10-12 16:18:20 -0700762 self->AssertThreadSuspensionIsAllowable();
Ian Rogers719d1a32014-03-06 12:13:39 -0800763 obj = FakeUnlock(obj);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700764 StackHandleScope<1> hs(self);
765 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800766 while (true) {
767 LockWord lock_word = obj->GetLockWord(true);
768 switch (lock_word.GetState()) {
769 case LockWord::kHashCode:
770 // Fall-through.
771 case LockWord::kUnlocked:
772 FailedUnlock(h_obj.Get(), self, nullptr, nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700773 return false; // Failure.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800774 case LockWord::kThinLocked: {
775 uint32_t thread_id = self->GetThreadId();
776 uint32_t owner_thread_id = lock_word.ThinLockOwner();
777 if (owner_thread_id != thread_id) {
778 // TODO: there's a race here with the owner dying while we unlock.
779 Thread* owner =
780 Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
781 FailedUnlock(h_obj.Get(), self, owner, nullptr);
782 return false; // Failure.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700783 } else {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800784 // We own the lock, decrease the recursion count.
785 LockWord new_lw = LockWord::Default();
786 if (lock_word.ThinLockCount() != 0) {
787 uint32_t new_count = lock_word.ThinLockCount() - 1;
788 new_lw = LockWord::FromThinLockId(thread_id, new_count, lock_word.ReadBarrierState());
789 } else {
790 new_lw = LockWord::FromDefault(lock_word.ReadBarrierState());
791 }
792 if (!kUseReadBarrier) {
793 DCHECK_EQ(new_lw.ReadBarrierState(), 0U);
794 h_obj->SetLockWord(new_lw, true);
795 // Success!
796 return true;
797 } else {
798 // Use CAS to preserve the read barrier state.
799 if (h_obj->CasLockWordWeakSequentiallyConsistent(lock_word, new_lw)) {
800 // Success!
801 return true;
802 }
803 }
804 continue; // Go again.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700805 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700806 }
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800807 case LockWord::kFatLocked: {
808 Monitor* mon = lock_word.FatLockMonitor();
809 return mon->Unlock(self);
810 }
811 default: {
812 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
813 return false;
814 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700815 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700816 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700817}
818
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800819void Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800820 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700821 DCHECK(self != nullptr);
822 DCHECK(obj != nullptr);
823 LockWord lock_word = obj->GetLockWord(true);
Ian Rogers43c69cc2014-08-15 11:09:28 -0700824 while (lock_word.GetState() != LockWord::kFatLocked) {
825 switch (lock_word.GetState()) {
826 case LockWord::kHashCode:
827 // Fall-through.
828 case LockWord::kUnlocked:
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700829 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
830 return; // Failure.
Ian Rogers43c69cc2014-08-15 11:09:28 -0700831 case LockWord::kThinLocked: {
832 uint32_t thread_id = self->GetThreadId();
833 uint32_t owner_thread_id = lock_word.ThinLockOwner();
834 if (owner_thread_id != thread_id) {
835 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
836 return; // Failure.
837 } else {
838 // We own the lock, inflate to enqueue ourself on the Monitor. May fail spuriously so
839 // re-load.
840 Inflate(self, self, obj, 0);
841 lock_word = obj->GetLockWord(true);
842 }
843 break;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700844 }
Ian Rogers43c69cc2014-08-15 11:09:28 -0700845 case LockWord::kFatLocked: // Unreachable given the loop condition above. Fall-through.
846 default: {
847 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
848 return;
849 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700850 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700851 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700852 Monitor* mon = lock_word.FatLockMonitor();
853 mon->Wait(self, ms, ns, interruptShouldThrow, why);
Elliott Hughes5f791332011-09-15 17:45:30 -0700854}
855
Ian Rogers13c479e2013-10-11 07:59:01 -0700856void Monitor::DoNotify(Thread* self, mirror::Object* obj, bool notify_all) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700857 DCHECK(self != nullptr);
858 DCHECK(obj != nullptr);
859 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700860 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700861 case LockWord::kHashCode:
862 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700863 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800864 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700865 return; // Failure.
866 case LockWord::kThinLocked: {
867 uint32_t thread_id = self->GetThreadId();
868 uint32_t owner_thread_id = lock_word.ThinLockOwner();
869 if (owner_thread_id != thread_id) {
870 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
871 return; // Failure.
872 } else {
873 // We own the lock but there's no Monitor and therefore no waiters.
874 return; // Success.
875 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700876 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700877 case LockWord::kFatLocked: {
878 Monitor* mon = lock_word.FatLockMonitor();
879 if (notify_all) {
880 mon->NotifyAll(self);
881 } else {
882 mon->Notify(self);
883 }
884 return; // Success.
885 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700886 default: {
887 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
888 return;
889 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700890 }
891}
892
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700893uint32_t Monitor::GetLockOwnerThreadId(mirror::Object* obj) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700894 DCHECK(obj != nullptr);
895 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700896 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700897 case LockWord::kHashCode:
898 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700899 case LockWord::kUnlocked:
900 return ThreadList::kInvalidThreadId;
901 case LockWord::kThinLocked:
902 return lock_word.ThinLockOwner();
903 case LockWord::kFatLocked: {
904 Monitor* mon = lock_word.FatLockMonitor();
905 return mon->GetOwnerThreadId();
Elliott Hughes5f791332011-09-15 17:45:30 -0700906 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700907 default: {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700908 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -0700909 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700910 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700911 }
912}
913
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700914void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
Ian Rogersd803bc72014-04-01 15:33:03 -0700915 // Determine the wait message and object we're waiting or blocked upon.
916 mirror::Object* pretty_object = nullptr;
917 const char* wait_message = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700918 uint32_t lock_owner = ThreadList::kInvalidThreadId;
Ian Rogersd803bc72014-04-01 15:33:03 -0700919 ThreadState state = thread->GetState();
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800920 if (state == kWaiting || state == kTimedWaiting || state == kSleeping) {
Ian Rogersd803bc72014-04-01 15:33:03 -0700921 wait_message = (state == kSleeping) ? " - sleeping on " : " - waiting on ";
922 Thread* self = Thread::Current();
923 MutexLock mu(self, *thread->GetWaitMutex());
924 Monitor* monitor = thread->GetWaitMonitor();
925 if (monitor != nullptr) {
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700926 pretty_object = monitor->GetObject();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700927 }
Elliott Hughes34e06962012-04-09 13:55:55 -0700928 } else if (state == kBlocked) {
Ian Rogersd803bc72014-04-01 15:33:03 -0700929 wait_message = " - waiting to lock ";
930 pretty_object = thread->GetMonitorEnterObject();
931 if (pretty_object != nullptr) {
932 lock_owner = pretty_object->GetLockOwnerThreadId();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700933 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700934 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700935
Ian Rogersd803bc72014-04-01 15:33:03 -0700936 if (wait_message != nullptr) {
937 if (pretty_object == nullptr) {
938 os << wait_message << "an unknown object";
939 } else {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700940 if ((pretty_object->GetLockWord(true).GetState() == LockWord::kThinLocked) &&
Ian Rogersd803bc72014-04-01 15:33:03 -0700941 Locks::mutator_lock_->IsExclusiveHeld(Thread::Current())) {
942 // Getting the identity hashcode here would result in lock inflation and suspension of the
943 // current thread, which isn't safe if this is the only runnable thread.
944 os << wait_message << StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)",
945 reinterpret_cast<intptr_t>(pretty_object),
946 PrettyTypeOf(pretty_object).c_str());
947 } else {
948 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
Mathieu Chartier49361592015-01-22 16:36:10 -0800949 // Call PrettyTypeOf before IdentityHashCode since IdentityHashCode can cause thread
950 // suspension and move pretty_object.
951 const std::string pretty_type(PrettyTypeOf(pretty_object));
Ian Rogersd803bc72014-04-01 15:33:03 -0700952 os << wait_message << StringPrintf("<0x%08x> (a %s)", pretty_object->IdentityHashCode(),
Mathieu Chartier49361592015-01-22 16:36:10 -0800953 pretty_type.c_str());
Ian Rogersd803bc72014-04-01 15:33:03 -0700954 }
955 }
956 // - waiting to lock <0x613f83d8> (a java.lang.Object) held by thread 5
957 if (lock_owner != ThreadList::kInvalidThreadId) {
958 os << " held by thread " << lock_owner;
959 }
960 os << "\n";
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700961 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700962}
963
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800964mirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800965 // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
966 // definition of contended that includes a monitor a thread is trying to enter...
Ian Rogersdd7624d2014-03-14 17:43:00 -0700967 mirror::Object* result = thread->GetMonitorEnterObject();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700968 if (result == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700969 // ...but also a monitor that the thread is waiting on.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700970 MutexLock mu(Thread::Current(), *thread->GetWaitMutex());
971 Monitor* monitor = thread->GetWaitMonitor();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700972 if (monitor != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700973 result = monitor->GetObject();
Elliott Hughesf9501702013-01-11 11:22:27 -0800974 }
975 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700976 return result;
Elliott Hughesf9501702013-01-11 11:22:27 -0800977}
978
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800979void Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
Andreas Gampe760172c2014-08-16 13:41:10 -0700980 void* callback_context, bool abort_on_failure) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700981 ArtMethod* m = stack_visitor->GetMethod();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700982 CHECK(m != nullptr);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700983
984 // Native methods are an easy special case.
985 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
986 if (m->IsNative()) {
987 if (m->IsSynchronized()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700988 mirror::Object* jni_this =
989 stack_visitor->GetCurrentHandleScope(sizeof(void*))->GetReference(0);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800990 callback(jni_this, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700991 }
992 return;
993 }
994
jeffhao61f916c2012-10-25 17:48:51 -0700995 // Proxy methods should not be synchronized.
996 if (m->IsProxyMethod()) {
997 CHECK(!m->IsSynchronized());
998 return;
999 }
1000
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001001 // Is there any reason to believe there's any synchronization in this method?
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001002 const DexFile::CodeItem* code_item = m->GetCodeItem();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001003 CHECK(code_item != nullptr) << PrettyMethod(m);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001004 if (code_item->tries_size_ == 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001005 return; // No "tries" implies no synchronization, so no held locks to report.
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001006 }
1007
Andreas Gampe760172c2014-08-16 13:41:10 -07001008 // Get the dex pc. If abort_on_failure is false, GetDexPc will not abort in the case it cannot
1009 // find the dex pc, and instead return kDexNoIndex. Then bail out, as it indicates we have an
1010 // inconsistent stack anyways.
1011 uint32_t dex_pc = stack_visitor->GetDexPc(abort_on_failure);
1012 if (!abort_on_failure && dex_pc == DexFile::kDexNoIndex) {
1013 LOG(ERROR) << "Could not find dex_pc for " << PrettyMethod(m);
1014 return;
1015 }
1016
Elliott Hughes80537bb2013-01-04 16:37:26 -08001017 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
1018 // the locks held in this stack frame.
1019 std::vector<uint32_t> monitor_enter_dex_pcs;
Andreas Gampe760172c2014-08-16 13:41:10 -07001020 verifier::MethodVerifier::FindLocksAtDexPc(m, dex_pc, &monitor_enter_dex_pcs);
Mathieu Chartiere6a8eec2015-01-06 14:17:57 -08001021 for (uint32_t monitor_dex_pc : monitor_enter_dex_pcs) {
Elliott Hughes80537bb2013-01-04 16:37:26 -08001022 // The verifier works in terms of the dex pcs of the monitor-enter instructions.
1023 // We want the registers used by those instructions (so we can read the values out of them).
Sebastien Hertz0f7c9332015-11-05 15:57:30 +01001024 const Instruction* monitor_enter_instruction =
1025 Instruction::At(&code_item->insns_[monitor_dex_pc]);
Elliott Hughes80537bb2013-01-04 16:37:26 -08001026
1027 // Quick sanity check.
Sebastien Hertz0f7c9332015-11-05 15:57:30 +01001028 CHECK_EQ(monitor_enter_instruction->Opcode(), Instruction::MONITOR_ENTER)
1029 << "expected monitor-enter @" << monitor_dex_pc << "; was "
1030 << reinterpret_cast<const void*>(monitor_enter_instruction);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001031
Sebastien Hertz0f7c9332015-11-05 15:57:30 +01001032 uint16_t monitor_register = monitor_enter_instruction->VRegA();
Nicolas Geoffray15b9d522015-03-12 15:05:13 +00001033 uint32_t value;
1034 bool success = stack_visitor->GetVReg(m, monitor_register, kReferenceVReg, &value);
1035 CHECK(success) << "Failed to read v" << monitor_register << " of kind "
1036 << kReferenceVReg << " in method " << PrettyMethod(m);
1037 mirror::Object* o = reinterpret_cast<mirror::Object*>(value);
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001038 callback(o, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001039 }
1040}
1041
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001042bool Monitor::IsValidLockWord(LockWord lock_word) {
1043 switch (lock_word.GetState()) {
1044 case LockWord::kUnlocked:
1045 // Nothing to check.
1046 return true;
1047 case LockWord::kThinLocked:
1048 // Basic sanity check of owner.
1049 return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
1050 case LockWord::kFatLocked: {
1051 // Check the monitor appears in the monitor list.
1052 Monitor* mon = lock_word.FatLockMonitor();
1053 MonitorList* list = Runtime::Current()->GetMonitorList();
1054 MutexLock mu(Thread::Current(), list->monitor_list_lock_);
1055 for (Monitor* list_mon : list->list_) {
1056 if (mon == list_mon) {
1057 return true; // Found our monitor.
1058 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001059 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001060 return false; // Fail - unowned monitor in an object.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001061 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001062 case LockWord::kHashCode:
1063 return true;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001064 default:
1065 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001066 UNREACHABLE();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001067 }
1068}
1069
Mathieu Chartier90443472015-07-16 20:32:27 -07001070bool Monitor::IsLocked() SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001071 MutexLock mu(Thread::Current(), monitor_lock_);
1072 return owner_ != nullptr;
1073}
1074
Mathieu Chartiere401d142015-04-22 13:56:20 -07001075void Monitor::TranslateLocation(ArtMethod* method, uint32_t dex_pc,
Brian Carlstromeaa46092015-10-07 21:29:28 -07001076 const char** source_file, int32_t* line_number) const {
jeffhao33dc7712011-11-09 17:54:24 -08001077 // If method is null, location is unknown
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001078 if (method == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001079 *source_file = "";
1080 *line_number = 0;
jeffhao33dc7712011-11-09 17:54:24 -08001081 return;
1082 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001083 *source_file = method->GetDeclaringClassSourceFile();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001084 if (*source_file == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001085 *source_file = "";
Elliott Hughes12c51e32012-01-17 20:25:05 -08001086 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001087 *line_number = method->GetLineNumFromDexPC(dex_pc);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001088}
1089
1090uint32_t Monitor::GetOwnerThreadId() {
1091 MutexLock mu(Thread::Current(), monitor_lock_);
1092 Thread* owner = owner_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001093 if (owner != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001094 return owner->GetThreadId();
1095 } else {
1096 return ThreadList::kInvalidThreadId;
1097 }
jeffhao33dc7712011-11-09 17:54:24 -08001098}
1099
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001100MonitorList::MonitorList()
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001101 : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock", kMonitorListLock),
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001102 monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001103}
1104
1105MonitorList::~MonitorList() {
Andreas Gampe74240812014-04-17 10:35:09 -07001106 Thread* self = Thread::Current();
1107 MutexLock mu(self, monitor_list_lock_);
1108 // Release all monitors to the pool.
1109 // TODO: Is it an invariant that *all* open monitors are in the list? Then we could
1110 // clear faster in the pool.
1111 MonitorPool::ReleaseMonitors(self, &list_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001112}
1113
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001114void MonitorList::DisallowNewMonitors() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001115 CHECK(!kUseReadBarrier);
Ian Rogers50b35e22012-10-04 10:09:15 -07001116 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001117 allow_new_monitors_ = false;
1118}
1119
1120void MonitorList::AllowNewMonitors() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001121 CHECK(!kUseReadBarrier);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001122 Thread* self = Thread::Current();
1123 MutexLock mu(self, monitor_list_lock_);
1124 allow_new_monitors_ = true;
1125 monitor_add_condition_.Broadcast(self);
1126}
1127
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001128void MonitorList::BroadcastForNewMonitors() {
1129 CHECK(kUseReadBarrier);
1130 Thread* self = Thread::Current();
1131 MutexLock mu(self, monitor_list_lock_);
1132 monitor_add_condition_.Broadcast(self);
1133}
1134
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001135void MonitorList::Add(Monitor* m) {
1136 Thread* self = Thread::Current();
1137 MutexLock mu(self, monitor_list_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001138 while (UNLIKELY((!kUseReadBarrier && !allow_new_monitors_) ||
1139 (kUseReadBarrier && !self->GetWeakRefAccessEnabled()))) {
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001140 monitor_add_condition_.WaitHoldingLocks(self);
1141 }
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001142 list_.push_front(m);
1143}
1144
Mathieu Chartier97509952015-07-13 14:35:43 -07001145void MonitorList::SweepMonitorList(IsMarkedVisitor* visitor) {
Andreas Gampe74240812014-04-17 10:35:09 -07001146 Thread* self = Thread::Current();
1147 MutexLock mu(self, monitor_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001148 for (auto it = list_.begin(); it != list_.end(); ) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001149 Monitor* m = *it;
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001150 // Disable the read barrier in GetObject() as this is called by GC.
1151 mirror::Object* obj = m->GetObject<kWithoutReadBarrier>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001152 // The object of a monitor can be null if we have deflated it.
Mathieu Chartier97509952015-07-13 14:35:43 -07001153 mirror::Object* new_obj = obj != nullptr ? visitor->IsMarked(obj) : nullptr;
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001154 if (new_obj == nullptr) {
1155 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001156 << obj;
Andreas Gampe74240812014-04-17 10:35:09 -07001157 MonitorPool::ReleaseMonitor(self, m);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001158 it = list_.erase(it);
1159 } else {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001160 m->SetObject(new_obj);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001161 ++it;
1162 }
1163 }
1164}
1165
Mathieu Chartier97509952015-07-13 14:35:43 -07001166class MonitorDeflateVisitor : public IsMarkedVisitor {
1167 public:
1168 MonitorDeflateVisitor() : self_(Thread::Current()), deflate_count_(0) {}
1169
1170 virtual mirror::Object* IsMarked(mirror::Object* object) OVERRIDE
Mathieu Chartier90443472015-07-16 20:32:27 -07001171 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001172 if (Monitor::Deflate(self_, object)) {
1173 DCHECK_NE(object->GetLockWord(true).GetState(), LockWord::kFatLocked);
1174 ++deflate_count_;
1175 // If we deflated, return null so that the monitor gets removed from the array.
1176 return nullptr;
1177 }
1178 return object; // Monitor was not deflated.
1179 }
1180
1181 Thread* const self_;
1182 size_t deflate_count_;
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001183};
1184
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001185size_t MonitorList::DeflateMonitors() {
Mathieu Chartier97509952015-07-13 14:35:43 -07001186 MonitorDeflateVisitor visitor;
1187 Locks::mutator_lock_->AssertExclusiveHeld(visitor.self_);
1188 SweepMonitorList(&visitor);
1189 return visitor.deflate_count_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001190}
1191
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001192MonitorInfo::MonitorInfo(mirror::Object* obj) : owner_(nullptr), entry_count_(0) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001193 DCHECK(obj != nullptr);
1194 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001195 switch (lock_word.GetState()) {
1196 case LockWord::kUnlocked:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001197 // Fall-through.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001198 case LockWord::kForwardingAddress:
1199 // Fall-through.
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001200 case LockWord::kHashCode:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001201 break;
1202 case LockWord::kThinLocked:
1203 owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
1204 entry_count_ = 1 + lock_word.ThinLockCount();
1205 // Thin locks have no waiters.
1206 break;
1207 case LockWord::kFatLocked: {
1208 Monitor* mon = lock_word.FatLockMonitor();
1209 owner_ = mon->owner_;
1210 entry_count_ = 1 + mon->lock_count_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001211 for (Thread* waiter = mon->wait_set_; waiter != nullptr; waiter = waiter->GetWaitNext()) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001212 waiters_.push_back(waiter);
1213 }
1214 break;
Elliott Hughesf327e072013-01-09 16:01:26 -08001215 }
1216 }
1217}
1218
Elliott Hughes5f791332011-09-15 17:45:30 -07001219} // namespace art