blob: 5020ced3964b808573dce553405e0d2204589907 [file] [log] [blame]
Elliott Hughes5f791332011-09-15 17:45:30 -07001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Elliott Hughes54e7df12011-09-16 11:47:04 -070017#include "monitor.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070018
Elliott Hughes08fc03a2012-06-26 17:34:00 -070019#include <vector>
20
Elliott Hughes76b61672012-12-12 17:47:30 -080021#include "base/mutex.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080022#include "base/stl_util.h"
jeffhao33dc7712011-11-09 17:54:24 -080023#include "class_linker.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070024#include "dex_file-inl.h"
Elliott Hughes08fc03a2012-06-26 17:34:00 -070025#include "dex_instruction.h"
Ian Rogersd9c4fc92013-10-01 19:45:43 -070026#include "lock_word-inl.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070027#include "mirror/art_method-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070028#include "mirror/class-inl.h"
Ian Rogers05f30572013-02-20 12:13:11 -080029#include "mirror/object-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080030#include "mirror/object_array-inl.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070031#include "scoped_thread_state_change.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070032#include "thread.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070033#include "thread_list.h"
Elliott Hughes08fc03a2012-06-26 17:34:00 -070034#include "verifier/method_verifier.h"
Elliott Hughes044288f2012-06-25 14:46:39 -070035#include "well_known_classes.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070036
37namespace art {
38
39/*
Ian Rogersd9c4fc92013-10-01 19:45:43 -070040 * Every Object has a monitor associated with it, but not every Object is actually locked. Even
41 * the ones that are locked do not need a full-fledged monitor until a) there is actual contention
42 * or b) wait() is called on the Object.
Elliott Hughes5f791332011-09-15 17:45:30 -070043 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070044 * For Android, we have implemented a scheme similar to the one described in Bacon et al.'s
45 * "Thin locks: featherweight synchronization for Java" (ACM 1998). Things are even easier for us,
46 * though, because we have a full 32 bits to work with.
Elliott Hughes5f791332011-09-15 17:45:30 -070047 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070048 * The two states of an Object's lock are referred to as "thin" and "fat". A lock may transition
49 * from the "thin" state to the "fat" state and this transition is referred to as inflation. Once
50 * a lock has been inflated it remains in the "fat" state indefinitely.
Elliott Hughes5f791332011-09-15 17:45:30 -070051 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070052 * The lock value itself is stored in mirror::Object::monitor_ and the representation is described
53 * in the LockWord value type.
Elliott Hughes54e7df12011-09-16 11:47:04 -070054 *
Elliott Hughes5f791332011-09-15 17:45:30 -070055 * Monitors provide:
56 * - mutually exclusive access to resources
57 * - a way for multiple threads to wait for notification
58 *
59 * In effect, they fill the role of both mutexes and condition variables.
60 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070061 * Only one thread can own the monitor at any time. There may be several threads waiting on it
62 * (the wait call unlocks it). One or more waiting threads may be getting interrupted or notified
63 * at any given time.
Elliott Hughes5f791332011-09-15 17:45:30 -070064 */
Elliott Hughes54e7df12011-09-16 11:47:04 -070065
Elliott Hughesfc861622011-10-17 17:57:47 -070066bool (*Monitor::is_sensitive_thread_hook_)() = NULL;
Elliott Hughesfc861622011-10-17 17:57:47 -070067uint32_t Monitor::lock_profiling_threshold_ = 0;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070068
Elliott Hughesfc861622011-10-17 17:57:47 -070069bool Monitor::IsSensitiveThread() {
70 if (is_sensitive_thread_hook_ != NULL) {
71 return (*is_sensitive_thread_hook_)();
72 }
73 return false;
74}
75
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -080076void Monitor::Init(uint32_t lock_profiling_threshold, bool (*is_sensitive_thread_hook)()) {
Elliott Hughesfc861622011-10-17 17:57:47 -070077 lock_profiling_threshold_ = lock_profiling_threshold;
78 is_sensitive_thread_hook_ = is_sensitive_thread_hook;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070079}
80
Ian Rogersef7d42f2014-01-06 12:55:46 -080081Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code)
Ian Rogers00f7d0e2012-07-19 15:28:27 -070082 : monitor_lock_("a monitor lock", kMonitorLock),
Ian Rogersd9c4fc92013-10-01 19:45:43 -070083 monitor_contenders_("monitor contenders", monitor_lock_),
Mathieu Chartier46bc7782013-11-12 17:03:02 -080084 num_waiters_(0),
Ian Rogers00f7d0e2012-07-19 15:28:27 -070085 owner_(owner),
Elliott Hughes5f791332011-09-15 17:45:30 -070086 lock_count_(0),
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070087 obj_(GcRoot<mirror::Object>(obj)),
Elliott Hughes5f791332011-09-15 17:45:30 -070088 wait_set_(NULL),
Mathieu Chartierad2541a2013-10-25 10:05:23 -070089 hash_code_(hash_code),
jeffhao33dc7712011-11-09 17:54:24 -080090 locking_method_(NULL),
Ian Rogersef7d42f2014-01-06 12:55:46 -080091 locking_dex_pc_(0),
Andreas Gampe74240812014-04-17 10:35:09 -070092 monitor_id_(MonitorPool::ComputeMonitorId(this, self)) {
93#ifdef __LP64__
94 DCHECK(false) << "Should not be reached in 64b";
95 next_free_ = nullptr;
96#endif
97 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
98 // with the owner unlocking the thin-lock.
99 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
100 // The identity hash code is set for the life time of the monitor.
101}
102
103Monitor::Monitor(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code,
104 MonitorId id)
105 : monitor_lock_("a monitor lock", kMonitorLock),
106 monitor_contenders_("monitor contenders", monitor_lock_),
107 num_waiters_(0),
108 owner_(owner),
109 lock_count_(0),
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700110 obj_(GcRoot<mirror::Object>(obj)),
Andreas Gampe74240812014-04-17 10:35:09 -0700111 wait_set_(NULL),
112 hash_code_(hash_code),
113 locking_method_(NULL),
114 locking_dex_pc_(0),
115 monitor_id_(id) {
116#ifdef __LP64__
117 next_free_ = nullptr;
118#endif
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700119 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
120 // with the owner unlocking the thin-lock.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800121 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700122 // The identity hash code is set for the life time of the monitor.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700123}
124
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700125int32_t Monitor::GetHashCode() {
126 while (!HasHashCode()) {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700127 if (hash_code_.CompareExchangeWeakRelaxed(0, mirror::Object::GenerateIdentityHashCode())) {
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700128 break;
129 }
130 }
131 DCHECK(HasHashCode());
Ian Rogers3e5cf302014-05-20 16:40:37 -0700132 return hash_code_.LoadRelaxed();
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700133}
134
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700135bool Monitor::Install(Thread* self) {
136 MutexLock mu(self, monitor_lock_); // Uncontended mutex acquisition as monitor isn't yet public.
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700137 CHECK(owner_ == nullptr || owner_ == self || owner_->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700138 // Propagate the lock state.
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700139 LockWord lw(GetObject()->GetLockWord(false));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700140 switch (lw.GetState()) {
141 case LockWord::kThinLocked: {
142 CHECK_EQ(owner_->GetThreadId(), lw.ThinLockOwner());
143 lock_count_ = lw.ThinLockCount();
144 break;
145 }
146 case LockWord::kHashCode: {
Ian Rogers3e5cf302014-05-20 16:40:37 -0700147 CHECK_EQ(hash_code_.LoadRelaxed(), static_cast<int32_t>(lw.GetHashCode()));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700148 break;
149 }
150 case LockWord::kFatLocked: {
151 // The owner_ is suspended but another thread beat us to install a monitor.
152 return false;
153 }
154 case LockWord::kUnlocked: {
155 LOG(FATAL) << "Inflating unlocked lock word";
156 break;
157 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700158 default: {
159 LOG(FATAL) << "Invalid monitor state " << lw.GetState();
160 return false;
161 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700162 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700163 LockWord fat(this);
164 // Publish the updated lock word, which may race with other threads.
Ian Rogers228602f2014-07-10 02:07:54 -0700165 bool success = GetObject()->CasLockWordWeakSequentiallyConsistent(lw, fat);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700166 // Lock profiling.
Mathieu Chartier9728f912013-10-30 09:45:13 -0700167 if (success && owner_ != nullptr && lock_profiling_threshold_ != 0) {
Andreas Gampe6ec8ebd2014-07-25 13:36:56 -0700168 // Do not abort on dex pc errors. This can easily happen when we want to dump a stack trace on
169 // abort.
170 locking_method_ = owner_->GetCurrentMethod(&locking_dex_pc_, false);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700171 }
172 return success;
Elliott Hughes5f791332011-09-15 17:45:30 -0700173}
174
175Monitor::~Monitor() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700176 // Deflated monitors have a null object.
Elliott Hughes5f791332011-09-15 17:45:30 -0700177}
178
Elliott Hughes5f791332011-09-15 17:45:30 -0700179void Monitor::AppendToWaitSet(Thread* thread) {
180 DCHECK(owner_ == Thread::Current());
181 DCHECK(thread != NULL);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700182 DCHECK(thread->GetWaitNext() == nullptr) << thread->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700183 if (wait_set_ == NULL) {
184 wait_set_ = thread;
185 return;
186 }
187
188 // push_back.
189 Thread* t = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700190 while (t->GetWaitNext() != nullptr) {
191 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700192 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700193 t->SetWaitNext(thread);
Elliott Hughes5f791332011-09-15 17:45:30 -0700194}
195
Elliott Hughes5f791332011-09-15 17:45:30 -0700196void Monitor::RemoveFromWaitSet(Thread *thread) {
197 DCHECK(owner_ == Thread::Current());
198 DCHECK(thread != NULL);
199 if (wait_set_ == NULL) {
200 return;
201 }
202 if (wait_set_ == thread) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700203 wait_set_ = thread->GetWaitNext();
204 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700205 return;
206 }
207
208 Thread* t = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700209 while (t->GetWaitNext() != NULL) {
210 if (t->GetWaitNext() == thread) {
211 t->SetWaitNext(thread->GetWaitNext());
212 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700213 return;
214 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700215 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700216 }
217}
218
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700219void Monitor::SetObject(mirror::Object* object) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700220 obj_ = GcRoot<mirror::Object>(object);
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700221}
222
Elliott Hughes5f791332011-09-15 17:45:30 -0700223void Monitor::Lock(Thread* self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700224 MutexLock mu(self, monitor_lock_);
225 while (true) {
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700226 if (owner_ == nullptr) { // Unowned.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700227 owner_ = self;
228 CHECK_EQ(lock_count_, 0);
229 // When debugging, save the current monitor holder for future
230 // acquisition failures to use in sampled logging.
231 if (lock_profiling_threshold_ != 0) {
232 locking_method_ = self->GetCurrentMethod(&locking_dex_pc_);
233 }
234 return;
235 } else if (owner_ == self) { // Recursive.
236 lock_count_++;
237 return;
238 }
239 // Contended.
240 const bool log_contention = (lock_profiling_threshold_ != 0);
Xin Guan65282b22014-08-22 11:55:37 -0500241 uint64_t wait_start_ms = log_contention ? MilliTime() : 0;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800242 mirror::ArtMethod* owners_method = locking_method_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700243 uint32_t owners_dex_pc = locking_dex_pc_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700244 // Do this before releasing the lock so that we don't get deflated.
245 ++num_waiters_;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700246 monitor_lock_.Unlock(self); // Let go of locks in order.
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700247 self->SetMonitorEnterObject(GetObject());
Elliott Hughes5f791332011-09-15 17:45:30 -0700248 {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700249 ScopedThreadStateChange tsc(self, kBlocked); // Change to blocked and give up mutator_lock_.
250 MutexLock mu2(self, monitor_lock_); // Reacquire monitor_lock_ without mutator_lock_ for Wait.
251 if (owner_ != NULL) { // Did the owner_ give the lock up?
252 monitor_contenders_.Wait(self); // Still contended so wait.
253 // Woken from contention.
254 if (log_contention) {
255 uint64_t wait_ms = MilliTime() - wait_start_ms;
256 uint32_t sample_percent;
257 if (wait_ms >= lock_profiling_threshold_) {
258 sample_percent = 100;
259 } else {
260 sample_percent = 100 * wait_ms / lock_profiling_threshold_;
261 }
262 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
263 const char* owners_filename;
264 uint32_t owners_line_number;
265 TranslateLocation(owners_method, owners_dex_pc, &owners_filename, &owners_line_number);
266 LogContentionEvent(self, wait_ms, sample_percent, owners_filename, owners_line_number);
267 }
268 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700269 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700270 }
Mathieu Chartiera6e7f082014-05-22 14:43:37 -0700271 self->SetMonitorEnterObject(nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700272 monitor_lock_.Lock(self); // Reacquire locks in order.
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700273 --num_waiters_;
Elliott Hughesfc861622011-10-17 17:57:47 -0700274 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700275}
276
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800277static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
278 __attribute__((format(printf, 1, 2)));
279
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700280static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700281 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800282 va_list args;
283 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800284 Thread* self = Thread::Current();
285 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
286 self->ThrowNewExceptionV(throw_location, "Ljava/lang/IllegalMonitorStateException;", fmt, args);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700287 if (!Runtime::Current()->IsStarted() || VLOG_IS_ON(monitor)) {
Brian Carlstrom64277f32012-03-26 23:53:34 -0700288 std::ostringstream ss;
Ian Rogers62d6c772013-02-27 08:32:07 -0800289 self->Dump(ss);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700290 LOG(Runtime::Current()->IsStarted() ? INFO : ERROR)
291 << self->GetException(NULL)->Dump() << "\n" << ss.str();
Brian Carlstrom64277f32012-03-26 23:53:34 -0700292 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800293 va_end(args);
294}
295
Elliott Hughesd4237412012-02-21 11:24:45 -0800296static std::string ThreadToString(Thread* thread) {
297 if (thread == NULL) {
298 return "NULL";
299 }
300 std::ostringstream oss;
301 // TODO: alternatively, we could just return the thread's name.
302 oss << *thread;
303 return oss.str();
304}
305
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800306void Monitor::FailedUnlock(mirror::Object* o, Thread* expected_owner, Thread* found_owner,
Elliott Hughesffb465f2012-03-01 18:46:05 -0800307 Monitor* monitor) {
308 Thread* current_owner = NULL;
309 std::string current_owner_string;
310 std::string expected_owner_string;
311 std::string found_owner_string;
312 {
313 // TODO: isn't this too late to prevent threads from disappearing?
314 // Acquire thread list lock so threads won't disappear from under us.
Ian Rogers50b35e22012-10-04 10:09:15 -0700315 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Elliott Hughesffb465f2012-03-01 18:46:05 -0800316 // Re-read owner now that we hold lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700317 current_owner = (monitor != NULL) ? monitor->GetOwner() : NULL;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800318 // Get short descriptions of the threads involved.
319 current_owner_string = ThreadToString(current_owner);
320 expected_owner_string = ThreadToString(expected_owner);
321 found_owner_string = ThreadToString(found_owner);
322 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800323 if (current_owner == NULL) {
324 if (found_owner == NULL) {
325 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
326 " on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800327 PrettyTypeOf(o).c_str(),
328 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800329 } else {
330 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800331 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
332 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800333 found_owner_string.c_str(),
334 PrettyTypeOf(o).c_str(),
335 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800336 }
337 } else {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800338 if (found_owner == NULL) {
339 // Race: originally there was no owner, there is now
340 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
341 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800342 current_owner_string.c_str(),
343 PrettyTypeOf(o).c_str(),
344 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800345 } else {
346 if (found_owner != current_owner) {
347 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800348 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
349 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800350 found_owner_string.c_str(),
351 current_owner_string.c_str(),
352 PrettyTypeOf(o).c_str(),
353 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800354 } else {
355 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
356 " on thread '%s",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800357 current_owner_string.c_str(),
358 PrettyTypeOf(o).c_str(),
359 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800360 }
361 }
362 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700363}
364
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700365bool Monitor::Unlock(Thread* self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700366 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700367 MutexLock mu(self, monitor_lock_);
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800368 Thread* owner = owner_;
369 if (owner == self) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700370 // We own the monitor, so nobody else can be in here.
371 if (lock_count_ == 0) {
372 owner_ = NULL;
jeffhao33dc7712011-11-09 17:54:24 -0800373 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700374 locking_dex_pc_ = 0;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700375 // Wake a contender.
376 monitor_contenders_.Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700377 } else {
378 --lock_count_;
379 }
380 } else {
381 // We don't own this, so we're not allowed to unlock it.
382 // The JNI spec says that we should throw IllegalMonitorStateException
383 // in this case.
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700384 FailedUnlock(GetObject(), self, owner, this);
Elliott Hughes5f791332011-09-15 17:45:30 -0700385 return false;
386 }
387 return true;
388}
389
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800390void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
391 bool interruptShouldThrow, ThreadState why) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700392 DCHECK(self != NULL);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800393 DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
Elliott Hughes5f791332011-09-15 17:45:30 -0700394
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700395 monitor_lock_.Lock(self);
396
Elliott Hughes5f791332011-09-15 17:45:30 -0700397 // Make sure that we hold the lock.
398 if (owner_ != self) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700399 monitor_lock_.Unlock(self);
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700400 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700401 return;
402 }
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800403
Elliott Hughesdf42c482013-01-09 12:49:02 -0800404 // We need to turn a zero-length timed wait into a regular wait because
405 // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
406 if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
407 why = kWaiting;
408 }
409
Elliott Hughes5f791332011-09-15 17:45:30 -0700410 // Enforce the timeout range.
411 if (ms < 0 || ns < 0 || ns > 999999) {
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700412 monitor_lock_.Unlock(self);
Ian Rogers62d6c772013-02-27 08:32:07 -0800413 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
414 self->ThrowNewExceptionF(throw_location, "Ljava/lang/IllegalArgumentException;",
Ian Rogersef7d42f2014-01-06 12:55:46 -0800415 "timeout arguments out of range: ms=%" PRId64 " ns=%d", ms, ns);
Elliott Hughes5f791332011-09-15 17:45:30 -0700416 return;
417 }
418
Elliott Hughes5f791332011-09-15 17:45:30 -0700419 /*
420 * Add ourselves to the set of threads waiting on this monitor, and
421 * release our hold. We need to let it go even if we're a few levels
422 * deep in a recursive lock, and we need to restore that later.
423 *
424 * We append to the wait set ahead of clearing the count and owner
425 * fields so the subroutine can check that the calling thread owns
426 * the monitor. Aside from that, the order of member updates is
427 * not order sensitive as we hold the pthread mutex.
428 */
429 AppendToWaitSet(self);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700430 ++num_waiters_;
Ian Rogers0399dde2012-06-06 17:09:28 -0700431 int prev_lock_count = lock_count_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700432 lock_count_ = 0;
433 owner_ = NULL;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800434 mirror::ArtMethod* saved_method = locking_method_;
jeffhao33dc7712011-11-09 17:54:24 -0800435 locking_method_ = NULL;
Ian Rogers0399dde2012-06-06 17:09:28 -0700436 uintptr_t saved_dex_pc = locking_dex_pc_;
437 locking_dex_pc_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700438
439 /*
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800440 * Update thread state. If the GC wakes up, it'll ignore us, knowing
Elliott Hughes5f791332011-09-15 17:45:30 -0700441 * that we won't touch any references in this state, and we'll check
442 * our suspend mode before we transition out.
443 */
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800444 self->TransitionFromRunnableToSuspended(why);
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 {
448 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700449 MutexLock mu(self, *self->GetWaitMutex());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700450
451 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
452 // non-NULL a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
453 // up.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700454 DCHECK(self->GetWaitMonitor() == nullptr);
455 self->SetWaitMonitor(this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700456
457 // Release the monitor lock.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700458 monitor_contenders_.Signal(self);
459 monitor_lock_.Unlock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700460
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800461 // Handle the case where the thread was interrupted before we called wait().
Ian Rogersdd7624d2014-03-14 17:43:00 -0700462 if (self->IsInterruptedLocked()) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800463 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700464 } else {
465 // Wait for a notification or a timeout to occur.
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800466 if (why == kWaiting) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700467 self->GetWaitConditionVariable()->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700468 } else {
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800469 DCHECK(why == kTimedWaiting || why == kSleeping) << why;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700470 self->GetWaitConditionVariable()->TimedWait(self, ms, ns);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700471 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700472 if (self->IsInterruptedLocked()) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800473 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700474 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700475 self->SetInterruptedLocked(false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700476 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700477 }
478
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700479 // Set self->status back to kRunnable, and self-suspend if needed.
480 self->TransitionFromSuspendedToRunnable();
Elliott Hughes5f791332011-09-15 17:45:30 -0700481
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800482 {
483 // We reset the thread's wait_monitor_ field after transitioning back to runnable so
484 // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
485 // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
486 // are waiting on "null".)
Ian Rogersdd7624d2014-03-14 17:43:00 -0700487 MutexLock mu(self, *self->GetWaitMutex());
488 DCHECK(self->GetWaitMonitor() != nullptr);
489 self->SetWaitMonitor(nullptr);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800490 }
491
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700492 // Re-acquire the monitor and lock.
Elliott Hughes5f791332011-09-15 17:45:30 -0700493 Lock(self);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700494 monitor_lock_.Lock(self);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700495 self->GetWaitMutex()->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700496
Elliott Hughes5f791332011-09-15 17:45:30 -0700497 /*
498 * We remove our thread from wait set after restoring the count
499 * and owner fields so the subroutine can check that the calling
500 * thread owns the monitor. Aside from that, the order of member
501 * updates is not order sensitive as we hold the pthread mutex.
502 */
503 owner_ = self;
Ian Rogers0399dde2012-06-06 17:09:28 -0700504 lock_count_ = prev_lock_count;
505 locking_method_ = saved_method;
506 locking_dex_pc_ = saved_dex_pc;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700507 --num_waiters_;
Elliott Hughes5f791332011-09-15 17:45:30 -0700508 RemoveFromWaitSet(self);
509
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700510 monitor_lock_.Unlock(self);
511
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800512 if (was_interrupted) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700513 /*
514 * We were interrupted while waiting, or somebody interrupted an
515 * un-interruptible thread earlier and we're bailing out immediately.
516 *
517 * The doc sayeth: "The interrupted status of the current thread is
518 * cleared when this exception is thrown."
519 */
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700520 {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700521 MutexLock mu(self, *self->GetWaitMutex());
522 self->SetInterruptedLocked(false);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700523 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700524 if (interruptShouldThrow) {
Ian Rogers62d6c772013-02-27 08:32:07 -0800525 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
526 self->ThrowNewException(throw_location, "Ljava/lang/InterruptedException;", NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700527 }
528 }
529}
530
531void Monitor::Notify(Thread* self) {
532 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700533 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700534 // Make sure that we hold the lock.
535 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800536 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700537 return;
538 }
539 // Signal the first waiting thread in the wait set.
540 while (wait_set_ != NULL) {
541 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700542 wait_set_ = thread->GetWaitNext();
543 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700544
545 // Check to see if the thread is still waiting.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700546 MutexLock mu(self, *thread->GetWaitMutex());
547 if (thread->GetWaitMonitor() != nullptr) {
548 thread->GetWaitConditionVariable()->Signal(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700549 return;
550 }
551 }
552}
553
554void Monitor::NotifyAll(Thread* self) {
555 DCHECK(self != NULL);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700556 MutexLock mu(self, monitor_lock_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700557 // Make sure that we hold the lock.
558 if (owner_ != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800559 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700560 return;
561 }
562 // Signal all threads in the wait set.
563 while (wait_set_ != NULL) {
564 Thread* thread = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700565 wait_set_ = thread->GetWaitNext();
566 thread->SetWaitNext(nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700567 thread->Notify();
568 }
569}
570
Mathieu Chartier590fee92013-09-13 13:46:47 -0700571bool Monitor::Deflate(Thread* self, mirror::Object* obj) {
572 DCHECK(obj != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700573 // Don't need volatile since we only deflate with mutators suspended.
574 LockWord lw(obj->GetLockWord(false));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700575 // If the lock isn't an inflated monitor, then we don't need to deflate anything.
576 if (lw.GetState() == LockWord::kFatLocked) {
577 Monitor* monitor = lw.FatLockMonitor();
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700578 DCHECK(monitor != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700579 MutexLock mu(self, monitor->monitor_lock_);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700580 // Can't deflate if we have anybody waiting on the CV.
581 if (monitor->num_waiters_ > 0) {
582 return false;
583 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700584 Thread* owner = monitor->owner_;
585 if (owner != nullptr) {
586 // Can't deflate if we are locked and have a hash code.
587 if (monitor->HasHashCode()) {
588 return false;
589 }
590 // Can't deflate if our lock count is too high.
591 if (monitor->lock_count_ > LockWord::kThinLockMaxCount) {
592 return false;
593 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700594 // Deflate to a thin lock.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700595 obj->SetLockWord(LockWord::FromThinLockId(owner->GetThreadId(), monitor->lock_count_), false);
596 VLOG(monitor) << "Deflated " << obj << " to thin lock " << owner->GetTid() << " / "
597 << monitor->lock_count_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700598 } else if (monitor->HasHashCode()) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700599 obj->SetLockWord(LockWord::FromHashCode(monitor->GetHashCode()), false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700600 VLOG(monitor) << "Deflated " << obj << " to hash monitor " << monitor->GetHashCode();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700601 } else {
602 // No lock and no hash, just put an empty lock word inside the object.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700603 obj->SetLockWord(LockWord(), false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -0700604 VLOG(monitor) << "Deflated" << obj << " to empty lock word";
Mathieu Chartier590fee92013-09-13 13:46:47 -0700605 }
606 // The monitor is deflated, mark the object as nullptr so that we know to delete it during the
607 // next GC.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700608 monitor->obj_ = GcRoot<mirror::Object>(nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700609 }
610 return true;
611}
612
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700613void Monitor::Inflate(Thread* self, Thread* owner, mirror::Object* obj, int32_t hash_code) {
Andreas Gampe74240812014-04-17 10:35:09 -0700614 DCHECK(self != nullptr);
615 DCHECK(obj != nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700616 // Allocate and acquire a new monitor.
Andreas Gampe74240812014-04-17 10:35:09 -0700617 Monitor* m = MonitorPool::CreateMonitor(self, owner, obj, hash_code);
618 DCHECK(m != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700619 if (m->Install(self)) {
Haifeng Li86ab7912014-05-16 10:47:59 +0800620 if (owner != nullptr) {
621 VLOG(monitor) << "monitor: thread" << owner->GetThreadId()
Andreas Gampe74240812014-04-17 10:35:09 -0700622 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800623 } else {
624 VLOG(monitor) << "monitor: Inflate with hashcode " << hash_code
Andreas Gampe74240812014-04-17 10:35:09 -0700625 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +0800626 }
Andreas Gampe74240812014-04-17 10:35:09 -0700627 Runtime::Current()->GetMonitorList()->Add(m);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700628 CHECK_EQ(obj->GetLockWord(true).GetState(), LockWord::kFatLocked);
Andreas Gampe74240812014-04-17 10:35:09 -0700629 } else {
630 MonitorPool::ReleaseMonitor(self, m);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700631 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700632}
633
Mathieu Chartier0cd81352014-05-22 16:48:55 -0700634void Monitor::InflateThinLocked(Thread* self, Handle<mirror::Object> obj, LockWord lock_word,
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700635 uint32_t hash_code) {
636 DCHECK_EQ(lock_word.GetState(), LockWord::kThinLocked);
637 uint32_t owner_thread_id = lock_word.ThinLockOwner();
638 if (owner_thread_id == self->GetThreadId()) {
639 // We own the monitor, we can easily inflate it.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700640 Inflate(self, self, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700641 } else {
642 ThreadList* thread_list = Runtime::Current()->GetThreadList();
643 // Suspend the owner, inflate. First change to blocked and give up mutator_lock_.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700644 self->SetMonitorEnterObject(obj.Get());
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700645 bool timed_out;
646 Thread* owner;
647 {
648 ScopedThreadStateChange tsc(self, kBlocked);
Ian Rogersf3d874c2014-07-17 18:52:42 -0700649 // Take suspend thread lock to avoid races with threads trying to suspend this one.
650 MutexLock mu(self, *Locks::thread_list_suspend_thread_lock_);
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700651 owner = thread_list->SuspendThreadByThreadId(owner_thread_id, false, &timed_out);
652 }
653 if (owner != nullptr) {
654 // We succeeded in suspending the thread, check the lock's status didn't change.
655 lock_word = obj->GetLockWord(true);
656 if (lock_word.GetState() == LockWord::kThinLocked &&
657 lock_word.ThinLockOwner() == owner_thread_id) {
658 // Go ahead and inflate the lock.
659 Inflate(self, owner, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700660 }
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -0700661 thread_list->Resume(owner, false);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700662 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700663 self->SetMonitorEnterObject(nullptr);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700664 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700665}
666
Ian Rogers719d1a32014-03-06 12:13:39 -0800667// Fool annotalysis into thinking that the lock on obj is acquired.
668static mirror::Object* FakeLock(mirror::Object* obj)
669 EXCLUSIVE_LOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
670 return obj;
671}
672
673// Fool annotalysis into thinking that the lock on obj is release.
674static mirror::Object* FakeUnlock(mirror::Object* obj)
675 UNLOCK_FUNCTION(obj) NO_THREAD_SAFETY_ANALYSIS {
676 return obj;
677}
678
Mathieu Chartiere7e8a5f2014-02-14 16:59:41 -0800679mirror::Object* Monitor::MonitorEnter(Thread* self, mirror::Object* obj) {
Elliott Hughes4681c802011-09-25 18:04:37 -0700680 DCHECK(self != NULL);
681 DCHECK(obj != NULL);
Ian Rogers719d1a32014-03-06 12:13:39 -0800682 obj = FakeLock(obj);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700683 uint32_t thread_id = self->GetThreadId();
684 size_t contention_count = 0;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700685 StackHandleScope<1> hs(self);
686 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700687 while (true) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700688 LockWord lock_word = h_obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700689 switch (lock_word.GetState()) {
690 case LockWord::kUnlocked: {
691 LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0));
Ian Rogers228602f2014-07-10 02:07:54 -0700692 if (h_obj->CasLockWordWeakSequentiallyConsistent(lock_word, thin_locked)) {
Hans Boehm30359612014-05-21 17:46:23 -0700693 // CasLockWord enforces more than the acquire ordering we need here.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700694 return h_obj.Get(); // Success!
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700695 }
696 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -0700697 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700698 case LockWord::kThinLocked: {
699 uint32_t owner_thread_id = lock_word.ThinLockOwner();
700 if (owner_thread_id == thread_id) {
701 // We own the lock, increase the recursion count.
702 uint32_t new_count = lock_word.ThinLockCount() + 1;
703 if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
704 LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700705 h_obj->SetLockWord(thin_locked, true);
706 return h_obj.Get(); // Success!
Elliott Hughes5f791332011-09-15 17:45:30 -0700707 } else {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700708 // We'd overflow the recursion count, so inflate the monitor.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700709 InflateThinLocked(self, h_obj, lock_word, 0);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700710 }
711 } else {
712 // Contention.
713 contention_count++;
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700714 Runtime* runtime = Runtime::Current();
715 if (contention_count <= runtime->GetMaxSpinsBeforeThinkLockInflation()) {
Mathieu Chartierb363f662014-07-16 13:28:58 -0700716 // TODO: Consider switching the thread state to kBlocked when we are yielding.
Mathieu Chartier251755c2014-07-15 18:10:25 -0700717 // Use sched_yield instead of NanoSleep since NanoSleep can wait much longer than the
718 // parameter you pass in. This can cause thread suspension to take excessively long
Mathieu Chartierb363f662014-07-16 13:28:58 -0700719 // and make long pauses. See b/16307460.
Mathieu Chartier251755c2014-07-15 18:10:25 -0700720 sched_yield();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700721 } else {
722 contention_count = 0;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700723 InflateThinLocked(self, h_obj, lock_word, 0);
Elliott Hughes5f791332011-09-15 17:45:30 -0700724 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700725 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700726 continue; // Start from the beginning.
Elliott Hughes5f791332011-09-15 17:45:30 -0700727 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700728 case LockWord::kFatLocked: {
729 Monitor* mon = lock_word.FatLockMonitor();
730 mon->Lock(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700731 return h_obj.Get(); // Success!
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700732 }
Ian Rogers719d1a32014-03-06 12:13:39 -0800733 case LockWord::kHashCode:
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700734 // Inflate with the existing hashcode.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700735 Inflate(self, nullptr, h_obj.Get(), lock_word.GetHashCode());
Ian Rogers719d1a32014-03-06 12:13:39 -0800736 continue; // Start from the beginning.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700737 default: {
738 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700739 return h_obj.Get();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700740 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700741 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700742 }
743}
744
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800745bool Monitor::MonitorExit(Thread* self, mirror::Object* obj) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700746 DCHECK(self != NULL);
Elliott Hughes5f791332011-09-15 17:45:30 -0700747 DCHECK(obj != NULL);
Ian Rogers719d1a32014-03-06 12:13:39 -0800748 obj = FakeUnlock(obj);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700749 LockWord lock_word = obj->GetLockWord(true);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700750 StackHandleScope<1> hs(self);
751 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700752 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700753 case LockWord::kHashCode:
754 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700755 case LockWord::kUnlocked:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700756 FailedUnlock(h_obj.Get(), self, nullptr, nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700757 return false; // Failure.
758 case LockWord::kThinLocked: {
759 uint32_t thread_id = self->GetThreadId();
760 uint32_t owner_thread_id = lock_word.ThinLockOwner();
761 if (owner_thread_id != thread_id) {
762 // TODO: there's a race here with the owner dying while we unlock.
763 Thread* owner =
764 Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700765 FailedUnlock(h_obj.Get(), self, owner, nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700766 return false; // Failure.
767 } else {
768 // We own the lock, decrease the recursion count.
769 if (lock_word.ThinLockCount() != 0) {
770 uint32_t new_count = lock_word.ThinLockCount() - 1;
771 LockWord thin_locked(LockWord::FromThinLockId(thread_id, new_count));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700772 h_obj->SetLockWord(thin_locked, true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700773 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700774 h_obj->SetLockWord(LockWord(), true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700775 }
776 return true; // Success!
777 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700778 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700779 case LockWord::kFatLocked: {
780 Monitor* mon = lock_word.FatLockMonitor();
781 return mon->Unlock(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700782 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700783 default: {
784 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700785 return false;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700786 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700787 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700788}
789
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800790void Monitor::Wait(Thread* self, mirror::Object *obj, int64_t ms, int32_t ns,
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800791 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700792 DCHECK(self != nullptr);
793 DCHECK(obj != nullptr);
794 LockWord lock_word = obj->GetLockWord(true);
Ian Rogers43c69cc2014-08-15 11:09:28 -0700795 while (lock_word.GetState() != LockWord::kFatLocked) {
796 switch (lock_word.GetState()) {
797 case LockWord::kHashCode:
798 // Fall-through.
799 case LockWord::kUnlocked:
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700800 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
801 return; // Failure.
Ian Rogers43c69cc2014-08-15 11:09:28 -0700802 case LockWord::kThinLocked: {
803 uint32_t thread_id = self->GetThreadId();
804 uint32_t owner_thread_id = lock_word.ThinLockOwner();
805 if (owner_thread_id != thread_id) {
806 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
807 return; // Failure.
808 } else {
809 // We own the lock, inflate to enqueue ourself on the Monitor. May fail spuriously so
810 // re-load.
811 Inflate(self, self, obj, 0);
812 lock_word = obj->GetLockWord(true);
813 }
814 break;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700815 }
Ian Rogers43c69cc2014-08-15 11:09:28 -0700816 case LockWord::kFatLocked: // Unreachable given the loop condition above. Fall-through.
817 default: {
818 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
819 return;
820 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700821 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700822 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700823 Monitor* mon = lock_word.FatLockMonitor();
824 mon->Wait(self, ms, ns, interruptShouldThrow, why);
Elliott Hughes5f791332011-09-15 17:45:30 -0700825}
826
Ian Rogers13c479e2013-10-11 07:59:01 -0700827void Monitor::DoNotify(Thread* self, mirror::Object* obj, bool notify_all) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700828 DCHECK(self != nullptr);
829 DCHECK(obj != nullptr);
830 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700831 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700832 case LockWord::kHashCode:
833 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700834 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800835 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700836 return; // Failure.
837 case LockWord::kThinLocked: {
838 uint32_t thread_id = self->GetThreadId();
839 uint32_t owner_thread_id = lock_word.ThinLockOwner();
840 if (owner_thread_id != thread_id) {
841 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
842 return; // Failure.
843 } else {
844 // We own the lock but there's no Monitor and therefore no waiters.
845 return; // Success.
846 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700847 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700848 case LockWord::kFatLocked: {
849 Monitor* mon = lock_word.FatLockMonitor();
850 if (notify_all) {
851 mon->NotifyAll(self);
852 } else {
853 mon->Notify(self);
854 }
855 return; // Success.
856 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700857 default: {
858 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
859 return;
860 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700861 }
862}
863
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700864uint32_t Monitor::GetLockOwnerThreadId(mirror::Object* obj) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700865 DCHECK(obj != nullptr);
866 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700867 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700868 case LockWord::kHashCode:
869 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700870 case LockWord::kUnlocked:
871 return ThreadList::kInvalidThreadId;
872 case LockWord::kThinLocked:
873 return lock_word.ThinLockOwner();
874 case LockWord::kFatLocked: {
875 Monitor* mon = lock_word.FatLockMonitor();
876 return mon->GetOwnerThreadId();
Elliott Hughes5f791332011-09-15 17:45:30 -0700877 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700878 default: {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700879 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -0700880 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700881 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700882 }
883}
884
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700885void Monitor::DescribeWait(std::ostream& os, const Thread* thread) {
Ian Rogersd803bc72014-04-01 15:33:03 -0700886 // Determine the wait message and object we're waiting or blocked upon.
887 mirror::Object* pretty_object = nullptr;
888 const char* wait_message = nullptr;
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700889 uint32_t lock_owner = ThreadList::kInvalidThreadId;
Ian Rogersd803bc72014-04-01 15:33:03 -0700890 ThreadState state = thread->GetState();
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800891 if (state == kWaiting || state == kTimedWaiting || state == kSleeping) {
Ian Rogersd803bc72014-04-01 15:33:03 -0700892 wait_message = (state == kSleeping) ? " - sleeping on " : " - waiting on ";
893 Thread* self = Thread::Current();
894 MutexLock mu(self, *thread->GetWaitMutex());
895 Monitor* monitor = thread->GetWaitMonitor();
896 if (monitor != nullptr) {
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700897 pretty_object = monitor->GetObject();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700898 }
Elliott Hughes34e06962012-04-09 13:55:55 -0700899 } else if (state == kBlocked) {
Ian Rogersd803bc72014-04-01 15:33:03 -0700900 wait_message = " - waiting to lock ";
901 pretty_object = thread->GetMonitorEnterObject();
902 if (pretty_object != nullptr) {
903 lock_owner = pretty_object->GetLockOwnerThreadId();
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700904 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700905 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700906
Ian Rogersd803bc72014-04-01 15:33:03 -0700907 if (wait_message != nullptr) {
908 if (pretty_object == nullptr) {
909 os << wait_message << "an unknown object";
910 } else {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700911 if ((pretty_object->GetLockWord(true).GetState() == LockWord::kThinLocked) &&
Ian Rogersd803bc72014-04-01 15:33:03 -0700912 Locks::mutator_lock_->IsExclusiveHeld(Thread::Current())) {
913 // Getting the identity hashcode here would result in lock inflation and suspension of the
914 // current thread, which isn't safe if this is the only runnable thread.
915 os << wait_message << StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)",
916 reinterpret_cast<intptr_t>(pretty_object),
917 PrettyTypeOf(pretty_object).c_str());
918 } else {
919 // - waiting on <0x6008c468> (a java.lang.Class<java.lang.ref.ReferenceQueue>)
920 os << wait_message << StringPrintf("<0x%08x> (a %s)", pretty_object->IdentityHashCode(),
921 PrettyTypeOf(pretty_object).c_str());
922 }
923 }
924 // - waiting to lock <0x613f83d8> (a java.lang.Object) held by thread 5
925 if (lock_owner != ThreadList::kInvalidThreadId) {
926 os << " held by thread " << lock_owner;
927 }
928 os << "\n";
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700929 }
Elliott Hughes8e4aac52011-09-26 17:03:36 -0700930}
931
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800932mirror::Object* Monitor::GetContendedMonitor(Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -0800933 // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
934 // definition of contended that includes a monitor a thread is trying to enter...
Ian Rogersdd7624d2014-03-14 17:43:00 -0700935 mirror::Object* result = thread->GetMonitorEnterObject();
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700936 if (result == NULL) {
937 // ...but also a monitor that the thread is waiting on.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700938 MutexLock mu(Thread::Current(), *thread->GetWaitMutex());
939 Monitor* monitor = thread->GetWaitMonitor();
Elliott Hughesf9501702013-01-11 11:22:27 -0800940 if (monitor != NULL) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700941 result = monitor->GetObject();
Elliott Hughesf9501702013-01-11 11:22:27 -0800942 }
943 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700944 return result;
Elliott Hughesf9501702013-01-11 11:22:27 -0800945}
946
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800947void Monitor::VisitLocks(StackVisitor* stack_visitor, void (*callback)(mirror::Object*, void*),
Andreas Gampe956a5222014-08-16 13:41:10 -0700948 void* callback_context, bool abort_on_failure) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700949 mirror::ArtMethod* m = stack_visitor->GetMethod();
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700950 CHECK(m != NULL);
951
952 // Native methods are an easy special case.
953 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
954 if (m->IsNative()) {
955 if (m->IsSynchronized()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700956 mirror::Object* jni_this = stack_visitor->GetCurrentHandleScope()->GetReference(0);
Elliott Hughes4993bbc2013-01-10 15:41:25 -0800957 callback(jni_this, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700958 }
959 return;
960 }
961
jeffhao61f916c2012-10-25 17:48:51 -0700962 // Proxy methods should not be synchronized.
963 if (m->IsProxyMethod()) {
964 CHECK(!m->IsSynchronized());
965 return;
966 }
967
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700968 // Is there any reason to believe there's any synchronization in this method?
Mathieu Chartierbfd9a432014-05-21 17:43:44 -0700969 const DexFile::CodeItem* code_item = m->GetCodeItem();
Elliott Hughescaf76542012-06-28 16:08:22 -0700970 CHECK(code_item != NULL) << PrettyMethod(m);
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700971 if (code_item->tries_size_ == 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700972 return; // No "tries" implies no synchronization, so no held locks to report.
Elliott Hughes08fc03a2012-06-26 17:34:00 -0700973 }
974
Andreas Gampe956a5222014-08-16 13:41:10 -0700975 // Get the dex pc. If abort_on_failure is false, GetDexPc will not abort in the case it cannot
976 // find the dex pc, and instead return kDexNoIndex. Then bail out, as it indicates we have an
977 // inconsistent stack anyways.
978 uint32_t dex_pc = stack_visitor->GetDexPc(abort_on_failure);
979 if (!abort_on_failure && dex_pc == DexFile::kDexNoIndex) {
980 LOG(ERROR) << "Could not find dex_pc for " << PrettyMethod(m);
981 return;
982 }
983
Elliott Hughes80537bb2013-01-04 16:37:26 -0800984 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
985 // the locks held in this stack frame.
986 std::vector<uint32_t> monitor_enter_dex_pcs;
Andreas Gampe956a5222014-08-16 13:41:10 -0700987 verifier::MethodVerifier::FindLocksAtDexPc(m, dex_pc, &monitor_enter_dex_pcs);
Elliott Hughes80537bb2013-01-04 16:37:26 -0800988 if (monitor_enter_dex_pcs.empty()) {
989 return;
990 }
991
Elliott Hughes80537bb2013-01-04 16:37:26 -0800992 for (size_t i = 0; i < monitor_enter_dex_pcs.size(); ++i) {
993 // The verifier works in terms of the dex pcs of the monitor-enter instructions.
994 // We want the registers used by those instructions (so we can read the values out of them).
995 uint32_t dex_pc = monitor_enter_dex_pcs[i];
996 uint16_t monitor_enter_instruction = code_item->insns_[dex_pc];
997
998 // Quick sanity check.
999 if ((monitor_enter_instruction & 0xff) != Instruction::MONITOR_ENTER) {
1000 LOG(FATAL) << "expected monitor-enter @" << dex_pc << "; was "
1001 << reinterpret_cast<void*>(monitor_enter_instruction);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001002 }
1003
Elliott Hughes80537bb2013-01-04 16:37:26 -08001004 uint16_t monitor_register = ((monitor_enter_instruction >> 8) & 0xff);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001005 mirror::Object* o = reinterpret_cast<mirror::Object*>(stack_visitor->GetVReg(m, monitor_register,
1006 kReferenceVReg));
Elliott Hughes4993bbc2013-01-10 15:41:25 -08001007 callback(o, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001008 }
1009}
1010
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001011bool Monitor::IsValidLockWord(LockWord lock_word) {
1012 switch (lock_word.GetState()) {
1013 case LockWord::kUnlocked:
1014 // Nothing to check.
1015 return true;
1016 case LockWord::kThinLocked:
1017 // Basic sanity check of owner.
1018 return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
1019 case LockWord::kFatLocked: {
1020 // Check the monitor appears in the monitor list.
1021 Monitor* mon = lock_word.FatLockMonitor();
1022 MonitorList* list = Runtime::Current()->GetMonitorList();
1023 MutexLock mu(Thread::Current(), list->monitor_list_lock_);
1024 for (Monitor* list_mon : list->list_) {
1025 if (mon == list_mon) {
1026 return true; // Found our monitor.
1027 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001028 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001029 return false; // Fail - unowned monitor in an object.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001030 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001031 case LockWord::kHashCode:
1032 return true;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001033 default:
1034 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001035 UNREACHABLE();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001036 }
1037}
1038
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001039bool Monitor::IsLocked() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1040 MutexLock mu(Thread::Current(), monitor_lock_);
1041 return owner_ != nullptr;
1042}
1043
Ian Rogersef7d42f2014-01-06 12:55:46 -08001044void Monitor::TranslateLocation(mirror::ArtMethod* method, uint32_t dex_pc,
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001045 const char** source_file, uint32_t* line_number) const {
jeffhao33dc7712011-11-09 17:54:24 -08001046 // If method is null, location is unknown
1047 if (method == NULL) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001048 *source_file = "";
1049 *line_number = 0;
jeffhao33dc7712011-11-09 17:54:24 -08001050 return;
1051 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001052 *source_file = method->GetDeclaringClassSourceFile();
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001053 if (*source_file == NULL) {
1054 *source_file = "";
Elliott Hughes12c51e32012-01-17 20:25:05 -08001055 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001056 *line_number = method->GetLineNumFromDexPC(dex_pc);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001057}
1058
1059uint32_t Monitor::GetOwnerThreadId() {
1060 MutexLock mu(Thread::Current(), monitor_lock_);
1061 Thread* owner = owner_;
1062 if (owner != NULL) {
1063 return owner->GetThreadId();
1064 } else {
1065 return ThreadList::kInvalidThreadId;
1066 }
jeffhao33dc7712011-11-09 17:54:24 -08001067}
1068
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001069MonitorList::MonitorList()
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001070 : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock", kMonitorListLock),
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001071 monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001072}
1073
1074MonitorList::~MonitorList() {
Andreas Gampe74240812014-04-17 10:35:09 -07001075 Thread* self = Thread::Current();
1076 MutexLock mu(self, monitor_list_lock_);
1077 // Release all monitors to the pool.
1078 // TODO: Is it an invariant that *all* open monitors are in the list? Then we could
1079 // clear faster in the pool.
1080 MonitorPool::ReleaseMonitors(self, &list_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001081}
1082
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001083void MonitorList::DisallowNewMonitors() {
Ian Rogers50b35e22012-10-04 10:09:15 -07001084 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001085 allow_new_monitors_ = false;
1086}
1087
1088void MonitorList::AllowNewMonitors() {
1089 Thread* self = Thread::Current();
1090 MutexLock mu(self, monitor_list_lock_);
1091 allow_new_monitors_ = true;
1092 monitor_add_condition_.Broadcast(self);
1093}
1094
1095void MonitorList::Add(Monitor* m) {
1096 Thread* self = Thread::Current();
1097 MutexLock mu(self, monitor_list_lock_);
1098 while (UNLIKELY(!allow_new_monitors_)) {
1099 monitor_add_condition_.WaitHoldingLocks(self);
1100 }
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001101 list_.push_front(m);
1102}
1103
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08001104void MonitorList::SweepMonitorList(IsMarkedCallback* callback, void* arg) {
Andreas Gampe74240812014-04-17 10:35:09 -07001105 Thread* self = Thread::Current();
1106 MutexLock mu(self, monitor_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001107 for (auto it = list_.begin(); it != list_.end(); ) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001108 Monitor* m = *it;
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001109 // Disable the read barrier in GetObject() as this is called by GC.
1110 mirror::Object* obj = m->GetObject<kWithoutReadBarrier>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001111 // The object of a monitor can be null if we have deflated it.
Mathieu Chartier83c8ee02014-01-28 14:50:23 -08001112 mirror::Object* new_obj = obj != nullptr ? callback(obj, arg) : nullptr;
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001113 if (new_obj == nullptr) {
1114 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001115 << obj;
Andreas Gampe74240812014-04-17 10:35:09 -07001116 MonitorPool::ReleaseMonitor(self, m);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001117 it = list_.erase(it);
1118 } else {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001119 m->SetObject(new_obj);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001120 ++it;
1121 }
1122 }
1123}
1124
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001125struct MonitorDeflateArgs {
1126 MonitorDeflateArgs() : self(Thread::Current()), deflate_count(0) {}
1127 Thread* const self;
1128 size_t deflate_count;
1129};
1130
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001131static mirror::Object* MonitorDeflateCallback(mirror::Object* object, void* arg)
1132 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001133 MonitorDeflateArgs* args = reinterpret_cast<MonitorDeflateArgs*>(arg);
1134 if (Monitor::Deflate(args->self, object)) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001135 DCHECK_NE(object->GetLockWord(true).GetState(), LockWord::kFatLocked);
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001136 ++args->deflate_count;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001137 // If we deflated, return nullptr so that the monitor gets removed from the array.
1138 return nullptr;
1139 }
1140 return object; // Monitor was not deflated.
1141}
1142
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001143size_t MonitorList::DeflateMonitors() {
1144 MonitorDeflateArgs args;
1145 Locks::mutator_lock_->AssertExclusiveHeld(args.self);
1146 SweepMonitorList(MonitorDeflateCallback, &args);
1147 return args.deflate_count;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001148}
1149
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001150MonitorInfo::MonitorInfo(mirror::Object* obj) : owner_(NULL), entry_count_(0) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001151 DCHECK(obj != nullptr);
1152 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001153 switch (lock_word.GetState()) {
1154 case LockWord::kUnlocked:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001155 // Fall-through.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001156 case LockWord::kForwardingAddress:
1157 // Fall-through.
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001158 case LockWord::kHashCode:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001159 break;
1160 case LockWord::kThinLocked:
1161 owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
1162 entry_count_ = 1 + lock_word.ThinLockCount();
1163 // Thin locks have no waiters.
1164 break;
1165 case LockWord::kFatLocked: {
1166 Monitor* mon = lock_word.FatLockMonitor();
1167 owner_ = mon->owner_;
1168 entry_count_ = 1 + mon->lock_count_;
Ian Rogersdd7624d2014-03-14 17:43:00 -07001169 for (Thread* waiter = mon->wait_set_; waiter != NULL; waiter = waiter->GetWaitNext()) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001170 waiters_.push_back(waiter);
1171 }
1172 break;
Elliott Hughesf327e072013-01-09 16:01:26 -08001173 }
1174 }
1175}
1176
Elliott Hughes5f791332011-09-15 17:45:30 -07001177} // namespace art