blob: f2189e16acdfbfb56e2c4d2e1513b2b5c6eb1df1 [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
Vladimir Markof52d92f2019-03-29 12:33:02 +000017#include "monitor-inl.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070018
Elliott Hughes08fc03a2012-06-26 17:34:00 -070019#include <vector>
20
Andreas Gampe46ee31b2016-12-14 10:11:49 -080021#include "android-base/stringprintf.h"
22
Mathieu Chartiere401d142015-04-22 13:56:20 -070023#include "art_method-inl.h"
Andreas Gampe170331f2017-12-07 18:41:03 -080024#include "base/logging.h" // For VLOG.
Elliott Hughes76b61672012-12-12 17:47:30 -080025#include "base/mutex.h"
David Sehrc431b9d2018-03-02 12:01:51 -080026#include "base/quasi_atomic.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080027#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080028#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010029#include "base/time_utils.h"
jeffhao33dc7712011-11-09 17:54:24 -080030#include "class_linker.h"
David Sehr9e734c72018-01-04 17:56:19 -080031#include "dex/dex_file-inl.h"
32#include "dex/dex_file_types.h"
33#include "dex/dex_instruction-inl.h"
Vladimir Markocedec9d2021-02-08 16:16:13 +000034#include "entrypoints/entrypoint_utils-inl.h"
Ian Rogersd9c4fc92013-10-01 19:45:43 -070035#include "lock_word-inl.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070036#include "mirror/class-inl.h"
Ian Rogers05f30572013-02-20 12:13:11 -080037#include "mirror/object-inl.h"
Andreas Gampe5d08fcc2017-06-05 17:56:46 -070038#include "object_callbacks.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070039#include "scoped_thread_state_change-inl.h"
Andreas Gampe513061a2017-06-01 09:17:34 -070040#include "stack.h"
Elliott Hughes5f791332011-09-15 17:45:30 -070041#include "thread.h"
Elliott Hughes8e4aac52011-09-26 17:03:36 -070042#include "thread_list.h"
Elliott Hughes08fc03a2012-06-26 17:34:00 -070043#include "verifier/method_verifier.h"
Elliott Hughes044288f2012-06-25 14:46:39 -070044#include "well_known_classes.h"
wangguibo0d290722021-04-24 11:27:06 +080045#include <android-base/properties.h>
Elliott Hughes5f791332011-09-15 17:45:30 -070046
Hans Boehm4dd1bf42021-03-08 11:49:34 -080047static_assert(ART_USE_FUTEXES);
48
Elliott Hughes5f791332011-09-15 17:45:30 -070049namespace art {
50
Andreas Gampe46ee31b2016-12-14 10:11:49 -080051using android::base::StringPrintf;
52
Andreas Gampe5d689142017-10-19 13:03:29 -070053static constexpr uint64_t kDebugThresholdFudgeFactor = kIsDebugBuild ? 10 : 1;
54static constexpr uint64_t kLongWaitMs = 100 * kDebugThresholdFudgeFactor;
Mathieu Chartierb9001ab2014-10-03 13:28:46 -070055
Elliott Hughes5f791332011-09-15 17:45:30 -070056/*
Ian Rogersd9c4fc92013-10-01 19:45:43 -070057 * Every Object has a monitor associated with it, but not every Object is actually locked. Even
58 * the ones that are locked do not need a full-fledged monitor until a) there is actual contention
Hans Boehm65c18a22020-01-03 23:37:13 +000059 * or b) wait() is called on the Object, or (c) we need to lock an object that also has an
60 * identity hashcode.
Elliott Hughes5f791332011-09-15 17:45:30 -070061 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070062 * For Android, we have implemented a scheme similar to the one described in Bacon et al.'s
63 * "Thin locks: featherweight synchronization for Java" (ACM 1998). Things are even easier for us,
64 * though, because we have a full 32 bits to work with.
Elliott Hughes5f791332011-09-15 17:45:30 -070065 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070066 * The two states of an Object's lock are referred to as "thin" and "fat". A lock may transition
Daniel Colascionec3d5b842018-04-15 10:52:18 -070067 * from the "thin" state to the "fat" state and this transition is referred to as inflation. We
68 * deflate locks from time to time as part of heap trimming.
Elliott Hughes5f791332011-09-15 17:45:30 -070069 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070070 * The lock value itself is stored in mirror::Object::monitor_ and the representation is described
71 * in the LockWord value type.
Elliott Hughes54e7df12011-09-16 11:47:04 -070072 *
Elliott Hughes5f791332011-09-15 17:45:30 -070073 * Monitors provide:
74 * - mutually exclusive access to resources
75 * - a way for multiple threads to wait for notification
76 *
77 * In effect, they fill the role of both mutexes and condition variables.
78 *
Ian Rogersd9c4fc92013-10-01 19:45:43 -070079 * Only one thread can own the monitor at any time. There may be several threads waiting on it
80 * (the wait call unlocks it). One or more waiting threads may be getting interrupted or notified
81 * at any given time.
Elliott Hughes5f791332011-09-15 17:45:30 -070082 */
Elliott Hughes54e7df12011-09-16 11:47:04 -070083
Elliott Hughesfc861622011-10-17 17:57:47 -070084uint32_t Monitor::lock_profiling_threshold_ = 0;
Andreas Gamped0210e52017-06-23 13:38:09 -070085uint32_t Monitor::stack_dump_lock_profiling_threshold_ = 0;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070086
Andreas Gamped0210e52017-06-23 13:38:09 -070087void Monitor::Init(uint32_t lock_profiling_threshold,
88 uint32_t stack_dump_lock_profiling_threshold) {
Andreas Gampe5d689142017-10-19 13:03:29 -070089 // It isn't great to always include the debug build fudge factor for command-
90 // line driven arguments, but it's easier to adjust here than in the build.
91 lock_profiling_threshold_ =
92 lock_profiling_threshold * kDebugThresholdFudgeFactor;
93 stack_dump_lock_profiling_threshold_ =
94 stack_dump_lock_profiling_threshold * kDebugThresholdFudgeFactor;
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070095}
96
Vladimir Markof52d92f2019-03-29 12:33:02 +000097Monitor::Monitor(Thread* self, Thread* owner, ObjPtr<mirror::Object> obj, int32_t hash_code)
Hans Boehmd56f7d12019-11-19 06:03:11 +000098 : monitor_lock_("a monitor lock", kMonitorLock),
Mathieu Chartier46bc7782013-11-12 17:03:02 -080099 num_waiters_(0),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700100 owner_(owner),
Hans Boehmd56f7d12019-11-19 06:03:11 +0000101 lock_count_(0),
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700102 obj_(GcRoot<mirror::Object>(obj)),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700103 wait_set_(nullptr),
Charles Mungerc665d632018-11-06 16:20:13 +0000104 wake_set_(nullptr),
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700105 hash_code_(hash_code),
Hans Boehme8bd0a92020-01-21 18:14:07 -0800106 lock_owner_(nullptr),
Hans Boehm65c18a22020-01-03 23:37:13 +0000107 lock_owner_method_(nullptr),
108 lock_owner_dex_pc_(0),
Hans Boehme8bd0a92020-01-21 18:14:07 -0800109 lock_owner_sum_(0),
110 lock_owner_request_(nullptr),
Andreas Gampe74240812014-04-17 10:35:09 -0700111 monitor_id_(MonitorPool::ComputeMonitorId(this, self)) {
112#ifdef __LP64__
113 DCHECK(false) << "Should not be reached in 64b";
114 next_free_ = nullptr;
115#endif
116 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
117 // with the owner unlocking the thin-lock.
118 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
119 // The identity hash code is set for the life time of the monitor.
wangguibo0d290722021-04-24 11:27:06 +0800120
121 bool monitor_timeout_enabled = Runtime::Current()->IsMonitorTimeoutEnabled();
122 if (monitor_timeout_enabled) {
123 MaybeEnableTimeout();
124 }
Andreas Gampe74240812014-04-17 10:35:09 -0700125}
126
Vladimir Markof52d92f2019-03-29 12:33:02 +0000127Monitor::Monitor(Thread* self,
128 Thread* owner,
129 ObjPtr<mirror::Object> obj,
130 int32_t hash_code,
Andreas Gampe74240812014-04-17 10:35:09 -0700131 MonitorId id)
Hans Boehmd56f7d12019-11-19 06:03:11 +0000132 : monitor_lock_("a monitor lock", kMonitorLock),
Andreas Gampe74240812014-04-17 10:35:09 -0700133 num_waiters_(0),
134 owner_(owner),
Hans Boehmd56f7d12019-11-19 06:03:11 +0000135 lock_count_(0),
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700136 obj_(GcRoot<mirror::Object>(obj)),
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700137 wait_set_(nullptr),
Charles Mungerc665d632018-11-06 16:20:13 +0000138 wake_set_(nullptr),
Andreas Gampe74240812014-04-17 10:35:09 -0700139 hash_code_(hash_code),
Hans Boehm65c18a22020-01-03 23:37:13 +0000140 lock_owner_(nullptr),
Hans Boehme8bd0a92020-01-21 18:14:07 -0800141 lock_owner_method_(nullptr),
142 lock_owner_dex_pc_(0),
143 lock_owner_sum_(0),
Hans Boehm65c18a22020-01-03 23:37:13 +0000144 lock_owner_request_(nullptr),
Andreas Gampe74240812014-04-17 10:35:09 -0700145 monitor_id_(id) {
146#ifdef __LP64__
147 next_free_ = nullptr;
148#endif
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700149 // We should only inflate a lock if the owner is ourselves or suspended. This avoids a race
150 // with the owner unlocking the thin-lock.
Ian Rogersef7d42f2014-01-06 12:55:46 -0800151 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700152 // The identity hash code is set for the life time of the monitor.
wangguibo0d290722021-04-24 11:27:06 +0800153
154 bool monitor_timeout_enabled = Runtime::Current()->IsMonitorTimeoutEnabled();
155 if (monitor_timeout_enabled) {
156 MaybeEnableTimeout();
157 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700158}
159
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700160int32_t Monitor::GetHashCode() {
Mathieu Chartier8bb3c682018-06-18 12:53:10 -0700161 int32_t hc = hash_code_.load(std::memory_order_relaxed);
162 if (!HasHashCode()) {
163 // Use a strong CAS to prevent spurious failures since these can make the boot image
164 // non-deterministic.
165 hash_code_.CompareAndSetStrongRelaxed(0, mirror::Object::GenerateIdentityHashCode());
166 hc = hash_code_.load(std::memory_order_relaxed);
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700167 }
168 DCHECK(HasHashCode());
Mathieu Chartier8bb3c682018-06-18 12:53:10 -0700169 return hc;
Mathieu Chartier4e6a31e2013-10-31 10:35:05 -0700170}
171
Hans Boehm65c18a22020-01-03 23:37:13 +0000172void Monitor::SetLockingMethod(Thread* owner) {
173 DCHECK(owner == Thread::Current() || owner->IsSuspended());
174 // Do not abort on dex pc errors. This can easily happen when we want to dump a stack trace on
175 // abort.
176 ArtMethod* lock_owner_method;
177 uint32_t lock_owner_dex_pc;
178 lock_owner_method = owner->GetCurrentMethod(&lock_owner_dex_pc, false);
179 if (lock_owner_method != nullptr && UNLIKELY(lock_owner_method->IsProxyMethod())) {
180 // Grab another frame. Proxy methods are not helpful for lock profiling. This should be rare
181 // enough that it's OK to walk the stack twice.
182 struct NextMethodVisitor final : public StackVisitor {
183 explicit NextMethodVisitor(Thread* thread) REQUIRES_SHARED(Locks::mutator_lock_)
184 : StackVisitor(thread,
185 nullptr,
186 StackVisitor::StackWalkKind::kIncludeInlinedFrames,
187 false),
188 count_(0),
189 method_(nullptr),
190 dex_pc_(0) {}
191 bool VisitFrame() override REQUIRES_SHARED(Locks::mutator_lock_) {
192 ArtMethod* m = GetMethod();
193 if (m->IsRuntimeMethod()) {
194 // Continue if this is a runtime method.
195 return true;
196 }
197 count_++;
198 if (count_ == 2u) {
199 method_ = m;
200 dex_pc_ = GetDexPc(false);
201 return false;
202 }
203 return true;
204 }
205 size_t count_;
206 ArtMethod* method_;
207 uint32_t dex_pc_;
208 };
209 NextMethodVisitor nmv(owner_.load(std::memory_order_relaxed));
210 nmv.WalkStack();
211 lock_owner_method = nmv.method_;
212 lock_owner_dex_pc = nmv.dex_pc_;
213 }
214 SetLockOwnerInfo(lock_owner_method, lock_owner_dex_pc, owner);
215 DCHECK(lock_owner_method == nullptr || !lock_owner_method->IsProxyMethod());
216}
217
218void Monitor::SetLockingMethodNoProxy(Thread *owner) {
219 DCHECK(owner == Thread::Current());
220 uint32_t lock_owner_dex_pc;
221 ArtMethod* lock_owner_method = owner->GetCurrentMethod(&lock_owner_dex_pc);
222 // We don't expect a proxy method here.
223 DCHECK(lock_owner_method == nullptr || !lock_owner_method->IsProxyMethod());
224 SetLockOwnerInfo(lock_owner_method, lock_owner_dex_pc, owner);
225}
226
227bool Monitor::Install(Thread* self) NO_THREAD_SAFETY_ANALYSIS {
228 // This may or may not result in acquiring monitor_lock_. Its behavior is much more complicated
229 // than what clang thread safety analysis understands.
230 // Monitor is not yet public.
231 Thread* owner = owner_.load(std::memory_order_relaxed);
Hans Boehm4dd1bf42021-03-08 11:49:34 -0800232 CHECK(owner == nullptr || owner == self || owner->IsSuspended());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700233 // Propagate the lock state.
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -0700234 LockWord lw(GetObject()->GetLockWord(false));
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700235 switch (lw.GetState()) {
236 case LockWord::kThinLocked: {
Hans Boehm65c18a22020-01-03 23:37:13 +0000237 DCHECK(owner != nullptr);
238 CHECK_EQ(owner->GetThreadId(), lw.ThinLockOwner());
239 DCHECK_EQ(monitor_lock_.GetExclusiveOwnerTid(), 0) << " my tid = " << SafeGetTid(self);
Hans Boehmd56f7d12019-11-19 06:03:11 +0000240 lock_count_ = lw.ThinLockCount();
Hans Boehm65c18a22020-01-03 23:37:13 +0000241 monitor_lock_.ExclusiveLockUncontendedFor(owner);
Hans Boehm65c18a22020-01-03 23:37:13 +0000242 DCHECK_EQ(monitor_lock_.GetExclusiveOwnerTid(), owner->GetTid())
243 << " my tid = " << SafeGetTid(self);
244 LockWord fat(this, lw.GCState());
245 // Publish the updated lock word, which may race with other threads.
246 bool success = GetObject()->CasLockWord(lw, fat, CASMode::kWeak, std::memory_order_release);
247 if (success) {
248 if (ATraceEnabled()) {
249 SetLockingMethod(owner);
250 }
251 return true;
252 } else {
Hans Boehm65c18a22020-01-03 23:37:13 +0000253 monitor_lock_.ExclusiveUnlockUncontended();
Hans Boehm65c18a22020-01-03 23:37:13 +0000254 return false;
255 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700256 }
257 case LockWord::kHashCode: {
Orion Hodson88591fe2018-03-06 13:35:43 +0000258 CHECK_EQ(hash_code_.load(std::memory_order_relaxed), static_cast<int32_t>(lw.GetHashCode()));
Hans Boehm65c18a22020-01-03 23:37:13 +0000259 DCHECK_EQ(monitor_lock_.GetExclusiveOwnerTid(), 0) << " my tid = " << SafeGetTid(self);
260 LockWord fat(this, lw.GCState());
261 return GetObject()->CasLockWord(lw, fat, CASMode::kWeak, std::memory_order_release);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700262 }
263 case LockWord::kFatLocked: {
264 // The owner_ is suspended but another thread beat us to install a monitor.
265 return false;
266 }
267 case LockWord::kUnlocked: {
268 LOG(FATAL) << "Inflating unlocked lock word";
Elliott Hughesc1896c92018-11-29 11:33:18 -0800269 UNREACHABLE();
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700270 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700271 default: {
272 LOG(FATAL) << "Invalid monitor state " << lw.GetState();
Elliott Hughesc1896c92018-11-29 11:33:18 -0800273 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700274 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700275 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700276}
277
278Monitor::~Monitor() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700279 // Deflated monitors have a null object.
Elliott Hughes5f791332011-09-15 17:45:30 -0700280}
281
Elliott Hughes5f791332011-09-15 17:45:30 -0700282void Monitor::AppendToWaitSet(Thread* thread) {
Charles Mungerc665d632018-11-06 16:20:13 +0000283 // Not checking that the owner is equal to this thread, since we've released
284 // the monitor by the time this method is called.
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700285 DCHECK(thread != nullptr);
Ian Rogersdd7624d2014-03-14 17:43:00 -0700286 DCHECK(thread->GetWaitNext() == nullptr) << thread->GetWaitNext();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700287 if (wait_set_ == nullptr) {
Elliott Hughes5f791332011-09-15 17:45:30 -0700288 wait_set_ = thread;
289 return;
290 }
291
292 // push_back.
293 Thread* t = wait_set_;
Ian Rogersdd7624d2014-03-14 17:43:00 -0700294 while (t->GetWaitNext() != nullptr) {
295 t = t->GetWaitNext();
Elliott Hughes5f791332011-09-15 17:45:30 -0700296 }
Ian Rogersdd7624d2014-03-14 17:43:00 -0700297 t->SetWaitNext(thread);
Elliott Hughes5f791332011-09-15 17:45:30 -0700298}
299
Elliott Hughes5f791332011-09-15 17:45:30 -0700300void Monitor::RemoveFromWaitSet(Thread *thread) {
301 DCHECK(owner_ == Thread::Current());
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700302 DCHECK(thread != nullptr);
Charles Mungerc665d632018-11-06 16:20:13 +0000303 auto remove = [&](Thread*& set){
304 if (set != nullptr) {
305 if (set == thread) {
306 set = thread->GetWaitNext();
307 thread->SetWaitNext(nullptr);
308 return true;
309 }
310 Thread* t = set;
311 while (t->GetWaitNext() != nullptr) {
312 if (t->GetWaitNext() == thread) {
313 t->SetWaitNext(thread->GetWaitNext());
314 thread->SetWaitNext(nullptr);
315 return true;
316 }
317 t = t->GetWaitNext();
318 }
Roland Levillain9cec9652018-11-06 10:50:20 +0000319 }
Charles Mungerc665d632018-11-06 16:20:13 +0000320 return false;
321 };
322 if (remove(wait_set_)) {
323 return;
Roland Levillain9cec9652018-11-06 10:50:20 +0000324 }
Charles Mungerc665d632018-11-06 16:20:13 +0000325 remove(wake_set_);
Elliott Hughes5f791332011-09-15 17:45:30 -0700326}
327
Vladimir Markof52d92f2019-03-29 12:33:02 +0000328void Monitor::SetObject(ObjPtr<mirror::Object> object) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700329 obj_ = GcRoot<mirror::Object>(object);
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700330}
331
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700332// This function is inlined and just helps to not have the VLOG and ATRACE check at all the
333// potential tracing points.
Vladimir Markof52d92f2019-03-29 12:33:02 +0000334void Monitor::AtraceMonitorLock(Thread* self, ObjPtr<mirror::Object> obj, bool is_wait) {
Orion Hodson119733d2019-01-30 15:14:41 +0000335 if (UNLIKELY(VLOG_IS_ON(systrace_lock_logging) && ATraceEnabled())) {
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700336 AtraceMonitorLockImpl(self, obj, is_wait);
337 }
338}
339
Vladimir Markof52d92f2019-03-29 12:33:02 +0000340void Monitor::AtraceMonitorLockImpl(Thread* self, ObjPtr<mirror::Object> obj, bool is_wait) {
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700341 // Wait() requires a deeper call stack to be useful. Otherwise you'll see "Waiting at
342 // Object.java". Assume that we'll wait a nontrivial amount, so it's OK to do a longer
343 // stack walk than if !is_wait.
Andreas Gampec7d878d2018-11-19 18:42:06 +0000344 const size_t wanted_frame_number = is_wait ? 1U : 0U;
345
346 ArtMethod* method = nullptr;
347 uint32_t dex_pc = 0u;
348
349 size_t current_frame_number = 0u;
350 StackVisitor::WalkStack(
351 // Note: Adapted from CurrentMethodVisitor in thread.cc. We must not resolve here.
352 [&](const art::StackVisitor* stack_visitor) REQUIRES_SHARED(Locks::mutator_lock_) {
353 ArtMethod* m = stack_visitor->GetMethod();
354 if (m == nullptr || m->IsRuntimeMethod()) {
355 // Runtime method, upcall, or resolution issue. Skip.
356 return true;
357 }
358
359 // Is this the requested frame?
360 if (current_frame_number == wanted_frame_number) {
361 method = m;
362 dex_pc = stack_visitor->GetDexPc(false /* abort_on_error*/);
363 return false;
364 }
365
366 // Look for more.
367 current_frame_number++;
368 return true;
369 },
370 self,
371 /* context= */ nullptr,
372 art::StackVisitor::StackWalkKind::kIncludeInlinedFrames);
373
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700374 const char* prefix = is_wait ? "Waiting on " : "Locking ";
375
376 const char* filename;
377 int32_t line_number;
Andreas Gampec7d878d2018-11-19 18:42:06 +0000378 TranslateLocation(method, dex_pc, &filename, &line_number);
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700379
380 // It would be nice to have a stable "ID" for the object here. However, the only stable thing
381 // would be the identity hashcode. But we cannot use IdentityHashcode here: For one, there are
382 // times when it is unsafe to make that call (see stack dumping for an explanation). More
383 // importantly, we would have to give up on thin-locking when adding systrace locks, as the
384 // identity hashcode is stored in the lockword normally (so can't be used with thin-locks).
385 //
386 // Because of thin-locks we also cannot use the monitor id (as there is no monitor). Monitor ids
387 // also do not have to be stable, as the monitor may be deflated.
388 std::string tmp = StringPrintf("%s %d at %s:%d",
389 prefix,
Vladimir Markof52d92f2019-03-29 12:33:02 +0000390 (obj == nullptr ? -1 : static_cast<int32_t>(reinterpret_cast<uintptr_t>(obj.Ptr()))),
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700391 (filename != nullptr ? filename : "null"),
392 line_number);
Orion Hodson119733d2019-01-30 15:14:41 +0000393 ATraceBegin(tmp.c_str());
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700394}
395
396void Monitor::AtraceMonitorUnlock() {
397 if (UNLIKELY(VLOG_IS_ON(systrace_lock_logging))) {
Orion Hodson119733d2019-01-30 15:14:41 +0000398 ATraceEnd();
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700399 }
400}
401
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700402std::string Monitor::PrettyContentionInfo(const std::string& owner_name,
403 pid_t owner_tid,
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700404 ArtMethod* owners_method,
405 uint32_t owners_dex_pc,
406 size_t num_waiters) {
Hiroshi Yamauchi71cd68d2017-01-25 18:28:12 -0800407 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700408 const char* owners_filename;
Goran Jakovljevic49c882b2016-04-19 10:27:21 +0200409 int32_t owners_line_number = 0;
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700410 if (owners_method != nullptr) {
411 TranslateLocation(owners_method, owners_dex_pc, &owners_filename, &owners_line_number);
412 }
413 std::ostringstream oss;
Mathieu Chartier0ffdc9c2016-04-19 13:46:03 -0700414 oss << "monitor contention with owner " << owner_name << " (" << owner_tid << ")";
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700415 if (owners_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700416 oss << " at " << owners_method->PrettyMethod();
Mathieu Chartier36891fe2016-04-28 17:21:08 -0700417 oss << "(" << owners_filename << ":" << owners_line_number << ")";
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -0700418 }
419 oss << " waiters=" << num_waiters;
420 return oss.str();
421}
422
Hans Boehm65c18a22020-01-03 23:37:13 +0000423bool Monitor::TryLock(Thread* self, bool spin) {
424 Thread *owner = owner_.load(std::memory_order_relaxed);
425 if (owner == self) {
Hans Boehmd56f7d12019-11-19 06:03:11 +0000426 lock_count_++;
Hans Boehm65c18a22020-01-03 23:37:13 +0000427 CHECK_NE(lock_count_, 0u); // Abort on overflow.
Hans Boehmd56f7d12019-11-19 06:03:11 +0000428 } else {
Hans Boehm65c18a22020-01-03 23:37:13 +0000429 bool success = spin ? monitor_lock_.ExclusiveTryLockWithSpinning(self)
430 : monitor_lock_.ExclusiveTryLock(self);
431 if (!success) {
432 return false;
433 }
434 DCHECK(owner_.load(std::memory_order_relaxed) == nullptr);
435 owner_.store(self, std::memory_order_relaxed);
436 CHECK_EQ(lock_count_, 0u);
437 if (ATraceEnabled()) {
438 SetLockingMethodNoProxy(self);
439 }
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700440 }
Hans Boehm65c18a22020-01-03 23:37:13 +0000441 DCHECK(monitor_lock_.IsExclusiveHeld(self));
Hans Boehmd56f7d12019-11-19 06:03:11 +0000442 AtraceMonitorLock(self, GetObject(), /* is_wait= */ false);
443 return true;
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -0700444}
445
Alex Light77fee872017-09-05 14:51:49 -0700446template <LockReason reason>
Elliott Hughes5f791332011-09-15 17:45:30 -0700447void Monitor::Lock(Thread* self) {
Alex Light77fee872017-09-05 14:51:49 -0700448 bool called_monitors_callback = false;
Hans Boehm65c18a22020-01-03 23:37:13 +0000449 if (TryLock(self, /*spin=*/ true)) {
450 // TODO: This preserves original behavior. Correct?
451 if (called_monitors_callback) {
452 CHECK(reason == LockReason::kForLock);
453 Runtime::Current()->GetRuntimeCallbacks()->MonitorContendedLocked(this);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700454 }
Hans Boehm65c18a22020-01-03 23:37:13 +0000455 return;
Hans Boehm3d52abe2019-11-19 18:49:50 +0000456 }
Hans Boehm65c18a22020-01-03 23:37:13 +0000457 // Contended; not reentrant. We hold no locks, so tread carefully.
458 const bool log_contention = (lock_profiling_threshold_ != 0);
459 uint64_t wait_start_ms = log_contention ? MilliTime() : 0;
460
461 Thread *orig_owner = nullptr;
462 ArtMethod* owners_method;
463 uint32_t owners_dex_pc;
464
465 // Do this before releasing the mutator lock so that we don't get deflated.
466 size_t num_waiters = num_waiters_.fetch_add(1, std::memory_order_relaxed);
467
468 bool started_trace = false;
469 if (ATraceEnabled() && owner_.load(std::memory_order_relaxed) != nullptr) {
470 // Acquiring thread_list_lock_ ensures that owner doesn't disappear while
471 // we're looking at it.
472 Locks::thread_list_lock_->ExclusiveLock(self);
473 orig_owner = owner_.load(std::memory_order_relaxed);
474 if (orig_owner != nullptr) { // Did the owner_ give the lock up?
475 const uint32_t orig_owner_thread_id = orig_owner->GetThreadId();
476 GetLockOwnerInfo(&owners_method, &owners_dex_pc, orig_owner);
477 std::ostringstream oss;
478 std::string name;
479 orig_owner->GetThreadName(name);
480 oss << PrettyContentionInfo(name,
481 orig_owner_thread_id,
482 owners_method,
483 owners_dex_pc,
484 num_waiters);
485 Locks::thread_list_lock_->ExclusiveUnlock(self);
486 // Add info for contending thread.
487 uint32_t pc;
488 ArtMethod* m = self->GetCurrentMethod(&pc);
489 const char* filename;
490 int32_t line_number;
491 TranslateLocation(m, pc, &filename, &line_number);
492 oss << " blocking from "
493 << ArtMethod::PrettyMethod(m) << "(" << (filename != nullptr ? filename : "null")
494 << ":" << line_number << ")";
495 ATraceBegin(oss.str().c_str());
496 started_trace = true;
497 } else {
498 Locks::thread_list_lock_->ExclusiveUnlock(self);
499 }
500 }
501 if (log_contention) {
502 // Request the current holder to set lock_owner_info.
503 // Do this even if tracing is enabled, so we semi-consistently get the information
504 // corresponding to MonitorExit.
505 // TODO: Consider optionally obtaining a stack trace here via a checkpoint. That would allow
506 // us to see what the other thread is doing while we're waiting.
507 orig_owner = owner_.load(std::memory_order_relaxed);
508 lock_owner_request_.store(orig_owner, std::memory_order_relaxed);
509 }
510 // Call the contended locking cb once and only once. Also only call it if we are locking for
511 // the first time, not during a Wait wakeup.
512 if (reason == LockReason::kForLock && !called_monitors_callback) {
513 called_monitors_callback = true;
514 Runtime::Current()->GetRuntimeCallbacks()->MonitorContendedLocking(this);
515 }
516 self->SetMonitorEnterObject(GetObject().Ptr());
517 {
518 ScopedThreadSuspension tsc(self, kBlocked); // Change to blocked and give up mutator_lock_.
519
520 // Acquire monitor_lock_ without mutator_lock_, expecting to block this time.
521 // We already tried spinning above. The shutdown procedure currently assumes we stop
522 // touching monitors shortly after we suspend, so don't spin again here.
523 monitor_lock_.ExclusiveLock(self);
524
525 if (log_contention && orig_owner != nullptr) {
526 // Woken from contention.
527 uint64_t wait_ms = MilliTime() - wait_start_ms;
528 uint32_t sample_percent;
529 if (wait_ms >= lock_profiling_threshold_) {
530 sample_percent = 100;
531 } else {
532 sample_percent = 100 * wait_ms / lock_profiling_threshold_;
533 }
534 if (sample_percent != 0 && (static_cast<uint32_t>(rand() % 100) < sample_percent)) {
535 // Do this unconditionally for consistency. It's possible another thread
536 // snuck in in the middle, and tracing was enabled. In that case, we may get its
537 // MonitorEnter information. We can live with that.
538 GetLockOwnerInfo(&owners_method, &owners_dex_pc, orig_owner);
539
540 // Reacquire mutator_lock_ for logging.
541 ScopedObjectAccess soa(self);
542
543 const bool should_dump_stacks = stack_dump_lock_profiling_threshold_ > 0 &&
544 wait_ms > stack_dump_lock_profiling_threshold_;
545
546 // Acquire thread-list lock to find thread and keep it from dying until we've got all
547 // the info we need.
548 Locks::thread_list_lock_->ExclusiveLock(self);
549
550 // Is there still a thread at the same address as the original owner?
551 // We tolerate the fact that it may occasionally be the wrong one.
552 if (Runtime::Current()->GetThreadList()->Contains(orig_owner)) {
553 uint32_t original_owner_tid = orig_owner->GetTid(); // System thread id.
554 std::string original_owner_name;
555 orig_owner->GetThreadName(original_owner_name);
556 std::string owner_stack_dump;
557
558 if (should_dump_stacks) {
559 // Very long contention. Dump stacks.
560 struct CollectStackTrace : public Closure {
561 void Run(art::Thread* thread) override
562 REQUIRES_SHARED(art::Locks::mutator_lock_) {
563 thread->DumpJavaStack(oss);
564 }
565
566 std::ostringstream oss;
567 };
568 CollectStackTrace owner_trace;
569 // RequestSynchronousCheckpoint releases the thread_list_lock_ as a part of its
570 // execution.
571 orig_owner->RequestSynchronousCheckpoint(&owner_trace);
572 owner_stack_dump = owner_trace.oss.str();
573 } else {
574 Locks::thread_list_lock_->ExclusiveUnlock(self);
575 }
576
577 // This is all the data we need. We dropped the thread-list lock, it's OK for the
578 // owner to go away now.
579
580 if (should_dump_stacks) {
581 // Give the detailed traces for really long contention.
582 // This must be here (and not above) because we cannot hold the thread-list lock
583 // while running the checkpoint.
584 std::ostringstream self_trace_oss;
585 self->DumpJavaStack(self_trace_oss);
586
587 uint32_t pc;
588 ArtMethod* m = self->GetCurrentMethod(&pc);
589
590 LOG(WARNING) << "Long "
591 << PrettyContentionInfo(original_owner_name,
592 original_owner_tid,
593 owners_method,
594 owners_dex_pc,
595 num_waiters)
596 << " in " << ArtMethod::PrettyMethod(m) << " for "
597 << PrettyDuration(MsToNs(wait_ms)) << "\n"
598 << "Current owner stack:\n" << owner_stack_dump
599 << "Contender stack:\n" << self_trace_oss.str();
600 } else if (wait_ms > kLongWaitMs && owners_method != nullptr) {
601 uint32_t pc;
602 ArtMethod* m = self->GetCurrentMethod(&pc);
603 // TODO: We should maybe check that original_owner is still a live thread.
604 LOG(WARNING) << "Long "
605 << PrettyContentionInfo(original_owner_name,
606 original_owner_tid,
607 owners_method,
608 owners_dex_pc,
609 num_waiters)
610 << " in " << ArtMethod::PrettyMethod(m) << " for "
611 << PrettyDuration(MsToNs(wait_ms));
612 }
613 LogContentionEvent(self,
614 wait_ms,
615 sample_percent,
616 owners_method,
617 owners_dex_pc);
618 } else {
619 Locks::thread_list_lock_->ExclusiveUnlock(self);
620 }
621 }
622 }
623 }
624 // We've successfully acquired monitor_lock_, released thread_list_lock, and are runnable.
625
626 // We avoided touching monitor fields while suspended, so set owner_ here.
627 owner_.store(self, std::memory_order_relaxed);
628 DCHECK_EQ(lock_count_, 0u);
629
630 if (ATraceEnabled()) {
631 SetLockingMethodNoProxy(self);
632 }
633 if (started_trace) {
634 ATraceEnd();
635 }
636 self->SetMonitorEnterObject(nullptr);
637 num_waiters_.fetch_sub(1, std::memory_order_relaxed);
638 DCHECK(monitor_lock_.IsExclusiveHeld(self));
Alex Light77fee872017-09-05 14:51:49 -0700639 // We need to pair this with a single contended locking call. NB we match the RI behavior and call
640 // this even if MonitorEnter failed.
641 if (called_monitors_callback) {
642 CHECK(reason == LockReason::kForLock);
643 Runtime::Current()->GetRuntimeCallbacks()->MonitorContendedLocked(this);
644 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700645}
646
Alex Light77fee872017-09-05 14:51:49 -0700647template void Monitor::Lock<LockReason::kForLock>(Thread* self);
648template void Monitor::Lock<LockReason::kForWait>(Thread* self);
649
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800650static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
651 __attribute__((format(printf, 1, 2)));
652
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700653static void ThrowIllegalMonitorStateExceptionF(const char* fmt, ...)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700654 REQUIRES_SHARED(Locks::mutator_lock_) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800655 va_list args;
656 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -0800657 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000658 self->ThrowNewExceptionV("Ljava/lang/IllegalMonitorStateException;", fmt, args);
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700659 if (!Runtime::Current()->IsStarted() || VLOG_IS_ON(monitor)) {
Brian Carlstrom64277f32012-03-26 23:53:34 -0700660 std::ostringstream ss;
Ian Rogers62d6c772013-02-27 08:32:07 -0800661 self->Dump(ss);
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700662 LOG(Runtime::Current()->IsStarted() ? ::android::base::INFO : ::android::base::ERROR)
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000663 << self->GetException()->Dump() << "\n" << ss.str();
Brian Carlstrom64277f32012-03-26 23:53:34 -0700664 }
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800665 va_end(args);
666}
667
Elliott Hughesd4237412012-02-21 11:24:45 -0800668static std::string ThreadToString(Thread* thread) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700669 if (thread == nullptr) {
670 return "nullptr";
Elliott Hughesd4237412012-02-21 11:24:45 -0800671 }
672 std::ostringstream oss;
673 // TODO: alternatively, we could just return the thread's name.
674 oss << *thread;
675 return oss.str();
676}
677
Vladimir Markof52d92f2019-03-29 12:33:02 +0000678void Monitor::FailedUnlock(ObjPtr<mirror::Object> o,
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700679 uint32_t expected_owner_thread_id,
680 uint32_t found_owner_thread_id,
Elliott Hughesffb465f2012-03-01 18:46:05 -0800681 Monitor* monitor) {
Elliott Hughesffb465f2012-03-01 18:46:05 -0800682 std::string current_owner_string;
683 std::string expected_owner_string;
684 std::string found_owner_string;
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700685 uint32_t current_owner_thread_id = 0u;
Elliott Hughesffb465f2012-03-01 18:46:05 -0800686 {
Ian Rogers50b35e22012-10-04 10:09:15 -0700687 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700688 ThreadList* const thread_list = Runtime::Current()->GetThreadList();
689 Thread* expected_owner = thread_list->FindThreadByThreadId(expected_owner_thread_id);
690 Thread* found_owner = thread_list->FindThreadByThreadId(found_owner_thread_id);
691
Elliott Hughesffb465f2012-03-01 18:46:05 -0800692 // Re-read owner now that we hold lock.
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700693 Thread* current_owner = (monitor != nullptr) ? monitor->GetOwner() : nullptr;
694 if (current_owner != nullptr) {
695 current_owner_thread_id = current_owner->GetThreadId();
696 }
Elliott Hughesffb465f2012-03-01 18:46:05 -0800697 // Get short descriptions of the threads involved.
698 current_owner_string = ThreadToString(current_owner);
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700699 expected_owner_string = expected_owner != nullptr ? ThreadToString(expected_owner) : "unnamed";
700 found_owner_string = found_owner != nullptr ? ThreadToString(found_owner) : "unnamed";
Elliott Hughesffb465f2012-03-01 18:46:05 -0800701 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700702
703 if (current_owner_thread_id == 0u) {
704 if (found_owner_thread_id == 0u) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800705 ThrowIllegalMonitorStateExceptionF("unlock of unowned monitor on object of type '%s'"
706 " on thread '%s'",
David Sehr709b0702016-10-13 09:12:37 -0700707 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800708 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800709 } else {
710 // Race: the original read found an owner but now there is none
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800711 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
712 " (where now the monitor appears unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800713 found_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700714 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800715 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800716 }
717 } else {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700718 if (found_owner_thread_id == 0u) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800719 // Race: originally there was no owner, there is now
720 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
721 " (originally believed to be unowned) on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800722 current_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700723 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800724 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800725 } else {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700726 if (found_owner_thread_id != current_owner_thread_id) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800727 // Race: originally found and current owner have changed
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800728 ThrowIllegalMonitorStateExceptionF("unlock of monitor originally owned by '%s' (now"
729 " owned by '%s') on object of type '%s' on thread '%s'",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800730 found_owner_string.c_str(),
731 current_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700732 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800733 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800734 } else {
735 ThrowIllegalMonitorStateExceptionF("unlock of monitor owned by '%s' on object of type '%s'"
736 " on thread '%s",
Elliott Hughesffb465f2012-03-01 18:46:05 -0800737 current_owner_string.c_str(),
David Sehr709b0702016-10-13 09:12:37 -0700738 mirror::Object::PrettyTypeOf(o).c_str(),
Elliott Hughesffb465f2012-03-01 18:46:05 -0800739 expected_owner_string.c_str());
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800740 }
741 }
742 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700743}
744
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700745bool Monitor::Unlock(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700746 DCHECK(self != nullptr);
Hans Boehm65c18a22020-01-03 23:37:13 +0000747 Thread* owner = owner_.load(std::memory_order_relaxed);
Hans Boehmd56f7d12019-11-19 06:03:11 +0000748 if (owner == self) {
749 // We own the monitor, so nobody else can be in here.
Hans Boehm65c18a22020-01-03 23:37:13 +0000750 CheckLockOwnerRequest(self);
Hans Boehmd56f7d12019-11-19 06:03:11 +0000751 AtraceMonitorUnlock();
752 if (lock_count_ == 0) {
Hans Boehm65c18a22020-01-03 23:37:13 +0000753 owner_.store(nullptr, std::memory_order_relaxed);
754 SignalWaiterAndReleaseMonitorLock(self);
Hans Boehmd56f7d12019-11-19 06:03:11 +0000755 } else {
756 --lock_count_;
Hans Boehm65c18a22020-01-03 23:37:13 +0000757 DCHECK(monitor_lock_.IsExclusiveHeld(self));
758 DCHECK_EQ(owner_.load(std::memory_order_relaxed), self);
759 // Keep monitor_lock_, but pretend we released it.
760 FakeUnlockMonitorLock();
Hans Boehmd56f7d12019-11-19 06:03:11 +0000761 }
Hans Boehm65c18a22020-01-03 23:37:13 +0000762 return true;
Hans Boehmd56f7d12019-11-19 06:03:11 +0000763 }
764 // We don't own this, so we're not allowed to unlock it.
765 // The JNI spec says that we should throw IllegalMonitorStateException in this case.
Hans Boehm65c18a22020-01-03 23:37:13 +0000766 uint32_t owner_thread_id = 0u;
767 {
768 MutexLock mu(self, *Locks::thread_list_lock_);
769 owner = owner_.load(std::memory_order_relaxed);
770 if (owner != nullptr) {
771 owner_thread_id = owner->GetThreadId();
772 }
773 }
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700774 FailedUnlock(GetObject(), self->GetThreadId(), owner_thread_id, this);
Hans Boehm65c18a22020-01-03 23:37:13 +0000775 // Pretend to release monitor_lock_, which we should not.
776 FakeUnlockMonitorLock();
Mathieu Chartier61b3cd42016-04-18 11:43:29 -0700777 return false;
Elliott Hughes5f791332011-09-15 17:45:30 -0700778}
779
Hans Boehm65c18a22020-01-03 23:37:13 +0000780void Monitor::SignalWaiterAndReleaseMonitorLock(Thread* self) {
781 // We want to release the monitor and signal up to one thread that was waiting
782 // but has since been notified.
783 DCHECK_EQ(lock_count_, 0u);
784 DCHECK(monitor_lock_.IsExclusiveHeld(self));
Charles Mungerc665d632018-11-06 16:20:13 +0000785 while (wake_set_ != nullptr) {
786 // No risk of waking ourselves here; since monitor_lock_ is not released until we're ready to
787 // return, notify can't move the current thread from wait_set_ to wake_set_ until this
788 // method is done checking wake_set_.
789 Thread* thread = wake_set_;
790 wake_set_ = thread->GetWaitNext();
791 thread->SetWaitNext(nullptr);
Hans Boehm65c18a22020-01-03 23:37:13 +0000792 DCHECK(owner_.load(std::memory_order_relaxed) == nullptr);
Charles Mungerc665d632018-11-06 16:20:13 +0000793
794 // Check to see if the thread is still waiting.
795 {
796 // In the case of wait(), we'll be acquiring another thread's GetWaitMutex with
797 // self's GetWaitMutex held. This does not risk deadlock, because we only acquire this lock
798 // for threads in the wake_set_. A thread can only enter wake_set_ from Notify or NotifyAll,
799 // and those hold monitor_lock_. Thus, the threads whose wait mutexes we acquire here must
800 // have already been released from wait(), since we have not released monitor_lock_ until
801 // after we've chosen our thread to wake, so there is no risk of the following lock ordering
802 // leading to deadlock:
803 // Thread 1 waits
804 // Thread 2 waits
805 // Thread 3 moves threads 1 and 2 from wait_set_ to wake_set_
806 // Thread 1 enters this block, and attempts to acquire Thread 2's GetWaitMutex to wake it
807 // Thread 2 enters this block, and attempts to acquire Thread 1's GetWaitMutex to wake it
808 //
809 // Since monitor_lock_ is not released until the thread-to-be-woken-up's GetWaitMutex is
810 // acquired, two threads cannot attempt to acquire each other's GetWaitMutex while holding
811 // their own and cause deadlock.
812 MutexLock wait_mu(self, *thread->GetWaitMutex());
813 if (thread->GetWaitMonitor() != nullptr) {
814 // Release the lock, so that a potentially awakened thread will not
815 // immediately contend on it. The lock ordering here is:
816 // monitor_lock_, self->GetWaitMutex, thread->GetWaitMutex
Hans Boehm65c18a22020-01-03 23:37:13 +0000817 monitor_lock_.Unlock(self); // Releases contenders.
Charles Mungerc665d632018-11-06 16:20:13 +0000818 thread->GetWaitConditionVariable()->Signal(self);
819 return;
820 }
821 }
822 }
Charles Mungerc665d632018-11-06 16:20:13 +0000823 monitor_lock_.Unlock(self);
Hans Boehm65c18a22020-01-03 23:37:13 +0000824 DCHECK(!monitor_lock_.IsExclusiveHeld(self));
Charles Mungerc665d632018-11-06 16:20:13 +0000825}
826
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800827void Monitor::Wait(Thread* self, int64_t ms, int32_t ns,
828 bool interruptShouldThrow, ThreadState why) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700829 DCHECK(self != nullptr);
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800830 DCHECK(why == kTimedWaiting || why == kWaiting || why == kSleeping);
Elliott Hughes5f791332011-09-15 17:45:30 -0700831
832 // Make sure that we hold the lock.
Hans Boehm65c18a22020-01-03 23:37:13 +0000833 if (owner_.load(std::memory_order_relaxed) != self) {
Elena Sayapina1af6a1f2014-06-20 16:58:37 +0700834 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700835 return;
836 }
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800837
Elliott Hughesdf42c482013-01-09 12:49:02 -0800838 // We need to turn a zero-length timed wait into a regular wait because
839 // Object.wait(0, 0) is defined as Object.wait(0), which is defined as Object.wait().
840 if (why == kTimedWaiting && (ms == 0 && ns == 0)) {
841 why = kWaiting;
842 }
843
Elliott Hughes5f791332011-09-15 17:45:30 -0700844 // Enforce the timeout range.
845 if (ms < 0 || ns < 0 || ns > 999999) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000846 self->ThrowNewExceptionF("Ljava/lang/IllegalArgumentException;",
Ian Rogersef7d42f2014-01-06 12:55:46 -0800847 "timeout arguments out of range: ms=%" PRId64 " ns=%d", ms, ns);
Elliott Hughes5f791332011-09-15 17:45:30 -0700848 return;
849 }
850
Hans Boehm65c18a22020-01-03 23:37:13 +0000851 CheckLockOwnerRequest(self);
852
Elliott Hughes5f791332011-09-15 17:45:30 -0700853 /*
Charles Mungerc665d632018-11-06 16:20:13 +0000854 * Release our hold - we need to let it go even if we're a few levels
Elliott Hughes5f791332011-09-15 17:45:30 -0700855 * deep in a recursive lock, and we need to restore that later.
Elliott Hughes5f791332011-09-15 17:45:30 -0700856 */
Hans Boehm65c18a22020-01-03 23:37:13 +0000857 unsigned int prev_lock_count = lock_count_;
Hans Boehmd56f7d12019-11-19 06:03:11 +0000858 lock_count_ = 0;
Elliott Hughes5f791332011-09-15 17:45:30 -0700859
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700860 AtraceMonitorUnlock(); // For the implict Unlock() just above. This will only end the deepest
861 // nesting, but that is enough for the visualization, and corresponds to
862 // the single Lock() we do afterwards.
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700863 AtraceMonitorLock(self, GetObject(), /* is_wait= */ true);
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700864
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800865 bool was_interrupted = false;
Alex Light77fee872017-09-05 14:51:49 -0700866 bool timed_out = false;
Hans Boehm65c18a22020-01-03 23:37:13 +0000867 // Update monitor state now; it's not safe once we're "suspended".
868 owner_.store(nullptr, std::memory_order_relaxed);
869 num_waiters_.fetch_add(1, std::memory_order_relaxed);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700870 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700871 // Update thread state. If the GC wakes up, it'll ignore us, knowing
872 // that we won't touch any references in this state, and we'll check
873 // our suspend mode before we transition out.
874 ScopedThreadSuspension sts(self, why);
875
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700876 // Pseudo-atomically wait on self's wait_cond_ and release the monitor lock.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700877 MutexLock mu(self, *self->GetWaitMutex());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700878
Charles Mungerc665d632018-11-06 16:20:13 +0000879 /*
880 * Add ourselves to the set of threads waiting on this monitor.
881 * It's important that we are only added to the wait set after
882 * acquiring our GetWaitMutex, so that calls to Notify() that occur after we
883 * have released monitor_lock_ will not move us from wait_set_ to wake_set_
884 * until we've signalled contenders on this monitor.
885 */
886 AppendToWaitSet(self);
Charles Mungerc665d632018-11-06 16:20:13 +0000887
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700888 // Set wait_monitor_ to the monitor object we will be waiting on. When wait_monitor_ is
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700889 // non-null a notifying or interrupting thread must signal the thread's wait_cond_ to wake it
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700890 // up.
Ian Rogersdd7624d2014-03-14 17:43:00 -0700891 DCHECK(self->GetWaitMonitor() == nullptr);
892 self->SetWaitMonitor(this);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700893
894 // Release the monitor lock.
Hans Boehm65c18a22020-01-03 23:37:13 +0000895 DCHECK(monitor_lock_.IsExclusiveHeld(self));
896 SignalWaiterAndReleaseMonitorLock(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700897
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800898 // Handle the case where the thread was interrupted before we called wait().
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000899 if (self->IsInterrupted()) {
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800900 was_interrupted = true;
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700901 } else {
902 // Wait for a notification or a timeout to occur.
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800903 if (why == kWaiting) {
Ian Rogersdd7624d2014-03-14 17:43:00 -0700904 self->GetWaitConditionVariable()->Wait(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700905 } else {
Elliott Hughes4cd121e2013-01-07 17:35:41 -0800906 DCHECK(why == kTimedWaiting || why == kSleeping) << why;
Alex Light77fee872017-09-05 14:51:49 -0700907 timed_out = self->GetWaitConditionVariable()->TimedWait(self, ms, ns);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700908 }
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000909 was_interrupted = self->IsInterrupted();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700910 }
Elliott Hughes5f791332011-09-15 17:45:30 -0700911 }
912
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800913 {
914 // We reset the thread's wait_monitor_ field after transitioning back to runnable so
915 // that a thread in a waiting/sleeping state has a non-null wait_monitor_ for debugging
916 // and diagnostic purposes. (If you reset this earlier, stack dumps will claim that threads
917 // are waiting on "null".)
Ian Rogersdd7624d2014-03-14 17:43:00 -0700918 MutexLock mu(self, *self->GetWaitMutex());
919 DCHECK(self->GetWaitMonitor() != nullptr);
920 self->SetWaitMonitor(nullptr);
Elliott Hughesb4e94fd2013-01-08 14:41:26 -0800921 }
922
Mathieu Chartierdaed5d82016-03-10 10:49:35 -0800923 // Allocate the interrupted exception not holding the monitor lock since it may cause a GC.
924 // If the GC requires acquiring the monitor for enqueuing cleared references, this would
925 // cause a deadlock if the monitor is held.
926 if (was_interrupted && interruptShouldThrow) {
927 /*
928 * We were interrupted while waiting, or somebody interrupted an
929 * un-interruptible thread earlier and we're bailing out immediately.
930 *
931 * The doc sayeth: "The interrupted status of the current thread is
932 * cleared when this exception is thrown."
933 */
Nicolas Geoffray365719c2017-03-08 13:11:50 +0000934 self->SetInterrupted(false);
Mathieu Chartierdaed5d82016-03-10 10:49:35 -0800935 self->ThrowNewException("Ljava/lang/InterruptedException;", nullptr);
936 }
937
Andreas Gampec7ed09b2016-04-25 20:08:55 -0700938 AtraceMonitorUnlock(); // End Wait().
939
Alex Light77fee872017-09-05 14:51:49 -0700940 // We just slept, tell the runtime callbacks about this.
941 Runtime::Current()->GetRuntimeCallbacks()->MonitorWaitFinished(this, timed_out);
942
Ian Rogersd9c4fc92013-10-01 19:45:43 -0700943 // Re-acquire the monitor and lock.
Alex Light77fee872017-09-05 14:51:49 -0700944 Lock<LockReason::kForWait>(self);
Hans Boehm65c18a22020-01-03 23:37:13 +0000945 lock_count_ = prev_lock_count;
946 DCHECK(monitor_lock_.IsExclusiveHeld(self));
Ian Rogersdd7624d2014-03-14 17:43:00 -0700947 self->GetWaitMutex()->AssertNotHeld(self);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700948
Hans Boehm65c18a22020-01-03 23:37:13 +0000949 num_waiters_.fetch_sub(1, std::memory_order_relaxed);
Elliott Hughes5f791332011-09-15 17:45:30 -0700950 RemoveFromWaitSet(self);
Elliott Hughes5f791332011-09-15 17:45:30 -0700951}
952
953void Monitor::Notify(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700954 DCHECK(self != nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700955 // Make sure that we hold the lock.
Hans Boehm65c18a22020-01-03 23:37:13 +0000956 if (owner_.load(std::memory_order_relaxed) != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800957 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700958 return;
959 }
Charles Mungerc665d632018-11-06 16:20:13 +0000960 // Move one thread from waiters to wake set
961 Thread* to_move = wait_set_;
962 if (to_move != nullptr) {
963 wait_set_ = to_move->GetWaitNext();
964 to_move->SetWaitNext(wake_set_);
965 wake_set_ = to_move;
Elliott Hughes5f791332011-09-15 17:45:30 -0700966 }
967}
968
969void Monitor::NotifyAll(Thread* self) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700970 DCHECK(self != nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -0700971 // Make sure that we hold the lock.
Hans Boehm65c18a22020-01-03 23:37:13 +0000972 if (owner_.load(std::memory_order_relaxed) != self) {
Ian Rogers6d0b13e2012-02-07 09:25:29 -0800973 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notifyAll()");
Elliott Hughes5f791332011-09-15 17:45:30 -0700974 return;
975 }
Charles Mungerc665d632018-11-06 16:20:13 +0000976
977 // Move all threads from waiters to wake set
978 Thread* to_move = wait_set_;
979 if (to_move != nullptr) {
980 wait_set_ = nullptr;
981 Thread* move_to = wake_set_;
982 if (move_to == nullptr) {
983 wake_set_ = to_move;
984 return;
985 }
986 while (move_to->GetWaitNext() != nullptr) {
987 move_to = move_to->GetWaitNext();
988 }
989 move_to->SetWaitNext(to_move);
Elliott Hughes5f791332011-09-15 17:45:30 -0700990 }
991}
992
Vladimir Markof52d92f2019-03-29 12:33:02 +0000993bool Monitor::Deflate(Thread* self, ObjPtr<mirror::Object> obj) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700994 DCHECK(obj != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700995 // Don't need volatile since we only deflate with mutators suspended.
996 LockWord lw(obj->GetLockWord(false));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700997 // If the lock isn't an inflated monitor, then we don't need to deflate anything.
998 if (lw.GetState() == LockWord::kFatLocked) {
999 Monitor* monitor = lw.FatLockMonitor();
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001000 DCHECK(monitor != nullptr);
Hans Boehm65c18a22020-01-03 23:37:13 +00001001 // Can't deflate if we have anybody waiting on the CV or trying to acquire the monitor.
1002 if (monitor->num_waiters_.load(std::memory_order_relaxed) > 0) {
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001003 return false;
1004 }
Hans Boehm65c18a22020-01-03 23:37:13 +00001005 if (!monitor->monitor_lock_.ExclusiveTryLock(self)) {
1006 // We cannot deflate a monitor that's currently held. It's unclear whether we should if
1007 // we could.
1008 return false;
1009 }
1010 DCHECK_EQ(monitor->lock_count_, 0u);
1011 DCHECK_EQ(monitor->owner_.load(std::memory_order_relaxed), static_cast<Thread*>(nullptr));
1012 if (monitor->HasHashCode()) {
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001013 LockWord new_lw = LockWord::FromHashCode(monitor->GetHashCode(), lw.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001014 // Assume no concurrent read barrier state changes as mutators are suspended.
1015 obj->SetLockWord(new_lw, false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001016 VLOG(monitor) << "Deflated " << obj << " to hash monitor " << monitor->GetHashCode();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001017 } else {
1018 // No lock and no hash, just put an empty lock word inside the object.
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001019 LockWord new_lw = LockWord::FromDefault(lw.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001020 // Assume no concurrent read barrier state changes as mutators are suspended.
1021 obj->SetLockWord(new_lw, false);
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001022 VLOG(monitor) << "Deflated" << obj << " to empty lock word";
Mathieu Chartier590fee92013-09-13 13:46:47 -07001023 }
Hans Boehm65c18a22020-01-03 23:37:13 +00001024 monitor->monitor_lock_.ExclusiveUnlock(self);
1025 DCHECK(!(monitor->monitor_lock_.IsExclusiveHeld(self)));
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001026 // 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 -07001027 // next GC.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001028 monitor->obj_ = GcRoot<mirror::Object>(nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001029 }
1030 return true;
1031}
1032
Vladimir Markof52d92f2019-03-29 12:33:02 +00001033void Monitor::Inflate(Thread* self, Thread* owner, ObjPtr<mirror::Object> obj, int32_t hash_code) {
Andreas Gampe74240812014-04-17 10:35:09 -07001034 DCHECK(self != nullptr);
1035 DCHECK(obj != nullptr);
Elliott Hughes5f791332011-09-15 17:45:30 -07001036 // Allocate and acquire a new monitor.
Andreas Gampe74240812014-04-17 10:35:09 -07001037 Monitor* m = MonitorPool::CreateMonitor(self, owner, obj, hash_code);
1038 DCHECK(m != nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001039 if (m->Install(self)) {
Haifeng Li86ab7912014-05-16 10:47:59 +08001040 if (owner != nullptr) {
1041 VLOG(monitor) << "monitor: thread" << owner->GetThreadId()
Andreas Gampe74240812014-04-17 10:35:09 -07001042 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +08001043 } else {
1044 VLOG(monitor) << "monitor: Inflate with hashcode " << hash_code
Andreas Gampe74240812014-04-17 10:35:09 -07001045 << " created monitor " << m << " for object " << obj;
Haifeng Li86ab7912014-05-16 10:47:59 +08001046 }
Andreas Gampe74240812014-04-17 10:35:09 -07001047 Runtime::Current()->GetMonitorList()->Add(m);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001048 CHECK_EQ(obj->GetLockWord(true).GetState(), LockWord::kFatLocked);
Andreas Gampe74240812014-04-17 10:35:09 -07001049 } else {
1050 MonitorPool::ReleaseMonitor(self, m);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001051 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001052}
1053
Mathieu Chartier0cd81352014-05-22 16:48:55 -07001054void Monitor::InflateThinLocked(Thread* self, Handle<mirror::Object> obj, LockWord lock_word,
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001055 uint32_t hash_code) {
1056 DCHECK_EQ(lock_word.GetState(), LockWord::kThinLocked);
1057 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1058 if (owner_thread_id == self->GetThreadId()) {
1059 // We own the monitor, we can easily inflate it.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001060 Inflate(self, self, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001061 } else {
1062 ThreadList* thread_list = Runtime::Current()->GetThreadList();
1063 // Suspend the owner, inflate. First change to blocked and give up mutator_lock_.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001064 self->SetMonitorEnterObject(obj.Get());
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -07001065 bool timed_out;
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07001066 Thread* owner;
1067 {
Alex Light77fee872017-09-05 14:51:49 -07001068 ScopedThreadSuspension sts(self, kWaitingForLockInflation);
Alex Light46f93402017-06-29 11:59:50 -07001069 owner = thread_list->SuspendThreadByThreadId(owner_thread_id,
1070 SuspendReason::kInternal,
1071 &timed_out);
Mathieu Chartierf1d666e2015-09-03 16:13:34 -07001072 }
Mathieu Chartiera1ee14f2014-05-14 16:51:03 -07001073 if (owner != nullptr) {
1074 // We succeeded in suspending the thread, check the lock's status didn't change.
1075 lock_word = obj->GetLockWord(true);
1076 if (lock_word.GetState() == LockWord::kThinLocked &&
1077 lock_word.ThinLockOwner() == owner_thread_id) {
1078 // Go ahead and inflate the lock.
1079 Inflate(self, owner, obj.Get(), hash_code);
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001080 }
Alex Light88fd7202017-06-30 08:31:59 -07001081 bool resumed = thread_list->Resume(owner, SuspendReason::kInternal);
1082 DCHECK(resumed);
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001083 }
Ian Rogersdd7624d2014-03-14 17:43:00 -07001084 self->SetMonitorEnterObject(nullptr);
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001085 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001086}
1087
Ian Rogers719d1a32014-03-06 12:13:39 -08001088// Fool annotalysis into thinking that the lock on obj is acquired.
Vladimir Markof52d92f2019-03-29 12:33:02 +00001089static ObjPtr<mirror::Object> FakeLock(ObjPtr<mirror::Object> obj)
1090 EXCLUSIVE_LOCK_FUNCTION(obj.Ptr()) NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers719d1a32014-03-06 12:13:39 -08001091 return obj;
1092}
1093
1094// Fool annotalysis into thinking that the lock on obj is release.
Vladimir Markof52d92f2019-03-29 12:33:02 +00001095static ObjPtr<mirror::Object> FakeUnlock(ObjPtr<mirror::Object> obj)
1096 UNLOCK_FUNCTION(obj.Ptr()) NO_THREAD_SAFETY_ANALYSIS {
Ian Rogers719d1a32014-03-06 12:13:39 -08001097 return obj;
1098}
1099
Vladimir Markof52d92f2019-03-29 12:33:02 +00001100ObjPtr<mirror::Object> Monitor::MonitorEnter(Thread* self,
1101 ObjPtr<mirror::Object> obj,
1102 bool trylock) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001103 DCHECK(self != nullptr);
1104 DCHECK(obj != nullptr);
Mathieu Chartier2d096c92015-10-12 16:18:20 -07001105 self->AssertThreadSuspensionIsAllowable();
Ian Rogers719d1a32014-03-06 12:13:39 -08001106 obj = FakeLock(obj);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001107 uint32_t thread_id = self->GetThreadId();
1108 size_t contention_count = 0;
Hans Boehmeedca4a2020-02-21 14:09:57 -08001109 constexpr size_t kExtraSpinIters = 100;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001110 StackHandleScope<1> hs(self);
1111 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001112 while (true) {
Hans Boehmb3da36c2016-12-15 13:12:59 -08001113 // We initially read the lockword with ordinary Java/relaxed semantics. When stronger
1114 // semantics are needed, we address it below. Since GetLockWord bottoms out to a relaxed load,
1115 // we can fix it later, in an infrequently executed case, with a fence.
1116 LockWord lock_word = h_obj->GetLockWord(false);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001117 switch (lock_word.GetState()) {
1118 case LockWord::kUnlocked: {
Hans Boehmb3da36c2016-12-15 13:12:59 -08001119 // No ordering required for preceding lockword read, since we retest.
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001120 LockWord thin_locked(LockWord::FromThinLockId(thread_id, 0, lock_word.GCState()));
Mathieu Chartier42c2e502018-06-19 12:30:56 -07001121 if (h_obj->CasLockWord(lock_word, thin_locked, CASMode::kWeak, std::memory_order_acquire)) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001122 AtraceMonitorLock(self, h_obj.Get(), /* is_wait= */ false);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001123 return h_obj.Get(); // Success!
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001124 }
1125 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -07001126 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001127 case LockWord::kThinLocked: {
1128 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1129 if (owner_thread_id == thread_id) {
Hans Boehmb3da36c2016-12-15 13:12:59 -08001130 // No ordering required for initial lockword read.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001131 // We own the lock, increase the recursion count.
1132 uint32_t new_count = lock_word.ThinLockCount() + 1;
1133 if (LIKELY(new_count <= LockWord::kThinLockMaxCount)) {
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001134 LockWord thin_locked(LockWord::FromThinLockId(thread_id,
1135 new_count,
1136 lock_word.GCState()));
Hans Boehmb3da36c2016-12-15 13:12:59 -08001137 // Only this thread pays attention to the count. Thus there is no need for stronger
1138 // than relaxed memory ordering.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001139 if (!kUseReadBarrier) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001140 h_obj->SetLockWord(thin_locked, /* as_volatile= */ false);
1141 AtraceMonitorLock(self, h_obj.Get(), /* is_wait= */ false);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001142 return h_obj.Get(); // Success!
1143 } else {
1144 // Use CAS to preserve the read barrier state.
Mathieu Chartier42c2e502018-06-19 12:30:56 -07001145 if (h_obj->CasLockWord(lock_word,
1146 thin_locked,
1147 CASMode::kWeak,
1148 std::memory_order_relaxed)) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -07001149 AtraceMonitorLock(self, h_obj.Get(), /* is_wait= */ false);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001150 return h_obj.Get(); // Success!
1151 }
1152 }
1153 continue; // Go again.
Elliott Hughes5f791332011-09-15 17:45:30 -07001154 } else {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001155 // We'd overflow the recursion count, so inflate the monitor.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001156 InflateThinLocked(self, h_obj, lock_word, 0);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001157 }
1158 } else {
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07001159 if (trylock) {
1160 return nullptr;
1161 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001162 // Contention.
1163 contention_count++;
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001164 Runtime* runtime = Runtime::Current();
Hans Boehmeedca4a2020-02-21 14:09:57 -08001165 if (contention_count
1166 <= kExtraSpinIters + runtime->GetMaxSpinsBeforeThinLockInflation()) {
Alex Light77fee872017-09-05 14:51:49 -07001167 // TODO: Consider switching the thread state to kWaitingForLockInflation when we are
1168 // yielding. Use sched_yield instead of NanoSleep since NanoSleep can wait much longer
1169 // than the parameter you pass in. This can cause thread suspension to take excessively
1170 // long and make long pauses. See b/16307460.
Hans Boehmeedca4a2020-02-21 14:09:57 -08001171 if (contention_count > kExtraSpinIters) {
1172 sched_yield();
1173 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001174 } else {
1175 contention_count = 0;
Hans Boehmb3da36c2016-12-15 13:12:59 -08001176 // No ordering required for initial lockword read. Install rereads it anyway.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001177 InflateThinLocked(self, h_obj, lock_word, 0);
Elliott Hughes5f791332011-09-15 17:45:30 -07001178 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001179 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001180 continue; // Start from the beginning.
Elliott Hughes5f791332011-09-15 17:45:30 -07001181 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001182 case LockWord::kFatLocked: {
Hans Boehmb3da36c2016-12-15 13:12:59 -08001183 // We should have done an acquire read of the lockword initially, to ensure
1184 // visibility of the monitor data structure. Use an explicit fence instead.
Orion Hodson27b96762018-03-13 16:06:57 +00001185 std::atomic_thread_fence(std::memory_order_acquire);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001186 Monitor* mon = lock_word.FatLockMonitor();
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07001187 if (trylock) {
1188 return mon->TryLock(self) ? h_obj.Get() : nullptr;
1189 } else {
1190 mon->Lock(self);
Hans Boehm65c18a22020-01-03 23:37:13 +00001191 DCHECK(mon->monitor_lock_.IsExclusiveHeld(self));
Mathieu Chartier4b0ef1c2016-07-29 16:26:01 -07001192 return h_obj.Get(); // Success!
1193 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001194 }
Ian Rogers719d1a32014-03-06 12:13:39 -08001195 case LockWord::kHashCode:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001196 // Inflate with the existing hashcode.
Hans Boehmb3da36c2016-12-15 13:12:59 -08001197 // Again no ordering required for initial lockword read, since we don't rely
1198 // on the visibility of any prior computation.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001199 Inflate(self, nullptr, h_obj.Get(), lock_word.GetHashCode());
Ian Rogers719d1a32014-03-06 12:13:39 -08001200 continue; // Start from the beginning.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001201 default: {
1202 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Andreas Gampec7ed09b2016-04-25 20:08:55 -07001203 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001204 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001205 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001206 }
1207}
1208
Vladimir Markof52d92f2019-03-29 12:33:02 +00001209bool Monitor::MonitorExit(Thread* self, ObjPtr<mirror::Object> obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001210 DCHECK(self != nullptr);
1211 DCHECK(obj != nullptr);
Mathieu Chartier2d096c92015-10-12 16:18:20 -07001212 self->AssertThreadSuspensionIsAllowable();
Ian Rogers719d1a32014-03-06 12:13:39 -08001213 obj = FakeUnlock(obj);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001214 StackHandleScope<1> hs(self);
1215 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001216 while (true) {
1217 LockWord lock_word = obj->GetLockWord(true);
1218 switch (lock_word.GetState()) {
1219 case LockWord::kHashCode:
1220 // Fall-through.
1221 case LockWord::kUnlocked:
Mathieu Chartier61b3cd42016-04-18 11:43:29 -07001222 FailedUnlock(h_obj.Get(), self->GetThreadId(), 0u, nullptr);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001223 return false; // Failure.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001224 case LockWord::kThinLocked: {
1225 uint32_t thread_id = self->GetThreadId();
1226 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1227 if (owner_thread_id != thread_id) {
Mathieu Chartier61b3cd42016-04-18 11:43:29 -07001228 FailedUnlock(h_obj.Get(), thread_id, owner_thread_id, nullptr);
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001229 return false; // Failure.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001230 } else {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001231 // We own the lock, decrease the recursion count.
1232 LockWord new_lw = LockWord::Default();
1233 if (lock_word.ThinLockCount() != 0) {
1234 uint32_t new_count = lock_word.ThinLockCount() - 1;
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001235 new_lw = LockWord::FromThinLockId(thread_id, new_count, lock_word.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001236 } else {
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001237 new_lw = LockWord::FromDefault(lock_word.GCState());
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001238 }
1239 if (!kUseReadBarrier) {
1240 DCHECK_EQ(new_lw.ReadBarrierState(), 0U);
Hans Boehmb3da36c2016-12-15 13:12:59 -08001241 // TODO: This really only needs memory_order_release, but we currently have
1242 // no way to specify that. In fact there seem to be no legitimate uses of SetLockWord
1243 // with a final argument of true. This slows down x86 and ARMv7, but probably not v8.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001244 h_obj->SetLockWord(new_lw, true);
Andreas Gampe6e759ad2016-05-17 10:13:10 -07001245 AtraceMonitorUnlock();
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001246 // Success!
1247 return true;
1248 } else {
1249 // Use CAS to preserve the read barrier state.
Mathieu Chartier42c2e502018-06-19 12:30:56 -07001250 if (h_obj->CasLockWord(lock_word, new_lw, CASMode::kWeak, std::memory_order_release)) {
Andreas Gampe6e759ad2016-05-17 10:13:10 -07001251 AtraceMonitorUnlock();
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001252 // Success!
1253 return true;
1254 }
1255 }
1256 continue; // Go again.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001257 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001258 }
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001259 case LockWord::kFatLocked: {
1260 Monitor* mon = lock_word.FatLockMonitor();
1261 return mon->Unlock(self);
1262 }
1263 default: {
1264 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Elliott Hughesc1896c92018-11-29 11:33:18 -08001265 UNREACHABLE();
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001266 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001267 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001268 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001269}
1270
Vladimir Markof52d92f2019-03-29 12:33:02 +00001271void Monitor::Wait(Thread* self,
1272 ObjPtr<mirror::Object> obj,
1273 int64_t ms,
1274 int32_t ns,
1275 bool interruptShouldThrow,
1276 ThreadState why) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001277 DCHECK(self != nullptr);
1278 DCHECK(obj != nullptr);
Alex Light77fee872017-09-05 14:51:49 -07001279 StackHandleScope<1> hs(self);
1280 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
1281
1282 Runtime::Current()->GetRuntimeCallbacks()->ObjectWaitStart(h_obj, ms);
Alex Light848574c2017-09-25 16:59:39 -07001283 if (UNLIKELY(self->ObserveAsyncException() || self->IsExceptionPending())) {
Alex Light77fee872017-09-05 14:51:49 -07001284 // See b/65558434 for information on handling of exceptions here.
1285 return;
1286 }
1287
1288 LockWord lock_word = h_obj->GetLockWord(true);
Ian Rogers43c69cc2014-08-15 11:09:28 -07001289 while (lock_word.GetState() != LockWord::kFatLocked) {
1290 switch (lock_word.GetState()) {
1291 case LockWord::kHashCode:
1292 // Fall-through.
1293 case LockWord::kUnlocked:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001294 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
1295 return; // Failure.
Ian Rogers43c69cc2014-08-15 11:09:28 -07001296 case LockWord::kThinLocked: {
1297 uint32_t thread_id = self->GetThreadId();
1298 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1299 if (owner_thread_id != thread_id) {
1300 ThrowIllegalMonitorStateExceptionF("object not locked by thread before wait()");
1301 return; // Failure.
1302 } else {
1303 // We own the lock, inflate to enqueue ourself on the Monitor. May fail spuriously so
1304 // re-load.
Alex Light77fee872017-09-05 14:51:49 -07001305 Inflate(self, self, h_obj.Get(), 0);
1306 lock_word = h_obj->GetLockWord(true);
Ian Rogers43c69cc2014-08-15 11:09:28 -07001307 }
1308 break;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001309 }
Ian Rogers43c69cc2014-08-15 11:09:28 -07001310 case LockWord::kFatLocked: // Unreachable given the loop condition above. Fall-through.
1311 default: {
1312 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Elliott Hughesc1896c92018-11-29 11:33:18 -08001313 UNREACHABLE();
Ian Rogers43c69cc2014-08-15 11:09:28 -07001314 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001315 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001316 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001317 Monitor* mon = lock_word.FatLockMonitor();
1318 mon->Wait(self, ms, ns, interruptShouldThrow, why);
Elliott Hughes5f791332011-09-15 17:45:30 -07001319}
1320
Vladimir Markof52d92f2019-03-29 12:33:02 +00001321void Monitor::DoNotify(Thread* self, ObjPtr<mirror::Object> obj, bool notify_all) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001322 DCHECK(self != nullptr);
1323 DCHECK(obj != nullptr);
1324 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001325 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001326 case LockWord::kHashCode:
1327 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001328 case LockWord::kUnlocked:
Ian Rogers6d0b13e2012-02-07 09:25:29 -08001329 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001330 return; // Failure.
1331 case LockWord::kThinLocked: {
1332 uint32_t thread_id = self->GetThreadId();
1333 uint32_t owner_thread_id = lock_word.ThinLockOwner();
1334 if (owner_thread_id != thread_id) {
1335 ThrowIllegalMonitorStateExceptionF("object not locked by thread before notify()");
1336 return; // Failure.
1337 } else {
1338 // We own the lock but there's no Monitor and therefore no waiters.
1339 return; // Success.
1340 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001341 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001342 case LockWord::kFatLocked: {
1343 Monitor* mon = lock_word.FatLockMonitor();
1344 if (notify_all) {
1345 mon->NotifyAll(self);
1346 } else {
1347 mon->Notify(self);
1348 }
1349 return; // Success.
1350 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001351 default: {
1352 LOG(FATAL) << "Invalid monitor state " << lock_word.GetState();
Elliott Hughesc1896c92018-11-29 11:33:18 -08001353 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001354 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001355 }
1356}
1357
Vladimir Markof52d92f2019-03-29 12:33:02 +00001358uint32_t Monitor::GetLockOwnerThreadId(ObjPtr<mirror::Object> obj) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001359 DCHECK(obj != nullptr);
1360 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001361 switch (lock_word.GetState()) {
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001362 case LockWord::kHashCode:
1363 // Fall-through.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001364 case LockWord::kUnlocked:
1365 return ThreadList::kInvalidThreadId;
1366 case LockWord::kThinLocked:
1367 return lock_word.ThinLockOwner();
1368 case LockWord::kFatLocked: {
1369 Monitor* mon = lock_word.FatLockMonitor();
1370 return mon->GetOwnerThreadId();
Elliott Hughes5f791332011-09-15 17:45:30 -07001371 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001372 default: {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001373 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001374 UNREACHABLE();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001375 }
Elliott Hughes5f791332011-09-15 17:45:30 -07001376 }
1377}
1378
Andreas Gampef3ebcce2017-12-11 20:40:23 -08001379ThreadState Monitor::FetchState(const Thread* thread,
Vladimir Markof52d92f2019-03-29 12:33:02 +00001380 /* out */ ObjPtr<mirror::Object>* monitor_object,
Andreas Gampef3ebcce2017-12-11 20:40:23 -08001381 /* out */ uint32_t* lock_owner_tid) {
1382 DCHECK(monitor_object != nullptr);
1383 DCHECK(lock_owner_tid != nullptr);
1384
1385 *monitor_object = nullptr;
1386 *lock_owner_tid = ThreadList::kInvalidThreadId;
1387
1388 ThreadState state = thread->GetState();
1389
1390 switch (state) {
1391 case kWaiting:
1392 case kTimedWaiting:
1393 case kSleeping:
1394 {
1395 Thread* self = Thread::Current();
1396 MutexLock mu(self, *thread->GetWaitMutex());
1397 Monitor* monitor = thread->GetWaitMonitor();
1398 if (monitor != nullptr) {
1399 *monitor_object = monitor->GetObject();
Ian Rogersd803bc72014-04-01 15:33:03 -07001400 }
1401 }
Andreas Gampef3ebcce2017-12-11 20:40:23 -08001402 break;
1403
1404 case kBlocked:
1405 case kWaitingForLockInflation:
1406 {
Vladimir Markof52d92f2019-03-29 12:33:02 +00001407 ObjPtr<mirror::Object> lock_object = thread->GetMonitorEnterObject();
Andreas Gampef3ebcce2017-12-11 20:40:23 -08001408 if (lock_object != nullptr) {
1409 if (kUseReadBarrier && Thread::Current()->GetIsGcMarking()) {
1410 // We may call Thread::Dump() in the middle of the CC thread flip and this thread's stack
1411 // may have not been flipped yet and "pretty_object" may be a from-space (stale) ref, in
1412 // which case the GetLockOwnerThreadId() call below will crash. So explicitly mark/forward
1413 // it here.
Vladimir Markof52d92f2019-03-29 12:33:02 +00001414 lock_object = ReadBarrier::Mark(lock_object.Ptr());
Andreas Gampef3ebcce2017-12-11 20:40:23 -08001415 }
1416 *monitor_object = lock_object;
1417 *lock_owner_tid = lock_object->GetLockOwnerThreadId();
1418 }
Ian Rogersd803bc72014-04-01 15:33:03 -07001419 }
Andreas Gampef3ebcce2017-12-11 20:40:23 -08001420 break;
1421
1422 default:
1423 break;
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001424 }
Andreas Gampef3ebcce2017-12-11 20:40:23 -08001425
1426 return state;
Elliott Hughes8e4aac52011-09-26 17:03:36 -07001427}
1428
Vladimir Markof52d92f2019-03-29 12:33:02 +00001429ObjPtr<mirror::Object> Monitor::GetContendedMonitor(Thread* thread) {
Elliott Hughesf9501702013-01-11 11:22:27 -08001430 // This is used to implement JDWP's ThreadReference.CurrentContendedMonitor, and has a bizarre
1431 // definition of contended that includes a monitor a thread is trying to enter...
Vladimir Markof52d92f2019-03-29 12:33:02 +00001432 ObjPtr<mirror::Object> result = thread->GetMonitorEnterObject();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001433 if (result == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001434 // ...but also a monitor that the thread is waiting on.
Ian Rogersdd7624d2014-03-14 17:43:00 -07001435 MutexLock mu(Thread::Current(), *thread->GetWaitMutex());
1436 Monitor* monitor = thread->GetWaitMonitor();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001437 if (monitor != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001438 result = monitor->GetObject();
Elliott Hughesf9501702013-01-11 11:22:27 -08001439 }
1440 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001441 return result;
Elliott Hughesf9501702013-01-11 11:22:27 -08001442}
1443
Vladimir Markof52d92f2019-03-29 12:33:02 +00001444void Monitor::VisitLocks(StackVisitor* stack_visitor,
1445 void (*callback)(ObjPtr<mirror::Object>, void*),
1446 void* callback_context,
1447 bool abort_on_failure) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001448 ArtMethod* m = stack_visitor->GetMethod();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001449 CHECK(m != nullptr);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001450
1451 // Native methods are an easy special case.
1452 // TODO: use the JNI implementation's table of explicit MonitorEnter calls and dump those too.
1453 if (m->IsNative()) {
1454 if (m->IsSynchronized()) {
Vladimir Marko654f01c2021-05-26 16:40:20 +01001455 DCHECK(!m->IsCriticalNative());
1456 DCHECK(!m->IsFastNative());
1457 ObjPtr<mirror::Object> lock;
1458 if (m->IsStatic()) {
1459 // Static methods synchronize on the declaring class object.
1460 lock = m->GetDeclaringClass();
1461 } else {
1462 // Instance methods synchronize on the `this` object.
1463 // The `this` reference is stored in the first out vreg in the caller's frame.
1464 uint8_t* sp = reinterpret_cast<uint8_t*>(stack_visitor->GetCurrentQuickFrame());
1465 size_t frame_size = stack_visitor->GetCurrentQuickFrameInfo().FrameSizeInBytes();
1466 lock = reinterpret_cast<StackReference<mirror::Object>*>(
1467 sp + frame_size + static_cast<size_t>(kRuntimePointerSize))->AsMirrorPtr();
1468 }
1469 callback(lock, callback_context);
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001470 }
1471 return;
1472 }
1473
jeffhao61f916c2012-10-25 17:48:51 -07001474 // Proxy methods should not be synchronized.
1475 if (m->IsProxyMethod()) {
1476 CHECK(!m->IsSynchronized());
1477 return;
1478 }
1479
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001480 // Is there any reason to believe there's any synchronization in this method?
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001481 CHECK(m->GetCodeItem() != nullptr) << m->PrettyMethod();
David Sehr0225f8e2018-01-31 08:52:24 +00001482 CodeItemDataAccessor accessor(m->DexInstructionData());
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001483 if (accessor.TriesSize() == 0) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001484 return; // No "tries" implies no synchronization, so no held locks to report.
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001485 }
1486
Andreas Gampe760172c2014-08-16 13:41:10 -07001487 // Get the dex pc. If abort_on_failure is false, GetDexPc will not abort in the case it cannot
1488 // find the dex pc, and instead return kDexNoIndex. Then bail out, as it indicates we have an
1489 // inconsistent stack anyways.
1490 uint32_t dex_pc = stack_visitor->GetDexPc(abort_on_failure);
Andreas Gampee2abbc62017-09-15 11:59:26 -07001491 if (!abort_on_failure && dex_pc == dex::kDexNoIndex) {
David Sehr709b0702016-10-13 09:12:37 -07001492 LOG(ERROR) << "Could not find dex_pc for " << m->PrettyMethod();
Andreas Gampe760172c2014-08-16 13:41:10 -07001493 return;
1494 }
1495
Elliott Hughes80537bb2013-01-04 16:37:26 -08001496 // Ask the verifier for the dex pcs of all the monitor-enter instructions corresponding to
1497 // the locks held in this stack frame.
Andreas Gampeaaf0d382017-11-27 14:10:21 -08001498 std::vector<verifier::MethodVerifier::DexLockInfo> monitor_enter_dex_pcs;
Andreas Gampe6cc23ac2018-08-24 15:22:43 -07001499 verifier::MethodVerifier::FindLocksAtDexPc(m,
1500 dex_pc,
1501 &monitor_enter_dex_pcs,
1502 Runtime::Current()->GetTargetSdkVersion());
Andreas Gampeaaf0d382017-11-27 14:10:21 -08001503 for (verifier::MethodVerifier::DexLockInfo& dex_lock_info : monitor_enter_dex_pcs) {
1504 // As a debug check, check that dex PC corresponds to a monitor-enter.
1505 if (kIsDebugBuild) {
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001506 const Instruction& monitor_enter_instruction = accessor.InstructionAt(dex_lock_info.dex_pc);
1507 CHECK_EQ(monitor_enter_instruction.Opcode(), Instruction::MONITOR_ENTER)
Andreas Gampeaaf0d382017-11-27 14:10:21 -08001508 << "expected monitor-enter @" << dex_lock_info.dex_pc << "; was "
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001509 << reinterpret_cast<const void*>(&monitor_enter_instruction);
Andreas Gampeaaf0d382017-11-27 14:10:21 -08001510 }
Elliott Hughes80537bb2013-01-04 16:37:26 -08001511
Andreas Gampeaaf0d382017-11-27 14:10:21 -08001512 // Iterate through the set of dex registers, as the compiler may not have held all of them
1513 // live.
1514 bool success = false;
1515 for (uint32_t dex_reg : dex_lock_info.dex_registers) {
1516 uint32_t value;
Artem Serov2808be82018-12-20 19:15:11 +00001517
1518 // For optimized code we expect the DexRegisterMap to be present - monitor information
1519 // not be optimized out.
Andreas Gampeaaf0d382017-11-27 14:10:21 -08001520 success = stack_visitor->GetVReg(m, dex_reg, kReferenceVReg, &value);
1521 if (success) {
Vladimir Markof52d92f2019-03-29 12:33:02 +00001522 ObjPtr<mirror::Object> o = reinterpret_cast<mirror::Object*>(value);
Andreas Gampeaaf0d382017-11-27 14:10:21 -08001523 callback(o, callback_context);
1524 break;
1525 }
1526 }
1527 DCHECK(success) << "Failed to find/read reference for monitor-enter at dex pc "
1528 << dex_lock_info.dex_pc
1529 << " in method "
1530 << m->PrettyMethod();
1531 if (!success) {
1532 LOG(WARNING) << "Had a lock reported for dex pc " << dex_lock_info.dex_pc
1533 << " but was not able to fetch a corresponding object!";
1534 }
Elliott Hughes08fc03a2012-06-26 17:34:00 -07001535 }
1536}
1537
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001538bool Monitor::IsValidLockWord(LockWord lock_word) {
1539 switch (lock_word.GetState()) {
1540 case LockWord::kUnlocked:
1541 // Nothing to check.
1542 return true;
1543 case LockWord::kThinLocked:
David Srbecky346fd962020-07-27 16:51:00 +01001544 // Basic consistency check of owner.
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001545 return lock_word.ThinLockOwner() != ThreadList::kInvalidThreadId;
1546 case LockWord::kFatLocked: {
1547 // Check the monitor appears in the monitor list.
1548 Monitor* mon = lock_word.FatLockMonitor();
1549 MonitorList* list = Runtime::Current()->GetMonitorList();
1550 MutexLock mu(Thread::Current(), list->monitor_list_lock_);
1551 for (Monitor* list_mon : list->list_) {
1552 if (mon == list_mon) {
1553 return true; // Found our monitor.
1554 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001555 }
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001556 return false; // Fail - unowned monitor in an object.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001557 }
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001558 case LockWord::kHashCode:
1559 return true;
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001560 default:
1561 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -07001562 UNREACHABLE();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001563 }
1564}
1565
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001566bool Monitor::IsLocked() REQUIRES_SHARED(Locks::mutator_lock_) {
Hans Boehm65c18a22020-01-03 23:37:13 +00001567 return GetOwner() != nullptr;
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001568}
1569
Mathieu Chartier74b3c8f2016-04-15 19:11:45 -07001570void Monitor::TranslateLocation(ArtMethod* method,
1571 uint32_t dex_pc,
1572 const char** source_file,
1573 int32_t* line_number) {
jeffhao33dc7712011-11-09 17:54:24 -08001574 // If method is null, location is unknown
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001575 if (method == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001576 *source_file = "";
1577 *line_number = 0;
jeffhao33dc7712011-11-09 17:54:24 -08001578 return;
1579 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001580 *source_file = method->GetDeclaringClassSourceFile();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001581 if (*source_file == nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001582 *source_file = "";
Elliott Hughes12c51e32012-01-17 20:25:05 -08001583 }
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07001584 *line_number = method->GetLineNumFromDexPC(dex_pc);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001585}
1586
1587uint32_t Monitor::GetOwnerThreadId() {
Hans Boehm65c18a22020-01-03 23:37:13 +00001588 // Make sure owner is not deallocated during access.
1589 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
1590 Thread* owner = GetOwner();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001591 if (owner != nullptr) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001592 return owner->GetThreadId();
1593 } else {
1594 return ThreadList::kInvalidThreadId;
1595 }
jeffhao33dc7712011-11-09 17:54:24 -08001596}
1597
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001598MonitorList::MonitorList()
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001599 : allow_new_monitors_(true), monitor_list_lock_("MonitorList lock", kMonitorListLock),
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001600 monitor_add_condition_("MonitorList disallow condition", monitor_list_lock_) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001601}
1602
1603MonitorList::~MonitorList() {
Andreas Gampe74240812014-04-17 10:35:09 -07001604 Thread* self = Thread::Current();
1605 MutexLock mu(self, monitor_list_lock_);
1606 // Release all monitors to the pool.
1607 // TODO: Is it an invariant that *all* open monitors are in the list? Then we could
1608 // clear faster in the pool.
1609 MonitorPool::ReleaseMonitors(self, &list_);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001610}
1611
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001612void MonitorList::DisallowNewMonitors() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001613 CHECK(!kUseReadBarrier);
Ian Rogers50b35e22012-10-04 10:09:15 -07001614 MutexLock mu(Thread::Current(), monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001615 allow_new_monitors_ = false;
1616}
1617
1618void MonitorList::AllowNewMonitors() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -07001619 CHECK(!kUseReadBarrier);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001620 Thread* self = Thread::Current();
1621 MutexLock mu(self, monitor_list_lock_);
1622 allow_new_monitors_ = true;
1623 monitor_add_condition_.Broadcast(self);
1624}
1625
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001626void MonitorList::BroadcastForNewMonitors() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -07001627 Thread* self = Thread::Current();
1628 MutexLock mu(self, monitor_list_lock_);
1629 monitor_add_condition_.Broadcast(self);
1630}
1631
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001632void MonitorList::Add(Monitor* m) {
1633 Thread* self = Thread::Current();
1634 MutexLock mu(self, monitor_list_lock_);
Hiroshi Yamauchif1c6f872017-01-06 12:23:47 -08001635 // CMS needs this to block for concurrent reference processing because an object allocated during
1636 // the GC won't be marked and concurrent reference processing would incorrectly clear the JNI weak
1637 // ref. But CC (kUseReadBarrier == true) doesn't because of the to-space invariant.
1638 while (!kUseReadBarrier && UNLIKELY(!allow_new_monitors_)) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -07001639 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
1640 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -08001641 self->CheckEmptyCheckpointFromWeakRefAccess(&monitor_list_lock_);
Mathieu Chartierc11d9b82013-09-19 10:01:59 -07001642 monitor_add_condition_.WaitHoldingLocks(self);
1643 }
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001644 list_.push_front(m);
1645}
1646
Mathieu Chartier97509952015-07-13 14:35:43 -07001647void MonitorList::SweepMonitorList(IsMarkedVisitor* visitor) {
Andreas Gampe74240812014-04-17 10:35:09 -07001648 Thread* self = Thread::Current();
1649 MutexLock mu(self, monitor_list_lock_);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001650 for (auto it = list_.begin(); it != list_.end(); ) {
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001651 Monitor* m = *it;
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001652 // Disable the read barrier in GetObject() as this is called by GC.
Vladimir Markof52d92f2019-03-29 12:33:02 +00001653 ObjPtr<mirror::Object> obj = m->GetObject<kWithoutReadBarrier>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001654 // The object of a monitor can be null if we have deflated it.
Vladimir Markof52d92f2019-03-29 12:33:02 +00001655 ObjPtr<mirror::Object> new_obj = obj != nullptr ? visitor->IsMarked(obj.Ptr()) : nullptr;
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001656 if (new_obj == nullptr) {
1657 VLOG(monitor) << "freeing monitor " << m << " belonging to unmarked object "
Hiroshi Yamauchi4cba0d92014-05-21 21:10:23 -07001658 << obj;
Andreas Gampe74240812014-04-17 10:35:09 -07001659 MonitorPool::ReleaseMonitor(self, m);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001660 it = list_.erase(it);
1661 } else {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001662 m->SetObject(new_obj);
Elliott Hughesc33a32b2011-10-11 18:18:07 -07001663 ++it;
1664 }
1665 }
1666}
1667
Hans Boehm6fe97e02016-05-04 18:35:57 -07001668size_t MonitorList::Size() {
1669 Thread* self = Thread::Current();
1670 MutexLock mu(self, monitor_list_lock_);
1671 return list_.size();
1672}
1673
Mathieu Chartier97509952015-07-13 14:35:43 -07001674class MonitorDeflateVisitor : public IsMarkedVisitor {
1675 public:
1676 MonitorDeflateVisitor() : self_(Thread::Current()), deflate_count_(0) {}
1677
Roland Levillainf73caca2018-08-24 17:19:07 +01001678 mirror::Object* IsMarked(mirror::Object* object) override
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001679 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier97509952015-07-13 14:35:43 -07001680 if (Monitor::Deflate(self_, object)) {
1681 DCHECK_NE(object->GetLockWord(true).GetState(), LockWord::kFatLocked);
1682 ++deflate_count_;
1683 // If we deflated, return null so that the monitor gets removed from the array.
1684 return nullptr;
1685 }
1686 return object; // Monitor was not deflated.
1687 }
1688
1689 Thread* const self_;
1690 size_t deflate_count_;
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001691};
1692
Mathieu Chartier48ab6872014-06-24 11:21:59 -07001693size_t MonitorList::DeflateMonitors() {
Mathieu Chartier97509952015-07-13 14:35:43 -07001694 MonitorDeflateVisitor visitor;
1695 Locks::mutator_lock_->AssertExclusiveHeld(visitor.self_);
1696 SweepMonitorList(&visitor);
1697 return visitor.deflate_count_;
Mathieu Chartier440e4ce2014-03-31 16:36:35 -07001698}
1699
Vladimir Markof52d92f2019-03-29 12:33:02 +00001700MonitorInfo::MonitorInfo(ObjPtr<mirror::Object> obj) : owner_(nullptr), entry_count_(0) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001701 DCHECK(obj != nullptr);
1702 LockWord lock_word = obj->GetLockWord(true);
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001703 switch (lock_word.GetState()) {
1704 case LockWord::kUnlocked:
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001705 // Fall-through.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001706 case LockWord::kForwardingAddress:
1707 // Fall-through.
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001708 case LockWord::kHashCode:
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001709 break;
1710 case LockWord::kThinLocked:
1711 owner_ = Runtime::Current()->GetThreadList()->FindThreadByThreadId(lock_word.ThinLockOwner());
Alex Lightce568642017-09-05 16:54:25 -07001712 DCHECK(owner_ != nullptr) << "Thin-locked without owner!";
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001713 entry_count_ = 1 + lock_word.ThinLockCount();
1714 // Thin locks have no waiters.
1715 break;
1716 case LockWord::kFatLocked: {
1717 Monitor* mon = lock_word.FatLockMonitor();
Hans Boehm65c18a22020-01-03 23:37:13 +00001718 owner_ = mon->owner_.load(std::memory_order_relaxed);
Alex Lightce568642017-09-05 16:54:25 -07001719 // Here it is okay for the owner to be null since we don't reset the LockWord back to
1720 // kUnlocked until we get a GC. In cases where this hasn't happened yet we will have a fat
1721 // lock without an owner.
Hans Boehm65c18a22020-01-03 23:37:13 +00001722 // Neither owner_ nor entry_count_ is touched by threads in "suspended" state, so
1723 // we must see consistent values.
Alex Lightce568642017-09-05 16:54:25 -07001724 if (owner_ != nullptr) {
Hans Boehmd56f7d12019-11-19 06:03:11 +00001725 entry_count_ = 1 + mon->lock_count_;
Alex Lightce568642017-09-05 16:54:25 -07001726 } else {
Hans Boehm65c18a22020-01-03 23:37:13 +00001727 DCHECK_EQ(mon->lock_count_, 0u) << "Monitor is fat-locked without any owner!";
Alex Lightce568642017-09-05 16:54:25 -07001728 }
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001729 for (Thread* waiter = mon->wait_set_; waiter != nullptr; waiter = waiter->GetWaitNext()) {
Ian Rogersd9c4fc92013-10-01 19:45:43 -07001730 waiters_.push_back(waiter);
1731 }
1732 break;
Elliott Hughesf327e072013-01-09 16:01:26 -08001733 }
1734 }
1735}
1736
wangguibo0d290722021-04-24 11:27:06 +08001737void Monitor::MaybeEnableTimeout() {
1738 std::string current_package = Runtime::Current()->GetProcessPackageName();
1739 bool enabled_for_app = android::base::GetBoolProperty("debug.art.monitor.app", false);
1740 if (current_package == "android" || enabled_for_app) {
1741 monitor_lock_.setEnableMonitorTimeout();
1742 monitor_lock_.setMonitorId(monitor_id_);
1743 }
1744}
1745
Elliott Hughes5f791332011-09-15 17:45:30 -07001746} // namespace art