blob: 8448c59c60dc54ab0f8f4be78ac35a56dad9416f [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
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700218std::string Monitor::PrettyContentionInfo(Thread* owner,
219 ArtMethod* owners_method,
220 uint32_t owners_dex_pc,
221 size_t num_waiters) {
222 DCHECK(owner != nullptr);
223 const char* owners_filename;
224 int32_t owners_line_number;
225 std::string name;
226 owner->GetThreadName(name);
227 if (owners_method != nullptr) {
228 TranslateLocation(owners_method, owners_dex_pc, &owners_filename, &owners_line_number);
229 }
230 std::ostringstream oss;
231 oss << "monitor contention with owner " << name << " (" << owner->GetTid() << ")";
232 if (owners_method != nullptr) {
233 oss << " owner method=" << PrettyMethod(owners_method);
234 oss << " from " << owners_filename << ":" << owners_line_number;
235 }
236 oss << " waiters=" << num_waiters;
237 return oss.str();
238}
239
Elliott Hughes5f791332011-09-15 17:45:30 -0700240void Monitor::Lock(Thread* self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700241 MutexLock mu(self, monitor_lock_);
242 while (true) {
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700243 if (owner_ == nullptr) { // Unowned.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700244 owner_ = self;
245 CHECK_EQ(lock_count_, 0);
246 // When debugging, save the current monitor holder for future
247 // acquisition failures to use in sampled logging.
248 if (lock_profiling_threshold_ != 0) {
249 locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
250 }
251 return;
252 } else if (owner_ == self) { // Recursive.
253 lock_count_++;
254 return;
255 }
256 // Contended.
257 const bool log_contention = (lock_profiling_threshold_ != 0);
Xin Guanb894a192014-08-22 11:55:37 -0500258 uint64_t wait_start_ms = log_contention ? MilliTime() : 0;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700259 ArtMethod* owners_method = locking_method_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700260 uint32_t owners_dex_pc = locking_dex_pc_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700261 // Do this before releasing the lock so that we don't get deflated.
Mathieu Chartierb9001ab2014-10-03 13:28:46 -0700262 size_t num_waiters = num_waiters_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700263 ++num_waiters_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700264 monitor_lock_.Unlock(self); // Let go of locks in order.
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700265 self->SetMonitorEnterObject(GetObject());
Elliott Hughes5f791332011-09-15 17:45:30 -0700266 {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700267 ScopedThreadStateChange tsc(self, kBlocked); // Change to blocked and give up mutator_lock_.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700268 // Reacquire monitor_lock_ without mutator_lock_ for Wait.
269 MutexLock mu2(self, monitor_lock_);
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700270 Thread* original_owner = owner_;
271 if (original_owner != nullptr) { // Did the owner_ give the lock up?
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800272 if (ATRACE_ENABLED()) {
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700273 std::ostringstream oss;
274 oss << PrettyContentionInfo(original_owner, owners_method, owners_dex_pc, num_waiters);
275 // Add info for contending thread.
276 uint32_t pc;
277 ArtMethod* m = self->GetCurrentMethod(&pc);
278 const char* filename;
279 int32_t line_number;
280 TranslateLocation(m, pc, &filename, &line_number);
281 oss << " blocking from " << (filename != nullptr ? filename : "null")
282 << ":" << line_number;
283 ATRACE_BEGIN(oss.str().c_str());
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800284 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700285 monitor_contenders_.Wait(self); // Still contended so wait.
286 // Woken from contention.
287 if (log_contention) {
288 uint64_t wait_ms = MilliTime() - wait_start_ms;
289 uint32_t sample_percent;
290 if (wait_ms >= lock_profiling_threshold_) {
291 sample_percent = 100;
292 } else {
293 sample_percent = 100 * wait_ms / lock_profiling_threshold_;
294 }
295 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700296 if (wait_ms > kLongWaitMs && owners_method != nullptr) {
297 // TODO: We should maybe check that original_owner is still a live thread.
298 LOG(WARNING) << "Long "
299 << PrettyContentionInfo(original_owner,
300 owners_method,
301 owners_dex_pc,
302 num_waiters)
303 << " for " << PrettyDuration(MsToNs(wait_ms));
304 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700305 const char* owners_filename;
Brian Carlstromeaa46092015-10-07 21:29:28 -0700306 int32_t owners_line_number;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700307 TranslateLocation(owners_method, owners_dex_pc, &owners_filename, &owners_line_number);
308 LogContentionEvent(self, wait_ms, sample_percent, owners_filename, owners_line_number);
309 }
310 }
Mathieu Chartierf0dc8b52014-12-17 10:13:30 -0800311 ATRACE_END();
Elliott Hughesfc861622011-10-17 17:57:47 -0700312 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700313 }
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700314 self->SetMonitorEnterObject(nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700315 monitor_lock_.Lock(self); // Reacquire locks in order.
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700316 --num_waiters_;
Elliott Hughesfc861622011-10-17 17:57:47 -0700317 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700318}
319
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800320static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
321 __attribute__((format(printf, 1, 2)));
322
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700323static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
Mathieu Chartier90443472015-07-16 20:32:27 -0700324 SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800325 va_list args;
326 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800327 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000328 self->ThrowNewExceptionV("Ljava/lang/IllegalMonitorStateException;", fmt, args);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700329 if (!Runtime::Current()->IsStarted() || VLOG_IS_ON(monitor)) {
Brian Carlstrom64277f32012-03-26 23:53:34 -0700330 std::ostringstream ss;
Ian Rogers62d6c772013-02-27 08:32:07 -0800331 self->Dump(ss);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700332 LOG(Runtime::Current()->IsStarted() ? INFO : ERROR)
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000333 << self->GetException()->Dump() << "\n" << ss.str();
Brian Carlstrom64277f32012-03-26 23:53:34 -0700334 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800335 va_end(args);
336}
337
Elliott Hughesd4237412012-02-21 11:24:45 -0800338static std::string ThreadToString(Thread* thread) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700339 if (thread == nullptr) {
340 return "nullptr";
Elliott Hughesd4237412012-02-21 11:24:45 -0800341 }
342 std::ostringstream oss;
343 // TODO: alternatively, we could just return the thread's name.
344 oss << *thread;
345 return oss.str();
346}
347
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800348void Monitor::FailedUnlock(mirror::Object* o, Thread* expected_owner, Thread* found_owner,
Elliott Hughesffb465f2012-03-01 18:46:05 -0800349 Monitor* monitor) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700350 Thread* current_owner = nullptr;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800351 std::string current_owner_string;
352 std::string expected_owner_string;
353 std::string found_owner_string;
354 {
355 // TODO: isn't this too late to prevent threads from disappearing?
356 // Acquire thread list lock so threads won't disappear from under us.
Ian Rogers50b35e22012-10-04 10:09:15 -0700357 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Elliott Hughesffb465f2012-03-01 18:46:05 -0800358 // Re-read owner now that we hold lock.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700359 current_owner = (monitor != nullptr) ? monitor->GetOwner() : nullptr;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800360 // Get short descriptions of the threads involved.
361 current_owner_string = ThreadToString(current_owner);
362 expected_owner_string = ThreadToString(expected_owner);
363 found_owner_string = ThreadToString(found_owner);
364 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700365 if (current_owner == nullptr) {
366 if (found_owner == nullptr) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800367 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
368 " on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800369 PrettyTypeOf(o).c_str(),
370 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800371 } else {
372 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800373 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
374 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800375 found_owner_string.c_str(),
376 PrettyTypeOf(o).c_str(),
377 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800378 }
379 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700380 if (found_owner == nullptr) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800381 // Race: originally there was no owner, there is now
382 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
383 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800384 current_owner_string.c_str(),
385 PrettyTypeOf(o).c_str(),
386 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800387 } else {
388 if (found_owner != current_owner) {
389 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800390 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
391 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800392 found_owner_string.c_str(),
393 current_owner_string.c_str(),
394 PrettyTypeOf(o).c_str(),
395 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800396 } else {
397 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
398 " on thread '%s",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800399 current_owner_string.c_str(),
400 PrettyTypeOf(o).c_str(),
401 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800402 }
403 }
404 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700405}
406
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700407bool Monitor::Unlock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700408 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700409 MutexLock mu(self, monitor_lock_);
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800410 Thread* owner = owner_;
411 if (owner == self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700412 // We own the monitor, so nobody else can be in here.
413 if (lock_count_ == 0) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700414 owner_ = nullptr;
415 locking_method_ = nullptr;
Ian Rogers0399dde2012-06-06 17:09:28 -0700416 locking_dex_pc_ = 0;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700417 // Wake a contender.
418 monitor_contenders_.Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700419 } else {
420 --lock_count_;
421 }
422 } else {
423 // We don't own this, so we're not allowed to unlock it.
424 // The JNI spec says that we should throw IllegalMonitorStateException
425 // in this case.
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700426 FailedUnlock(GetObject(), self, owner, this);
Elliott Hughes5f791332011-09-15 17:45:30 -0700427 return false;
428 }
429 return true;
430}
431
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800432void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
433 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700434 DCHECK(self != nullptr);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800435 DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
Elliott Hughes5f791332011-09-15 17:45:30 -0700436
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700437 monitor_lock_.Lock(self);
438
Elliott Hughes5f791332011-09-15 17:45:30 -0700439 // Make sure that we hold the lock.
440 if (owner_ != self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700441 monitor_lock_.Unlock(self);
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700442 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700443 return;
444 }
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800445
Elliott Hughesdf42c482013-01-09 12:49:02 -0800446 // We need to turn a zero-length timed wait into a regular wait because
447 // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
448 if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
449 why = kWaiting;
450 }
451
Elliott Hughes5f791332011-09-15 17:45:30 -0700452 // Enforce the timeout range.
453 if (ms < 0 || ns < 0 || ns > 999999) {
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700454 monitor_lock_.Unlock(self);
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000455 self->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
Ian Rogersef7d42f2014-01-06 12:55:46 -0800456 "timeout arguments out of range: ms=%" PRId64 " ns=%d", ms, ns);
Elliott Hughes5f791332011-09-15 17:45:30 -0700457 return;
458 }
459
Elliott Hughes5f791332011-09-15 17:45:30 -0700460 /*
461 * Add ourselves to the set of threads waiting on this monitor, and
462 * release our hold. We need to let it go even if we're a few levels
463 * deep in a recursive lock, and we need to restore that later.
464 *
465 * We append to the wait set ahead of clearing the count and owner
466 * fields so the subroutine can check that the calling thread owns
467 * the monitor. Aside from that, the order of member updates is
468 * not order sensitive as we hold the pthread mutex.
469 */
470 AppendToWaitSet(self);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700471 ++num_waiters_;
Ian Rogers0399dde2012-06-06 17:09:28 -0700472 int prev_lock_count = lock_count_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700473 lock_count_ = 0;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700474 owner_ = nullptr;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700475 ArtMethod* saved_method = locking_method_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700476 locking_method_ = nullptr;
Ian Rogers0399dde2012-06-06 17:09:28 -0700477 uintptr_t saved_dex_pc = locking_dex_pc_;
478 locking_dex_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700479
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800480 bool was_interrupted = false;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700481 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700482 // Update thread state. If the GC wakes up, it'll ignore us, knowing
483 // that we won't touch any references in this state, and we'll check
484 // our suspend mode before we transition out.
485 ScopedThreadSuspension sts(self, why);
486
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700487 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700488 MutexLock mu(self, *self->GetWaitMutex());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700489
490 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700491 // non-null a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700492 // up.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700493 DCHECK(self->GetWaitMonitor() == nullptr);
494 self->SetWaitMonitor(this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700495
496 // Release the monitor lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700497 monitor_contenders_.Signal(self);
498 monitor_lock_.Unlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700499
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800500 // Handle the case where the thread was interrupted before we called wait().
Ian Rogersdd7624d2014-03-14 17:43:00 -0700501 if (self->IsInterruptedLocked()) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800502 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700503 } else {
504 // Wait for a notification or a timeout to occur.
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800505 if (why == kWaiting) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700506 self->GetWaitConditionVariable()->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700507 } else {
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800508 DCHECK(why == kTimedWaiting || why == kSleeping) << why;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700509 self->GetWaitConditionVariable()->TimedWait(self, ms, ns);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700510 }
Hans Boehm328c5dc2015-11-11 16:13:57 -0800511 was_interrupted = self->IsInterruptedLocked();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700512 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700513 }
514
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800515 {
516 // We reset the thread's wait_monitor_ field after transitioning back to runnable so
517 // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
518 // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
519 // are waiting on "null".)
Ian Rogersdd7624d2014-03-14 17:43:00 -0700520 MutexLock mu(self, *self->GetWaitMutex());
521 DCHECK(self->GetWaitMonitor() != nullptr);
522 self->SetWaitMonitor(nullptr);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800523 }
524
Mathieu Chartierdaed5d82016-03-10 10:49:35 -0800525 // Allocate the interrupted exception not holding the monitor lock since it may cause a GC.
526 // If the GC requires acquiring the monitor for enqueuing cleared references, this would
527 // cause a deadlock if the monitor is held.
528 if (was_interrupted && interruptShouldThrow) {
529 /*
530 * We were interrupted while waiting, or somebody interrupted an
531 * un-interruptible thread earlier and we're bailing out immediately.
532 *
533 * The doc sayeth: "The interrupted status of the current thread is
534 * cleared when this exception is thrown."
535 */
536 {
537 MutexLock mu(self, *self->GetWaitMutex());
538 self->SetInterruptedLocked(false);
539 }
540 self->ThrowNewException("Ljava/lang/InterruptedException;", nullptr);
541 }
542
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700543 // Re-acquire the monitor and lock.
Elliott Hughes5f791332011-09-15 17:45:30 -0700544 Lock(self);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700545 monitor_lock_.Lock(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700546 self->GetWaitMutex()->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700547
Elliott Hughes5f791332011-09-15 17:45:30 -0700548 /*
549 * We remove our thread from wait set after restoring the count
550 * and owner fields so the subroutine can check that the calling
551 * thread owns the monitor. Aside from that, the order of member
552 * updates is not order sensitive as we hold the pthread mutex.
553 */
554 owner_ = self;
Ian Rogers0399dde2012-06-06 17:09:28 -0700555 lock_count_ = prev_lock_count;
556 locking_method_ = saved_method;
557 locking_dex_pc_ = saved_dex_pc;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700558 --num_waiters_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700559 RemoveFromWaitSet(self);
560
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700561 monitor_lock_.Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700562}
563
564void Monitor::Notify(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700565 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700566 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700567 // Make sure that we hold the lock.
568 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800569 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700570 return;
571 }
572 // Signal the first waiting thread in the wait set.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700573 while (wait_set_ != nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700574 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700575 wait_set_ = thread->GetWaitNext();
576 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700577
578 // Check to see if the thread is still waiting.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800579 MutexLock wait_mu(self, *thread->GetWaitMutex());
Ian Rogersdd7624d2014-03-14 17:43:00 -0700580 if (thread->GetWaitMonitor() != nullptr) {
581 thread->GetWaitConditionVariable()->Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700582 return;
583 }
584 }
585}
586
587void Monitor::NotifyAll(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700588 DCHECK(self != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700589 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700590 // Make sure that we hold the lock.
591 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800592 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700593 return;
594 }
595 // Signal all threads in the wait set.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700596 while (wait_set_ != nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700597 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700598 wait_set_ = thread->GetWaitNext();
599 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700600 thread->Notify();
601 }
602}
603
Mathieu Chartier590fee92013-09-13 13:46:47 -0700604bool Monitor::Deflate(Thread* self, mirror::Object* obj) {
605 DCHECK(obj != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700606 // Don't need volatile since we only deflate with mutators suspended.
607 LockWord lw(obj->GetLockWord(false));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700608 // If the lock isn't an inflated monitor, then we don't need to deflate anything.
609 if (lw.GetState() == LockWord::kFatLocked) {
610 Monitor* monitor = lw.FatLockMonitor();
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700611 DCHECK(monitor != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700612 MutexLock mu(self, monitor->monitor_lock_);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700613 // Can't deflate if we have anybody waiting on the CV.
614 if (monitor->num_waiters_ > 0) {
615 return false;
616 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700617 Thread* owner = monitor->owner_;
618 if (owner != nullptr) {
619 // Can't deflate if we are locked and have a hash code.
620 if (monitor->HasHashCode()) {
621 return false;
622 }
623 // Can't deflate if our lock count is too high.
624 if (monitor->lock_count_ > LockWord::kThinLockMaxCount) {
625 return false;
626 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700627 // Deflate to a thin lock.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800628 LockWord new_lw = LockWord::FromThinLockId(owner->GetThreadId(), monitor->lock_count_,
629 lw.ReadBarrierState());
630 // Assume no concurrent read barrier state changes as mutators are suspended.
631 obj->SetLockWord(new_lw, false);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700632 VLOG(monitor) << "Deflated " << obj << " to thin lock " << owner->GetTid() << " / "
633 << monitor->lock_count_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700634 } else if (monitor->HasHashCode()) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800635 LockWord new_lw = LockWord::FromHashCode(monitor->GetHashCode(), lw.ReadBarrierState());
636 // Assume no concurrent read barrier state changes as mutators are suspended.
637 obj->SetLockWord(new_lw, false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700638 VLOG(monitor) << "Deflated " << obj << " to hash monitor " << monitor->GetHashCode();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700639 } else {
640 // No lock and no hash, just put an empty lock word inside the object.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800641 LockWord new_lw = LockWord::FromDefault(lw.ReadBarrierState());
642 // Assume no concurrent read barrier state changes as mutators are suspended.
643 obj->SetLockWord(new_lw, false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700644 VLOG(monitor) << "Deflated" << obj << " to empty lock word";
Mathieu Chartier590fee92013-09-13 13:46:47 -0700645 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700646 // 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 -0700647 // next GC.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700648 monitor->obj_ = GcRoot<mirror::Object>(nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700649 }
650 return true;
651}
652
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700653void Monitor::Inflate(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code) {
Andreas Gampe74240812014-04-17 10:35:09 -0700654 DCHECK(self != nullptr);
655 DCHECK(obj != nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700656 // Allocate and acquire a new monitor.
Andreas Gampe74240812014-04-17 10:35:09 -0700657 Monitor* m = MonitorPool::CreateMonitor(self, owner, obj, hash_code);
658 DCHECK(m != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700659 if (m->Install(self)) {
Haifeng Li86ab7912014-05-16 10:47:59 +0800660 if (owner != nullptr) {
661 VLOG(monitor) << "monitor: thread" << owner->GetThreadId()
Andreas Gampe74240812014-04-17 10:35:09 -0700662 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800663 } else {
664 VLOG(monitor) << "monitor: Inflate with hashcode " << hash_code
Andreas Gampe74240812014-04-17 10:35:09 -0700665 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800666 }
Andreas Gampe74240812014-04-17 10:35:09 -0700667 Runtime::Current()->GetMonitorList()->Add(m);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700668 CHECK_EQ(obj->GetLockWord(true).GetState(), LockWord::kFatLocked);
Andreas Gampe74240812014-04-17 10:35:09 -0700669 } else {
670 MonitorPool::ReleaseMonitor(self, m);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700671 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700672}
673
Mathieu Chartier0cd81352014-05-22 16:48:55 -0700674void Monitor::InflateThinLocked(Thread* self, Handle<mirror::Object> obj, LockWord lock_word,
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700675 uint32_t hash_code) {
676 DCHECK_EQ(lock_word.GetState(), LockWord::kThinLocked);
677 uint32_t owner_thread_id = lock_word.ThinLockOwner();
678 if (owner_thread_id == self->GetThreadId()) {
679 // We own the monitor, we can easily inflate it.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700680 Inflate(self, self, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700681 } else {
682 ThreadList* thread_list = Runtime::Current()->GetThreadList();
683 // Suspend the owner, inflate. First change to blocked and give up mutator_lock_.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700684 self->SetMonitorEnterObject(obj.Get());
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700685 bool timed_out;
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700686 Thread* owner;
687 {
688 ScopedThreadSuspension sts(self, kBlocked);
689 owner = thread_list->SuspendThreadByThreadId(owner_thread_id, false, &timed_out);
690 }
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700691 if (owner != nullptr) {
692 // We succeeded in suspending the thread, check the lock's status didn't change.
693 lock_word = obj->GetLockWord(true);
694 if (lock_word.GetState() == LockWord::kThinLocked &&
695 lock_word.ThinLockOwner() == owner_thread_id) {
696 // Go ahead and inflate the lock.
697 Inflate(self, owner, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700698 }
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700699 thread_list->Resume(owner, false);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700700 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700701 self->SetMonitorEnterObject(nullptr);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700702 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700703}
704
Ian Rogers719d1a32014-03-06 12:13:39 -0800705// Fool annotalysis into thinking that the lock on obj is acquired.
706static mirror::Object* FakeLock(mirror::Object* obj)
707 EXCLUSIVE_LOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
708 return obj;
709}
710
711// Fool annotalysis into thinking that the lock on obj is release.
712static mirror::Object* FakeUnlock(mirror::Object* obj)
713 UNLOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
714 return obj;
715}
716
Mathieu Chartiere7e8a5f2014-02-14 16:59:41 -0800717mirror::Object* Monitor::MonitorEnter(Thread* self, mirror::Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700718 DCHECK(self != nullptr);
719 DCHECK(obj != nullptr);
Mathieu Chartier2d096c92015-10-12 16:18:20 -0700720 self->AssertThreadSuspensionIsAllowable();
Ian Rogers719d1a32014-03-06 12:13:39 -0800721 obj = FakeLock(obj);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700722 uint32_t thread_id = self->GetThreadId();
723 size_t contention_count = 0;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700724 StackHandleScope<1> hs(self);
725 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700726 while (true) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700727 LockWord lock_word = h_obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700728 switch (lock_word.GetState()) {
729 case LockWord::kUnlocked: {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800730 LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0, lock_word.ReadBarrierState()));
Ian Rogers228602f2014-07-10 02:07:54 -0700731 if (h_obj->CasLockWordWeakSequentiallyConsistent(lock_word, thin_locked)) {
Hans Boehm30359612014-05-21 17:46:23 -0700732 // CasLockWord enforces more than the acquire ordering we need here.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700733 return h_obj.Get(); // Success!
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700734 }
735 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -0700736 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700737 case LockWord::kThinLocked: {
738 uint32_t owner_thread_id = lock_word.ThinLockOwner();
739 if (owner_thread_id == thread_id) {
740 // We own the lock, increase the recursion count.
741 uint32_t new_count = lock_word.ThinLockCount() + 1;
742 if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800743 LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count,
744 lock_word.ReadBarrierState()));
745 if (!kUseReadBarrier) {
746 h_obj->SetLockWord(thin_locked, true);
747 return h_obj.Get(); // Success!
748 } else {
749 // Use CAS to preserve the read barrier state.
750 if (h_obj->CasLockWordWeakSequentiallyConsistent(lock_word, thin_locked)) {
751 return h_obj.Get(); // Success!
752 }
753 }
754 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -0700755 } else {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700756 // We'd overflow the recursion count, so inflate the monitor.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700757 InflateThinLocked(self, h_obj, lock_word, 0);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700758 }
759 } else {
760 // Contention.
761 contention_count++;
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700762 Runtime* runtime = Runtime::Current();
763 if (contention_count <= runtime->GetMaxSpinsBeforeThinkLockInflation()) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700764 // TODO: Consider switching the thread state to kBlocked when we are yielding.
Mathieu Chartier251755c2014-07-15 18:10:25 -0700765 // Use sched_yield instead of NanoSleep since NanoSleep can wait much longer than the
766 // parameter you pass in. This can cause thread suspension to take excessively long
Mathieu Chartierb363f662014-07-16 13:28:58 -0700767 // and make long pauses. See b/16307460.
Mathieu Chartier251755c2014-07-15 18:10:25 -0700768 sched_yield();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700769 } else {
770 contention_count = 0;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700771 InflateThinLocked(self, h_obj, lock_word, 0);
Elliott Hughes5f791332011-09-15 17:45:30 -0700772 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700773 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700774 continue; // Start from the beginning.
Elliott Hughes5f791332011-09-15 17:45:30 -0700775 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700776 case LockWord::kFatLocked: {
777 Monitor* mon = lock_word.FatLockMonitor();
778 mon->Lock(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700779 return h_obj.Get(); // Success!
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700780 }
Ian Rogers719d1a32014-03-06 12:13:39 -0800781 case LockWord::kHashCode:
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700782 // Inflate with the existing hashcode.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700783 Inflate(self, nullptr, h_obj.Get(), lock_word.GetHashCode());
Ian Rogers719d1a32014-03-06 12:13:39 -0800784 continue; // Start from the beginning.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700785 default: {
786 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700787 return h_obj.Get();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700788 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700789 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700790 }
791}
792
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800793bool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700794 DCHECK(self != nullptr);
795 DCHECK(obj != nullptr);
Mathieu Chartier2d096c92015-10-12 16:18:20 -0700796 self->AssertThreadSuspensionIsAllowable();
Ian Rogers719d1a32014-03-06 12:13:39 -0800797 obj = FakeUnlock(obj);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700798 StackHandleScope<1> hs(self);
799 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800800 while (true) {
801 LockWord lock_word = obj->GetLockWord(true);
802 switch (lock_word.GetState()) {
803 case LockWord::kHashCode:
804 // Fall-through.
805 case LockWord::kUnlocked:
806 FailedUnlock(h_obj.Get(), self, nullptr, nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700807 return false; // Failure.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800808 case LockWord::kThinLocked: {
809 uint32_t thread_id = self->GetThreadId();
810 uint32_t owner_thread_id = lock_word.ThinLockOwner();
811 if (owner_thread_id != thread_id) {
812 // TODO: there's a race here with the owner dying while we unlock.
813 Thread* owner =
814 Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
815 FailedUnlock(h_obj.Get(), self, owner, nullptr);
816 return false; // Failure.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700817 } else {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800818 // We own the lock, decrease the recursion count.
819 LockWord new_lw = LockWord::Default();
820 if (lock_word.ThinLockCount() != 0) {
821 uint32_t new_count = lock_word.ThinLockCount() - 1;
822 new_lw = LockWord::FromThinLockId(thread_id, new_count, lock_word.ReadBarrierState());
823 } else {
824 new_lw = LockWord::FromDefault(lock_word.ReadBarrierState());
825 }
826 if (!kUseReadBarrier) {
827 DCHECK_EQ(new_lw.ReadBarrierState(), 0U);
828 h_obj->SetLockWord(new_lw, true);
829 // Success!
830 return true;
831 } else {
832 // Use CAS to preserve the read barrier state.
833 if (h_obj->CasLockWordWeakSequentiallyConsistent(lock_word, new_lw)) {
834 // Success!
835 return true;
836 }
837 }
838 continue; // Go again.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700839 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700840 }
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800841 case LockWord::kFatLocked: {
842 Monitor* mon = lock_word.FatLockMonitor();
843 return mon->Unlock(self);
844 }
845 default: {
846 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
847 return false;
848 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700849 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700850 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700851}
852
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800853void Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800854 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700855 DCHECK(self != nullptr);
856 DCHECK(obj != nullptr);
857 LockWord lock_word = obj->GetLockWord(true);
Ian Rogers43c69cc2014-08-15 11:09:28 -0700858 while (lock_word.GetState() != LockWord::kFatLocked) {
859 switch (lock_word.GetState()) {
860 case LockWord::kHashCode:
861 // Fall-through.
862 case LockWord::kUnlocked:
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700863 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
864 return; // Failure.
Ian Rogers43c69cc2014-08-15 11:09:28 -0700865 case LockWord::kThinLocked: {
866 uint32_t thread_id = self->GetThreadId();
867 uint32_t owner_thread_id = lock_word.ThinLockOwner();
868 if (owner_thread_id != thread_id) {
869 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
870 return; // Failure.
871 } else {
872 // We own the lock, inflate to enqueue ourself on the Monitor. May fail spuriously so
873 // re-load.
874 Inflate(self, self, obj, 0);
875 lock_word = obj->GetLockWord(true);
876 }
877 break;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700878 }
Ian Rogers43c69cc2014-08-15 11:09:28 -0700879 case LockWord::kFatLocked: // Unreachable given the loop condition above. Fall-through.
880 default: {
881 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
882 return;
883 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700884 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700885 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700886 Monitor* mon = lock_word.FatLockMonitor();
887 mon->Wait(self, ms, ns, interruptShouldThrow, why);
Elliott Hughes5f791332011-09-15 17:45:30 -0700888}
889
Ian Rogers13c479e2013-10-11 07:59:01 -0700890void Monitor::DoNotify(Thread* self, mirror::Object* obj, bool notify_all) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700891 DCHECK(self != nullptr);
892 DCHECK(obj != nullptr);
893 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700894 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700895 case LockWord::kHashCode:
896 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700897 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800898 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700899 return; // Failure.
900 case LockWord::kThinLocked: {
901 uint32_t thread_id = self->GetThreadId();
902 uint32_t owner_thread_id = lock_word.ThinLockOwner();
903 if (owner_thread_id != thread_id) {
904 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
905 return; // Failure.
906 } else {
907 // We own the lock but there's no Monitor and therefore no waiters.
908 return; // Success.
909 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700910 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700911 case LockWord::kFatLocked: {
912 Monitor* mon = lock_word.FatLockMonitor();
913 if (notify_all) {
914 mon->NotifyAll(self);
915 } else {
916 mon->Notify(self);
917 }
918 return; // Success.
919 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700920 default: {
921 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
922 return;
923 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700924 }
925}
926
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700927uint32_t Monitor::GetLockOwnerThreadId(mirror::Object* obj) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700928 DCHECK(obj != nullptr);
929 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700930 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700931 case LockWord::kHashCode:
932 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700933 case LockWord::kUnlocked:
934 return ThreadList::kInvalidThreadId;
935 case LockWord::kThinLocked:
936 return lock_word.ThinLockOwner();
937 case LockWord::kFatLocked: {
938 Monitor* mon = lock_word.FatLockMonitor();
939 return mon->GetOwnerThreadId();
Elliott Hughes5f791332011-09-15 17:45:30 -0700940 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700941 default: {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700942 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -0700943 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700944 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700945 }
946}
947
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700948void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
Ian Rogersd803bc72014-04-01 15:33:03 -0700949 // Determine the wait message and object we're waiting or blocked upon.
950 mirror::Object* pretty_object = nullptr;
951 const char* wait_message = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700952 uint32_t lock_owner = ThreadList::kInvalidThreadId;
Ian Rogersd803bc72014-04-01 15:33:03 -0700953 ThreadState state = thread->GetState();
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800954 if (state == kWaiting || state == kTimedWaiting || state == kSleeping) {
Ian Rogersd803bc72014-04-01 15:33:03 -0700955 wait_message = (state == kSleeping) ? " - sleeping on " : " - waiting on ";
956 Thread* self = Thread::Current();
957 MutexLock mu(self, *thread->GetWaitMutex());
958 Monitor* monitor = thread->GetWaitMonitor();
959 if (monitor != nullptr) {
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700960 pretty_object = monitor->GetObject();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700961 }
Elliott Hughes34e06962012-04-09 13:55:55 -0700962 } else if (state == kBlocked) {
Ian Rogersd803bc72014-04-01 15:33:03 -0700963 wait_message = " - waiting to lock ";
964 pretty_object = thread->GetMonitorEnterObject();
965 if (pretty_object != nullptr) {
966 lock_owner = pretty_object->GetLockOwnerThreadId();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700967 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700968 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700969
Ian Rogersd803bc72014-04-01 15:33:03 -0700970 if (wait_message != nullptr) {
971 if (pretty_object == nullptr) {
972 os << wait_message << "an unknown object";
973 } else {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700974 if ((pretty_object->GetLockWord(true).GetState() == LockWord::kThinLocked) &&
Ian Rogersd803bc72014-04-01 15:33:03 -0700975 Locks::mutator_lock_->IsExclusiveHeld(Thread::Current())) {
976 // Getting the identity hashcode here would result in lock inflation and suspension of the
977 // current thread, which isn't safe if this is the only runnable thread.
978 os << wait_message << StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)",
979 reinterpret_cast<intptr_t>(pretty_object),
980 PrettyTypeOf(pretty_object).c_str());
981 } else {
982 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
Mathieu Chartier49361592015-01-22 16:36:10 -0800983 // Call PrettyTypeOf before IdentityHashCode since IdentityHashCode can cause thread
984 // suspension and move pretty_object.
985 const std::string pretty_type(PrettyTypeOf(pretty_object));
Ian Rogersd803bc72014-04-01 15:33:03 -0700986 os << wait_message << StringPrintf("<0x%08x> (a %s)", pretty_object->IdentityHashCode(),
Mathieu Chartier49361592015-01-22 16:36:10 -0800987 pretty_type.c_str());
Ian Rogersd803bc72014-04-01 15:33:03 -0700988 }
989 }
990 // - waiting to lock <0x613f83d8> (a java.lang.Object) held by thread 5
991 if (lock_owner != ThreadList::kInvalidThreadId) {
992 os << " held by thread " << lock_owner;
993 }
994 os << "\n";
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700995 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700996}
997
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800998mirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800999 // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
1000 // definition of contended that includes a monitor a thread is trying to enter...
Ian Rogersdd7624d2014-03-14 17:43:00 -07001001 mirror::Object* result = thread->GetMonitorEnterObject();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001002 if (result == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001003 // ...but also a monitor that the thread is waiting on.
Ian Rogersdd7624d2014-03-14 17:43:00 -07001004 MutexLock mu(Thread::Current(), *thread->GetWaitMutex());
1005 Monitor* monitor = thread->GetWaitMonitor();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001006 if (monitor != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001007 result = monitor->GetObject();
Elliott Hughesf9501702013-01-11 11:22:27 -08001008 }
1009 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001010 return result;
Elliott Hughesf9501702013-01-11 11:22:27 -08001011}
1012
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001013void Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
Andreas Gampe760172c2014-08-16 13:41:10 -07001014 void* callback_context, bool abort_on_failure) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001015 ArtMethod* m = stack_visitor->GetMethod();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001016 CHECK(m != nullptr);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001017
1018 // Native methods are an easy special case.
1019 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
1020 if (m->IsNative()) {
1021 if (m->IsSynchronized()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001022 mirror::Object* jni_this =
1023 stack_visitor->GetCurrentHandleScope(sizeof(void*))->GetReference(0);
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001024 callback(jni_this, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001025 }
1026 return;
1027 }
1028
jeffhao61f916c2012-10-25 17:48:51 -07001029 // Proxy methods should not be synchronized.
1030 if (m->IsProxyMethod()) {
1031 CHECK(!m->IsSynchronized());
1032 return;
1033 }
1034
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001035 // Is there any reason to believe there's any synchronization in this method?
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001036 const DexFile::CodeItem* code_item = m->GetCodeItem();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001037 CHECK(code_item != nullptr) << PrettyMethod(m);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001038 if (code_item->tries_size_ == 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001039 return; // No "tries" implies no synchronization, so no held locks to report.
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001040 }
1041
Andreas Gampe760172c2014-08-16 13:41:10 -07001042 // Get the dex pc. If abort_on_failure is false, GetDexPc will not abort in the case it cannot
1043 // find the dex pc, and instead return kDexNoIndex. Then bail out, as it indicates we have an
1044 // inconsistent stack anyways.
1045 uint32_t dex_pc = stack_visitor->GetDexPc(abort_on_failure);
1046 if (!abort_on_failure && dex_pc == DexFile::kDexNoIndex) {
1047 LOG(ERROR) << "Could not find dex_pc for " << PrettyMethod(m);
1048 return;
1049 }
1050
Elliott Hughes80537bb2013-01-04 16:37:26 -08001051 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
1052 // the locks held in this stack frame.
1053 std::vector<uint32_t> monitor_enter_dex_pcs;
Andreas Gampe760172c2014-08-16 13:41:10 -07001054 verifier::MethodVerifier::FindLocksAtDexPc(m, dex_pc, &monitor_enter_dex_pcs);
Mathieu Chartiere6a8eec2015-01-06 14:17:57 -08001055 for (uint32_t monitor_dex_pc : monitor_enter_dex_pcs) {
Elliott Hughes80537bb2013-01-04 16:37:26 -08001056 // The verifier works in terms of the dex pcs of the monitor-enter instructions.
1057 // We want the registers used by those instructions (so we can read the values out of them).
Sebastien Hertz0f7c9332015-11-05 15:57:30 +01001058 const Instruction* monitor_enter_instruction =
1059 Instruction::At(&code_item->insns_[monitor_dex_pc]);
Elliott Hughes80537bb2013-01-04 16:37:26 -08001060
1061 // Quick sanity check.
Sebastien Hertz0f7c9332015-11-05 15:57:30 +01001062 CHECK_EQ(monitor_enter_instruction->Opcode(), Instruction::MONITOR_ENTER)
1063 << "expected monitor-enter @" << monitor_dex_pc << "; was "
1064 << reinterpret_cast<const void*>(monitor_enter_instruction);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001065
Sebastien Hertz0f7c9332015-11-05 15:57:30 +01001066 uint16_t monitor_register = monitor_enter_instruction->VRegA();
Nicolas Geoffray15b9d522015-03-12 15:05:13 +00001067 uint32_t value;
1068 bool success = stack_visitor->GetVReg(m, monitor_register, kReferenceVReg, &value);
1069 CHECK(success) << "Failed to read v" << monitor_register << " of kind "
1070 << kReferenceVReg << " in method " << PrettyMethod(m);
1071 mirror::Object* o = reinterpret_cast<mirror::Object*>(value);
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001072 callback(o, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001073 }
1074}
1075
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001076bool Monitor::IsValidLockWord(LockWord lock_word) {
1077 switch (lock_word.GetState()) {
1078 case LockWord::kUnlocked:
1079 // Nothing to check.
1080 return true;
1081 case LockWord::kThinLocked:
1082 // Basic sanity check of owner.
1083 return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
1084 case LockWord::kFatLocked: {
1085 // Check the monitor appears in the monitor list.
1086 Monitor* mon = lock_word.FatLockMonitor();
1087 MonitorList* list = Runtime::Current()->GetMonitorList();
1088 MutexLock mu(Thread::Current(), list->monitor_list_lock_);
1089 for (Monitor* list_mon : list->list_) {
1090 if (mon == list_mon) {
1091 return true; // Found our monitor.
1092 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001093 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001094 return false; // Fail - unowned monitor in an object.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001095 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001096 case LockWord::kHashCode:
1097 return true;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001098 default:
1099 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001100 UNREACHABLE();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001101 }
1102}
1103
Mathieu Chartier90443472015-07-16 20:32:27 -07001104bool Monitor::IsLocked() SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001105 MutexLock mu(Thread::Current(), monitor_lock_);
1106 return owner_ != nullptr;
1107}
1108
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -07001109void Monitor::TranslateLocation(ArtMethod* method,
1110 uint32_t dex_pc,
1111 const char** source_file,
1112 int32_t* line_number) {
jeffhao33dc7712011-11-09 17:54:24 -08001113 // If method is null, location is unknown
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001114 if (method == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001115 *source_file = "";
1116 *line_number = 0;
jeffhao33dc7712011-11-09 17:54:24 -08001117 return;
1118 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001119 *source_file = method->GetDeclaringClassSourceFile();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001120 if (*source_file == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001121 *source_file = "";
Elliott Hughes12c51e32012-01-17 20:25:05 -08001122 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001123 *line_number = method->GetLineNumFromDexPC(dex_pc);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001124}
1125
1126uint32_t Monitor::GetOwnerThreadId() {
1127 MutexLock mu(Thread::Current(), monitor_lock_);
1128 Thread* owner = owner_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001129 if (owner != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001130 return owner->GetThreadId();
1131 } else {
1132 return ThreadList::kInvalidThreadId;
1133 }
jeffhao33dc7712011-11-09 17:54:24 -08001134}
1135
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001136MonitorList::MonitorList()
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001137 : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock", kMonitorListLock),
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001138 monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001139}
1140
1141MonitorList::~MonitorList() {
Andreas Gampe74240812014-04-17 10:35:09 -07001142 Thread* self = Thread::Current();
1143 MutexLock mu(self, monitor_list_lock_);
1144 // Release all monitors to the pool.
1145 // TODO: Is it an invariant that *all* open monitors are in the list? Then we could
1146 // clear faster in the pool.
1147 MonitorPool::ReleaseMonitors(self, &list_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001148}
1149
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001150void MonitorList::DisallowNewMonitors() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001151 CHECK(!kUseReadBarrier);
Ian Rogers50b35e22012-10-04 10:09:15 -07001152 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001153 allow_new_monitors_ = false;
1154}
1155
1156void MonitorList::AllowNewMonitors() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001157 CHECK(!kUseReadBarrier);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001158 Thread* self = Thread::Current();
1159 MutexLock mu(self, monitor_list_lock_);
1160 allow_new_monitors_ = true;
1161 monitor_add_condition_.Broadcast(self);
1162}
1163
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001164void MonitorList::BroadcastForNewMonitors() {
1165 CHECK(kUseReadBarrier);
1166 Thread* self = Thread::Current();
1167 MutexLock mu(self, monitor_list_lock_);
1168 monitor_add_condition_.Broadcast(self);
1169}
1170
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001171void MonitorList::Add(Monitor* m) {
1172 Thread* self = Thread::Current();
1173 MutexLock mu(self, monitor_list_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001174 while (UNLIKELY((!kUseReadBarrier && !allow_new_monitors_) ||
1175 (kUseReadBarrier && !self->GetWeakRefAccessEnabled()))) {
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001176 monitor_add_condition_.WaitHoldingLocks(self);
1177 }
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001178 list_.push_front(m);
1179}
1180
Mathieu Chartier97509952015-07-13 14:35:43 -07001181void MonitorList::SweepMonitorList(IsMarkedVisitor* visitor) {
Andreas Gampe74240812014-04-17 10:35:09 -07001182 Thread* self = Thread::Current();
1183 MutexLock mu(self, monitor_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001184 for (auto it = list_.begin(); it != list_.end(); ) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001185 Monitor* m = *it;
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001186 // Disable the read barrier in GetObject() as this is called by GC.
1187 mirror::Object* obj = m->GetObject<kWithoutReadBarrier>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001188 // The object of a monitor can be null if we have deflated it.
Mathieu Chartier97509952015-07-13 14:35:43 -07001189 mirror::Object* new_obj = obj != nullptr ? visitor->IsMarked(obj) : nullptr;
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001190 if (new_obj == nullptr) {
1191 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001192 << obj;
Andreas Gampe74240812014-04-17 10:35:09 -07001193 MonitorPool::ReleaseMonitor(self, m);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001194 it = list_.erase(it);
1195 } else {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001196 m->SetObject(new_obj);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001197 ++it;
1198 }
1199 }
1200}
1201
Mathieu Chartier97509952015-07-13 14:35:43 -07001202class MonitorDeflateVisitor : public IsMarkedVisitor {
1203 public:
1204 MonitorDeflateVisitor() : self_(Thread::Current()), deflate_count_(0) {}
1205
1206 virtual mirror::Object* IsMarked(mirror::Object* object) OVERRIDE
Mathieu Chartier90443472015-07-16 20:32:27 -07001207 SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001208 if (Monitor::Deflate(self_, object)) {
1209 DCHECK_NE(object->GetLockWord(true).GetState(), LockWord::kFatLocked);
1210 ++deflate_count_;
1211 // If we deflated, return null so that the monitor gets removed from the array.
1212 return nullptr;
1213 }
1214 return object; // Monitor was not deflated.
1215 }
1216
1217 Thread* const self_;
1218 size_t deflate_count_;
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001219};
1220
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001221size_t MonitorList::DeflateMonitors() {
Mathieu Chartier97509952015-07-13 14:35:43 -07001222 MonitorDeflateVisitor visitor;
1223 Locks::mutator_lock_->AssertExclusiveHeld(visitor.self_);
1224 SweepMonitorList(&visitor);
1225 return visitor.deflate_count_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001226}
1227
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001228MonitorInfo::MonitorInfo(mirror::Object* obj) : owner_(nullptr), entry_count_(0) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001229 DCHECK(obj != nullptr);
1230 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001231 switch (lock_word.GetState()) {
1232 case LockWord::kUnlocked:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001233 // Fall-through.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001234 case LockWord::kForwardingAddress:
1235 // Fall-through.
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001236 case LockWord::kHashCode:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001237 break;
1238 case LockWord::kThinLocked:
1239 owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
1240 entry_count_ = 1 + lock_word.ThinLockCount();
1241 // Thin locks have no waiters.
1242 break;
1243 case LockWord::kFatLocked: {
1244 Monitor* mon = lock_word.FatLockMonitor();
1245 owner_ = mon->owner_;
1246 entry_count_ = 1 + mon->lock_count_;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001247 for (Thread* waiter = mon->wait_set_; waiter != nullptr; waiter = waiter->GetWaitNext()) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001248 waiters_.push_back(waiter);
1249 }
1250 break;
Elliott Hughesf327e072013-01-09 16:01:26 -08001251 }
1252 }
1253}
1254
Elliott Hughes5f791332011-09-15 17:45:30 -07001255} // namespace art